file_path
stringlengths 20
202
| content
stringlengths 9
3.85M
| size
int64 9
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 3.33
100
| max_line_length
int64 8
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
NVIDIA/warp/docs/modules/differentiability.rst | Differentiability
=================
.. currentmodule:: warp
By default, Warp generates a forward and backward (adjoint) version of each kernel definition. The backward version of a kernel can be used
to compute gradients of loss functions that can be back propagated to machine learning frameworks like PyTorch.
Arrays that participate in the chain of computation which require gradients should be created with ``requires_grad=True``, for example::
a = wp.zeros(1024, dtype=wp.vec3, device="cuda", requires_grad=True)
The ``wp.Tape`` class can then be used to record kernel launches, and replay them to compute the gradient of a scalar loss function with respect to the kernel inputs::
tape = wp.Tape()
# forward pass
with tape:
wp.launch(kernel=compute1, inputs=[a, b], device="cuda")
wp.launch(kernel=compute2, inputs=[c, d], device="cuda")
wp.launch(kernel=loss, inputs=[d, l], device="cuda")
# reverse pass
tape.backward(l)
After the backward pass has completed, the gradients with respect to the inputs are available from the ``array.grad`` attribute::
# gradient of loss with respect to input a
print(a.grad)
Note that gradients are accumulated on the participating buffers, so if you wish to reuse the same buffers for multiple backward passes you should first zero the gradients::
tape.zero()
.. note::
Warp uses a source-code transformation approach to auto-differentiation.
In this approach, the backwards pass must keep a record of intermediate values computed during the forward pass.
This imposes some restrictions on what kernels can do and still be differentiable:
* Dynamic loops should not mutate any previously declared local variable. This means the loop must be side-effect free.
A simple way to ensure this is to move the loop body into a separate function.
Static loops that are unrolled at compile time do not have this restriction and can perform any computation.
* Kernels should not overwrite any previously used array values except to perform simple linear add/subtract operations (e.g. via :func:`wp.atomic_add() <atomic_add>`)
.. autoclass:: Tape
:members:
Jacobians
#########
To compute the Jacobian matrix :math:`J\in\mathbb{R}^{m\times n}` of a multi-valued function :math:`f: \mathbb{R}^n \to \mathbb{R}^m`, we can evaluate an entire row of the Jacobian in parallel by finding the Jacobian-vector product :math:`J^\top \mathbf{e}`. The vector :math:`\mathbf{e}\in\mathbb{R}^m` selects the indices in the output buffer to differentiate with respect to.
In Warp, instead of passing a scalar loss buffer to the ``tape.backward()`` method, we pass a dictionary ``grads`` mapping from the function output array to the selection vector :math:`\mathbf{e}` having the same type::
# compute the Jacobian for a function of single output
jacobian = np.empty((output_dim, input_dim), dtype=np.float32)
# record computation
tape = wp.Tape()
with tape:
output_buffer = launch_kernels_to_be_differentiated(input_buffer)
# compute each row of the Jacobian
for output_index in range(output_dim):
# select which row of the Jacobian we want to compute
select_index = np.zeros(output_dim)
select_index[output_index] = 1.0
e = wp.array(select_index, dtype=wp.float32)
# pass input gradients to the output buffer to apply selection
tape.backward(grads={output_buffer: e})
q_grad_i = tape.gradients[input_buffer]
jacobian[output_index, :] = q_grad_i.numpy()
# zero gradient arrays for next row
tape.zero()
When we run simulations independently in parallel, the Jacobian corresponding to the entire system dynamics is a block-diagonal matrix. In this case, we can compute the Jacobian in parallel for all environments by choosing a selection vector that has the output indices active for all environment copies. For example, to get the first rows of the Jacobians of all environments, :math:`\mathbf{e}=[\begin{smallmatrix}1 & 0 & 0 & \dots & 1 & 0 & 0 & \dots\end{smallmatrix}]^\top`, to compute the second rows, :math:`\mathbf{e}=[\begin{smallmatrix}0 & 1 & 0 & \dots & 0 & 1 & 0 & \dots\end{smallmatrix}]^\top`, etc.::
# compute the Jacobian for a function over multiple environments in parallel
jacobians = np.empty((num_envs, output_dim, input_dim), dtype=np.float32)
# record computation
tape = wp.Tape()
with tape:
output_buffer = launch_kernels_to_be_differentiated(input_buffer)
# compute each row of the Jacobian
for output_index in range(output_dim):
# select which row of the Jacobian we want to compute
select_index = np.zeros(output_dim)
select_index[output_index] = 1.0
# assemble selection vector for all environments (can be precomputed)
e = wp.array(np.tile(select_index, num_envs), dtype=wp.float32)
tape.backward(grads={output_buffer: e})
q_grad_i = tape.gradients[input_buffer]
jacobians[:, output_index, :] = q_grad_i.numpy().reshape(num_envs, input_dim)
tape.zero()
Custom Gradient Functions
#########################
Warp supports custom gradient function definitions for user-defined Warp functions.
This allows users to define code that should replace the automatically generated derivatives.
To differentiate a function :math:`h(x) = f(g(x))` that has a nested call to function :math:`g(x)`, the chain rule is evaluated in the automatic differentiation of :math:`h(x)`:
.. math::
h^\prime(x) = f^\prime({\color{green}{\underset{\textrm{replay}}{g(x)}}}) {\color{blue}{\underset{\textrm{grad}}{g^\prime(x)}}}
This implies that a function to be compatible with the autodiff engine needs to provide an implementation of its forward version
:math:`\color{green}{g(x)}`, which we refer to as "replay" function (that matches the original function definition by default),
and its derivative :math:`\color{blue}{g^\prime(x)}`, referred to as "grad".
Both the replay and the grad implementations can be customized by the user. They are defined as follows:
.. list-table:: Customizing the replay and grad versions of function ``myfunc``
:widths: 100
:header-rows: 0
* - Forward Function
* - .. code-block:: python
@wp.func
def myfunc(in1: InType1, ..., inN: InTypeN) -> OutType1, ..., OutTypeM:
return out1, ..., outM
* - Custom Replay Function
* - .. code-block:: python
@wp.func_replay(myfunc)
def replay_myfunc(in1: InType1, ..., inN: InTypeN) -> OutType1, ..., OutTypeM:
# Custom forward computations to be executed in the backward pass of a
# function calling `myfunc` go here
# Ensure the output variables match the original forward definition
return out1, ..., outM
* - Custom Grad Function
* - .. code-block:: python
@wp.func_grad(myfunc)
def adj_myfunc(in1: InType1, ..., inN: InTypeN, adj_out1: OutType1, ..., adj_outM: OutTypeM):
# Custom adjoint code goes here
# Update the partial derivatives for the inputs as follows:
wp.adjoint[in1] += ...
...
wp.adjoint[inN] += ...
.. note:: It is currently not possible to define custom replay or grad functions for functions that
have generic arguments, e.g. ``Any`` or ``wp.array(dtype=Any)``. Replay or grad functions that
themselves use generic arguments are also not yet supported.
Example 1: Custom Grad Function
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
In the following, we define a Warp function ``safe_sqrt`` that computes the square root of a number::
@wp.func
def safe_sqrt(x: float):
return wp.sqrt(x)
To evaluate this function, we define a kernel that applies ``safe_sqrt`` to an array of input values::
@wp.kernel
def run_safe_sqrt(xs: wp.array(dtype=float), output: wp.array(dtype=float)):
i = wp.tid()
output[i] = safe_sqrt(xs[i])
Calling the kernel for an array of values ``[1.0, 2.0, 0.0]`` yields the expected outputs, the gradients are finite except for the zero input::
xs = wp.array([1.0, 2.0, 0.0], dtype=wp.float32, requires_grad=True)
ys = wp.zeros_like(xs)
tape = wp.Tape()
with tape:
wp.launch(run_safe_sqrt, dim=len(xs), inputs=[xs], outputs=[ys])
tape.backward(grads={ys: wp.array(np.ones(len(xs)), dtype=wp.float32)})
print("ys ", ys)
print("xs.grad", xs.grad)
# ys [1. 1.4142135 0. ]
# xs.grad [0.5 0.35355338 inf]
It is often desired to catch nonfinite gradients in the computation graph as they may cause the entire gradient computation to be nonfinite.
To do so, we can define a custom gradient function that replaces the adjoint function for ``safe_sqrt`` which is automatically generated by
decorating the custom gradient code via ``@wp.func_grad(safe_sqrt)``::
@wp.func_grad(safe_sqrt)
def adj_safe_sqrt(x: float, adj_ret: float):
if x > 0.0:
wp.adjoint[x] += 1.0 / (2.0 * wp.sqrt(x)) * adj_ret
.. note:: The function signature of the custom grad code consists of the input arguments of the forward function plus the adjoint variables of the
forward function outputs. To access and modify the partial derivatives of the input arguments, we use the ``wp.adjoint`` dictionary.
The keys of this dictionary are the input arguments of the forward function, and the values are the partial derivatives of the forward function
output with respect to the input argument.
Example 2: Custom Replay Function
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
In the following, we increment an array index in each thread via :func:`wp.atomic_add() <atomic_add>` and compute
the square root of an input array at the incremented index::
@wp.kernel
def test_add(counter: wp.array(dtype=int), input: wp.array(dtype=float), output: wp.array(dtype=float)):
idx = wp.atomic_add(counter, 0, 1)
output[idx] = wp.sqrt(input[idx])
def main():
dim = 16
use_reversible_increment = False
input = wp.array(np.arange(1, dim + 1), dtype=wp.float32, requires_grad=True)
counter = wp.zeros(1, dtype=wp.int32)
thread_ids = wp.zeros(dim, dtype=wp.int32)
output = wp.zeros(dim, dtype=wp.float32, requires_grad=True)
tape = wp.Tape()
with tape:
if use_reversible_increment:
wp.launch(test_add_diff, dim, inputs=[counter, thread_ids, input], outputs=[output])
else:
wp.launch(test_add, dim, inputs=[counter, input], outputs=[output])
print("counter: ", counter.numpy())
print("thread_ids: ", thread_ids.numpy())
print("input: ", input.numpy())
print("output: ", output.numpy())
tape.backward(grads={
output: wp.array(np.ones(dim), dtype=wp.float32)
})
print("input.grad: ", input.grad.numpy())
if __name__ == "__main__":
main()
The output of the above code is:
.. code-block:: js
counter: [8]
thread_ids: [0 0 0 0 0 0 0 0]
input: [1. 2. 3. 4. 5. 6. 7. 8.]
output: [1. 1.4142135 1.7320508 2. 2.236068 2.4494898 2.6457512 2.828427]
input.grad: [4. 0. 0. 0. 0. 0. 0. 0.]
The gradient of the input is incorrect because the backward pass involving the atomic operation ``wp.atomic_add()`` does not know which thread ID corresponds
to which input value.
The index returned by the adjoint of ``wp.atomic_add()`` is always zero so that the gradient the first entry of the input array,
i.e. :math:`\frac{1}{2\sqrt{1}} = 0.5`, is accumulated ``dim`` times (hence ``input.grad[0] == 4.0`` and all other entries zero).
To fix this, we define a new Warp function ``reversible_increment()`` with a custom *replay* definition that stores the thread ID in a separate array::
@wp.func
def reversible_increment(
buf: wp.array(dtype=int),
buf_index: int,
value: int,
thread_values: wp.array(dtype=int),
tid: int
):
next_index = wp.atomic_add(buf, buf_index, value)
# store which thread ID corresponds to which index for the backward pass
thread_values[tid] = next_index
return next_index
@wp.func_replay(reversible_increment)
def replay_reversible_increment(
buf: wp.array(dtype=int),
buf_index: int,
value: int,
thread_values: wp.array(dtype=int),
tid: int
):
return thread_values[tid]
Instead of running ``reversible_increment()``, the custom replay code in ``replay_reversible_increment()`` is now executed
during forward phase in the backward pass of the function calling ``reversible_increment()``.
We first stored the array index to each thread ID in the forward pass, and now we retrieve the array index for each thread ID in the backward pass.
That way, the backward pass can reproduce the same addition operation as in the forward pass with exactly the same operands per thread.
.. warning:: The function signature of the custom replay code must match the forward function signature.
To use our function we write the following kernel::
@wp.kernel
def test_add_diff(
counter: wp.array(dtype=int),
thread_ids: wp.array(dtype=int),
input: wp.array(dtype=float),
output: wp.array(dtype=float)
):
tid = wp.tid()
idx = reversible_increment(counter, 0, 1, thread_ids, tid)
output[idx] = wp.sqrt(input[idx])
Running the ``test_add_diff`` kernel via the previous ``main`` function with ``use_reversible_increment = True``, we now compute correct gradients
for the input array:
.. code-block:: js
counter: [8]
thread_ids: [0 1 2 3 4 5 6 7]
input: [1. 2. 3. 4. 5. 6. 7. 8.]
output: [1. 1.4142135 1.7320508 2. 2.236068 2.4494898 2.6457512 2.828427 ]
input.grad: [0.5 0.35355338 0.28867513 0.25 0.2236068 0.20412414 0.18898225 0.17677669]
Custom Native Functions
#######################
Users may insert native C++/CUDA code in Warp kernels using ``@func_native`` decorated functions.
These accept native code as strings that get compiled after code generation, and are called within ``@wp.kernel`` functions.
For example::
snippet = """
__shared__ int sum[128];
sum[tid] = arr[tid];
__syncthreads();
for (int stride = 64; stride > 0; stride >>= 1) {
if (tid < stride) {
sum[tid] += sum[tid + stride];
}
__syncthreads();
}
if (tid == 0) {
out[0] = sum[0];
}
"""
@wp.func_native(snippet)
def reduce(arr: wp.array(dtype=int), out: wp.array(dtype=int), tid: int):
...
@wp.kernel
def reduce_kernel(arr: wp.array(dtype=int), out: wp.array(dtype=int)):
tid = wp.tid()
reduce(arr, out, tid)
N = 128
x = wp.array(np.arange(N, dtype=int), dtype=int, device=device)
out = wp.zeros(1, dtype=int, device=device)
wp.launch(kernel=reduce_kernel, dim=N, inputs=[x, out], device=device)
Notice the use of shared memory here: the Warp library does not expose shared memory as a feature, but the CUDA compiler will
readily accept the above snippet. This means CUDA features not exposed in Warp are still accessible in Warp scripts.
Warp kernels meant for the CPU won't be able to leverage CUDA features of course, but this same mechanism supports pure C++ snippets as well.
Please bear in mind the following: the thread index in your snippet should be computed in a ``@wp.kernel`` and passed to your snippet,
as in the above example. This means your ``@wp.func_native`` function signature should include the variables used in your snippet,
as well as a thread index of type ``int``. The function body itself should be stubbed with ``...`` (the snippet will be inserted during compilation).
Should you wish to record your native function on the tape and then subsequently rewind the tape, you must include an adjoint snippet
alongside your snippet as an additional input to the decorator, as in the following example::
snippet = """
out[tid] = a * x[tid] + y[tid];
"""
adj_snippet = """
adj_a += x[tid] * adj_out[tid];
adj_x[tid] += a * adj_out[tid];
adj_y[tid] += adj_out[tid];
"""
@wp.func_native(snippet, adj_snippet)
def saxpy(
a: wp.float32,
x: wp.array(dtype=wp.float32),
y: wp.array(dtype=wp.float32),
out: wp.array(dtype=wp.float32),
tid: int,
):
...
@wp.kernel
def saxpy_kernel(
a: wp.float32,
x: wp.array(dtype=wp.float32),
y: wp.array(dtype=wp.float32),
out: wp.array(dtype=wp.float32)
):
tid = wp.tid()
saxpy(a, x, y, out, tid)
N = 128
a = 2.0
x = wp.array(np.arange(N, dtype=np.float32), dtype=wp.float32, device=device, requires_grad=True)
y = wp.zeros_like(x1)
out = wp.array(np.arange(N, dtype=np.float32), dtype=wp.float32, device=device)
adj_out = wp.array(np.ones(N, dtype=np.float32), dtype=wp.float32, device=device)
tape = wp.Tape()
with tape:
wp.launch(kernel=saxpy_kernel, dim=N, inputs=[a, x, y], outputs=[out], device=device)
tape.backward(grads={out: adj_out})
You may also include a custom replay snippet, to be executed as part of the adjoint (see `Custom Gradient Functions`_ for a full explanation).
Consider the following example::
def test_custom_replay_grad():
num_threads = 8
counter = wp.zeros(1, dtype=wp.int32)
thread_values = wp.zeros(num_threads, dtype=wp.int32)
inputs = wp.array(np.arange(num_threads, dtype=np.float32), requires_grad=True)
outputs = wp.zeros_like(inputs)
snippet = """
int next_index = atomicAdd(counter, 1);
thread_values[tid] = next_index;
"""
replay_snippet = ""
@wp.func_native(snippet, replay_snippet=replay_snippet)
def reversible_increment(
counter: wp.array(dtype=int), thread_values: wp.array(dtype=int), tid: int
):
...
@wp.kernel
def run_atomic_add(
input: wp.array(dtype=float),
counter: wp.array(dtype=int),
thread_values: wp.array(dtype=int),
output: wp.array(dtype=float),
):
tid = wp.tid()
reversible_increment(counter, thread_values, tid)
idx = thread_values[tid]
output[idx] = input[idx] ** 2.0
tape = wp.Tape()
with tape:
wp.launch(
run_atomic_add, dim=num_threads, inputs=[inputs, counter, thread_values], outputs=[outputs]
)
tape.backward(grads={outputs: wp.array(np.ones(num_threads, dtype=np.float32))})
By default, ``snippet`` would be called in the backward pass, but in this case, we have a custom replay snippet defined, which is called instead.
In this case, ``replay_snippet`` is a no-op, which is all that we require, since ``thread_values`` are cached in the forward pass.
If we did not have a ``replay_snippet`` defined, ``thread_values`` would be overwritten with counter values that exceed the input array size in the backward pass.
A native snippet may also include a return statement. If this is the case, you must specify the return type in the native function definition, as in the following example::
snippet = """
float sq = x * x;
return sq;
"""
adj_snippet = """
adj_x += 2.f * x * adj_ret;
"""
@wp.func_native(snippet, adj_snippet)
def square(x: float) -> float: ...
@wp.kernel
def square_kernel(input: wp.array(dtype=Any), output: wp.array(dtype=Any)):
tid = wp.tid()
x = input[tid]
output[tid] = square(x)
N = 5
x = wp.array(np.arange(N, dtype=float), dtype=float, requires_grad=True)
y = wp.zeros_like(x)
tape = wp.Tape()
with tape:
wp.launch(kernel=square_kernel, dim=N, inputs=[x, y])
tape.backward(grads={y: wp.ones(N, dtype=float)})
Debugging Gradients
###################
.. note::
We are expanding the debugging section to provide tools to help users debug gradient computations in the next Warp release.
Visualizing Computation Graphs
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Computing gradients via automatic differentiation can be error-prone, where arrays sometimes miss the ``requires_grad`` setting, or the wrong arrays are passed between kernels. To help debug gradient computations, Warp provides a
``tape.visualize()`` method that generates a graph visualization of the kernel launches recorded on the tape in the `GraphViz <https://graphviz.org/>`_ dot format.
The visualization shows how the Warp arrays are used as inputs and outputs of the kernel launches.
Example usage::
import warp as wp
@wp.kernel
def add(a: wp.array(dtype=float), b: wp.array(dtype=float), c: wp.array(dtype=float)):
tid = wp.tid()
c[tid] = a[tid] + b[tid]
tape = wp.Tape()
a = wp.array([2.0], dtype=wp.float32)
b = wp.array([3.0], dtype=wp.float32, requires_grad=True)
c = wp.array([4.0], dtype=wp.float32)
d = c
e = wp.array([5.0], dtype=wp.float32, requires_grad=True)
result = wp.zeros(1, dtype=wp.float32, requires_grad=True)
with tape:
wp.launch(add, dim=1, inputs=[b, e], outputs=[a])
# ScopedTimer registers itself as a scope on the tape
with wp.ScopedTimer("Adder"):
# we can also manually record scopes
tape.record_scope_begin("Custom Scope")
wp.launch(add, dim=1, inputs=[a, b], outputs=[c])
tape.record_scope_end()
wp.launch(add, dim=1, inputs=[d, a], outputs=[result])
tape.visualize(
filename="tape.dot",
array_labels={a: "a", b: "b", c: "c", e: "e", result: "result"},
)
This will generate a file `tape.dot` that can be visualized using the `GraphViz <https://graphviz.org/>`_ toolset:
.. code-block:: bash
dot -Tsvg tape.dot -o tape.svg
The resulting SVG image can be rendered in a web browser:
.. image:: ../img/tape.svg
The graph visualization shows the kernel launches as grey boxes with the ports below them indicating the input and output arguments. Arrays
are shown as ellipses, where gray ellipses indicate arrays that do not require gradients, and green ellipses indicate arrays that do not have ``requires_grad=True``.
In the example above we can see that the array ``c`` does not have its ``requires_grad`` flag set, which means gradients will not be propagated through this path.
.. note::
Arrays can be labeled with custom names using the ``array_labels`` argument to the ``tape.visualize()`` method.
| 22,938 | reStructuredText | 40.183124 | 614 | 0.65276 |
NVIDIA/warp/docs/modules/devices.rst | Devices
=======
Warp assigns unique string aliases to all supported compute devices in the system. There is currently a single CPU device exposed as ``"cpu"``. Each CUDA-capable GPU gets an alias of the form ``"cuda:i"``, where ``i`` is the CUDA device ordinal. This convention should be familiar to users of other popular frameworks like PyTorch.
It is possible to explicitly target a specific device with each Warp API call using the ``device`` argument::
a = wp.zeros(n, device="cpu")
wp.launch(kernel, dim=a.size, inputs=[a], device="cpu")
b = wp.zeros(n, device="cuda:0")
wp.launch(kernel, dim=b.size, inputs=[b], device="cuda:0")
c = wp.zeros(n, device="cuda:1")
wp.launch(kernel, dim=c.size, inputs=[c], device="cuda:1")
.. note::
A Warp CUDA device (``"cuda:i"``) corresponds to the primary CUDA context of device ``i``.
This is compatible with frameworks like PyTorch and other software that uses the CUDA Runtime API.
It makes interoperability easy because GPU resources like memory can be shared with Warp.
.. autoclass:: warp.context.Device
:members:
:exclude-members: init_streams
Default Device
--------------
To simplify writing code, Warp has the concept of **default device**. When the ``device`` argument is omitted from a Warp API call, the default device will be used.
During Warp initialization, the default device is set to be ``"cuda:0"`` if CUDA is available. Otherwise, the default device is ``"cpu"``.
The function ``wp.set_device()`` can be used to change the default device::
wp.set_device("cpu")
a = wp.zeros(n)
wp.launch(kernel, dim=a.size, inputs=[a])
wp.set_device("cuda:0")
b = wp.zeros(n)
wp.launch(kernel, dim=b.size, inputs=[b])
wp.set_device("cuda:1")
c = wp.zeros(n)
wp.launch(kernel, dim=c.size, inputs=[c])
.. note::
For CUDA devices, ``wp.set_device()`` does two things: it sets the Warp default device and it makes the device's CUDA context current. This helps to minimize the number of CUDA context switches in blocks of code targeting a single device.
For PyTorch users, this function is similar to ``torch.cuda.set_device()``. It is still possible to specify a different device in individual API calls, like in this snippet::
# set default device
wp.set_device("cuda:0")
# use default device
a = wp.zeros(n)
# use explicit devices
b = wp.empty(n, device="cpu")
c = wp.empty(n, device="cuda:1")
# use default device
wp.launch(kernel, dim=a.size, inputs=[a])
wp.copy(b, a)
wp.copy(c, a)
Scoped Devices
--------------
Another way to manage the default device is using ``wp.ScopedDevice`` objects. They can be arbitrarily nested and restore the previous default device on exit::
with wp.ScopedDevice("cpu"):
# alloc and launch on "cpu"
a = wp.zeros(n)
wp.launch(kernel, dim=a.size, inputs=[a])
with wp.ScopedDevice("cuda:0"):
# alloc on "cuda:0"
b = wp.zeros(n)
with wp.ScopedDevice("cuda:1"):
# alloc and launch on "cuda:1"
c = wp.zeros(n)
wp.launch(kernel, dim=c.size, inputs=[c])
# launch on "cuda:0"
wp.launch(kernel, dim=b.size, inputs=[b])
.. note::
For CUDA devices, ``wp.ScopedDevice`` makes the device's CUDA context current and restores the previous CUDA context on exit. This is handy when running Warp scripts as part of a bigger pipeline, because it avoids any side effects of changing the CUDA context in the enclosed code.
Example: Using ``wp.ScopedDevice`` with multiple GPUs
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following example shows how to allocate arrays and launch kernels on all available CUDA devices.
.. code:: python
import warp as wp
@wp.kernel
def inc(a: wp.array(dtype=float)):
tid = wp.tid()
a[tid] = a[tid] + 1.0
# get all CUDA devices
devices = wp.get_cuda_devices()
device_count = len(devices)
# number of launches
iters = 1000
# list of arrays, one per device
arrs = []
# loop over all devices
for device in devices:
# use a ScopedDevice to set the target device
with wp.ScopedDevice(device):
# allocate array
a = wp.zeros(250 * 1024 * 1024, dtype=float)
arrs.append(a)
# launch kernels
for _ in range(iters):
wp.launch(inc, dim=a.size, inputs=[a])
# synchronize all devices
wp.synchronize()
# print results
for i in range(device_count):
print(f"{arrs[i].device} -> {arrs[i].numpy()}")
Current CUDA Device
-------------------
Warp uses the device alias ``"cuda"`` to target the current CUDA device. This allows external code to manage the CUDA device on which to execute Warp scripts. It is analogous to the PyTorch ``"cuda"`` device, which should be familiar to Torch users and simplify interoperation.
In this snippet, we use PyTorch to manage the current CUDA device and invoke a Warp kernel on that device::
def example_function():
# create a Torch tensor on the current CUDA device
t = torch.arange(10, dtype=torch.float32, device="cuda")
a = wp.from_torch(t)
# launch a Warp kernel on the current CUDA device
wp.launch(kernel, dim=a.size, inputs=[a], device="cuda")
# use Torch to set the current CUDA device and run example_function() on that device
torch.cuda.set_device(0)
example_function()
# use Torch to change the current CUDA device and re-run example_function() on that device
torch.cuda.set_device(1)
example_function()
.. note::
Using the device alias ``"cuda"`` can be problematic if the code runs in an environment where another part of the code can unpredictably change the CUDA context. Using an explicit CUDA device like ``"cuda:i"`` is recommended to avoid such issues.
Device Synchronization
----------------------
CUDA kernel launches and memory operations can execute asynchronously. This allows for overlapping compute and memory operations on different devices. Warp allows synchronizing the host with outstanding asynchronous operations on a specific device::
wp.synchronize_device("cuda:1")
The ``wp.synchronize_device()`` function offers more fine-grained synchronization than ``wp.synchronize()``, as the latter waits for *all* devices to complete their work.
Custom CUDA Contexts
--------------------
Warp is designed to work with arbitrary CUDA contexts so it can easily integrate into different workflows.
Applications built on the CUDA Runtime API target the *primary context* of each device. The Runtime API hides CUDA context management under the hood. In Warp, device ``"cuda:i"`` represents the primary context of device ``i``, which aligns with the CUDA Runtime API.
Applications built on the CUDA Driver API work with CUDA contexts directly and can create custom CUDA contexts on any device. Custom CUDA contexts can be created with specific affinity or interop features that benefit the application. Warp can work with these CUDA contexts as well.
The special device alias ``"cuda"`` can be used to target the current CUDA context, whether this is a primary or custom context.
In addition, Warp allows registering new device aliases for custom CUDA contexts, so that they can be explicitly targeted by name. If the ``CUcontext`` pointer is available, it can be used to create a new device alias like this::
wp.map_cuda_device("foo", ctypes.c_void_p(context_ptr))
Alternatively, if the custom CUDA context was made current by the application, the pointer can be omitted::
wp.map_cuda_device("foo")
In either case, mapping the custom CUDA context allows us to target the context directly using the assigned alias::
with wp.ScopedDevice("foo"):
a = wp.zeros(n)
wp.launch(kernel, dim=a.size, inputs=[a])
.. _peer_access:
CUDA Peer Access
----------------
CUDA allows direct memory access between different GPUs if the system hardware configuration supports it. Typically, the GPUs should be of the same type and a special interconnect may be required (e.g., NVLINK or PCIe topology).
During initialization, Warp reports whether peer access is supported on multi-GPU systems:
.. code:: text
Warp 0.15.1 initialized:
CUDA Toolkit 11.5, Driver 12.2
Devices:
"cpu" : "x86_64"
"cuda:0" : "NVIDIA L40" (48 GiB, sm_89, mempool enabled)
"cuda:1" : "NVIDIA L40" (48 GiB, sm_89, mempool enabled)
"cuda:2" : "NVIDIA L40" (48 GiB, sm_89, mempool enabled)
"cuda:3" : "NVIDIA L40" (48 GiB, sm_89, mempool enabled)
CUDA peer access:
Supported fully (all-directional)
If the message reports that CUDA peer access is ``Supported fully``, it means that every CUDA device can access every other CUDA device in the system. If it says ``Supported partially``, it will be followed by the access matrix that shows which devices can access each other. If it says ``Not supported``, it means that access is not supported between any devices.
In code, we can check support and enable peer access like this:
.. code:: python
if wp.is_peer_access_supported("cuda:0", "cuda:1"):
wp.set_peer_access_enabled("cuda:0", "cuda:1", True):
This will allow the memory of device ``cuda:0`` to be directly accessed on device ``cuda:1``. Peer access is directional, which means that enabling access to ``cuda:0`` from ``cuda:1`` does not automatically enable access to ``cuda:1`` from ``cuda:0``.
The benefit of enabling peer access is that it allows direct memory transfers (DMA) between the devices. This is generally a faster way to copy data, since otherwise the transfer needs to be done using a CPU staging buffer.
The drawback is that enabling peer access can reduce the performance of allocations and deallocations. Programs that don't rely on peer-to-peer memory transfers should leave this setting disabled.
It's possible to temporarily enable or disable peer access using a scoped manager:
.. code:: python
with wp.ScopedPeerAccess("cuda:0", "cuda:1", True):
...
.. note::
Peer access does not accelerate memory transfers between arrays allocated using the :ref:`stream-ordered memory pool allocators<mempool_allocators>` introduced in Warp 0.14.0. To accelerate memory pool transfers, :ref:`memory pool access<mempool_access>` should be enabled instead.
.. autofunction:: warp.is_peer_access_supported
.. autofunction:: warp.is_peer_access_enabled
.. autofunction:: warp.set_peer_access_enabled
| 10,687 | reStructuredText | 40.913725 | 366 | 0.688126 |
NVIDIA/warp/docs/modules/allocators.rst | Allocators
==========
.. _mempool_allocators:
Stream-Ordered Memory Pool Allocators
-------------------------------------
Introduction
~~~~~~~~~~~~
Warp 0.14.0 added support for `stream-ordered memory pool allocators for CUDA arrays <https://developer.nvidia.com/blog/using-cuda-stream-ordered-memory-allocator-part-1>`_. As of Warp 0.15.0, these allocators are enabled by default on
all CUDA devices that support them. "Stream-ordered memory pool allocator" is quite a mouthful, so let's unpack it one bit at a time.
Whenever you create an array, the memory needs to be allocated on the device:
.. code:: python
a = wp.empty(n, dtype=float, device="cuda:0")
b = wp.zeros(n, dtype=float, device="cuda:0")
c = wp.ones(n, dtype=float, device="cuda:0")
d = wp.full(n, 42.0, dtype=float, device="cuda:0")
Each of the calls above allocates a block of device memory large enough to hold the array and optionally initializes the contents with
the specified values. ``wp.empty()`` is the only function that does not initialize the contents in any way, it just allocates the memory.
Memory pool allocators grab a block of memory from a larger pool of reserved memory, which is generally faster than asking
the operating system for a brand new chunk of storage. This is an important benefit of these pooled allocators - they are faster.
Stream-ordered means that each allocation is scheduled on a :ref:`CUDA stream<streams>`, which represents a sequence of instructions that execute in order on the GPU. The main benefit is that it allows memory to be allocated in CUDA graphs, which was previously not possible:
.. code:: python
with wp.ScopedCapture() as capture:
a = wp.zeros(n, dtype=float)
wp.launch(kernel, dim=a.size, inputs=[a])
wp.capture_launch(capture.graph)
From now on, we will refer to these allocators as mempool allocators, for short.
Configuration
~~~~~~~~~~~~~
Mempool allocators are a feature of CUDA that is supported on most modern devices and operating systems. However,
there can be systems where they are not supported, such as certain virtual machine setups. Warp is designed with resiliency in mind,
so existing code written prior to the introduction of these new allocators should continue to function regardless of whether they
are supported by the underlying system or not.
Warp's startup message gives the status of these allocators, for example:
.. code-block:: text
Warp 0.15.1 initialized:
CUDA Toolkit 11.5, Driver 12.2
Devices:
"cpu" : "x86_64"
"cuda:0" : "NVIDIA GeForce RTX 4090" (24 GiB, sm_89, mempool enabled)
"cuda:1" : "NVIDIA GeForce RTX 3090" (24 GiB, sm_86, mempool enabled)
Note the ``mempool enabled`` text next to each CUDA device. This means that memory pools are enabled on the device. Whenever you create
an array on that device, it will be allocated using the mempool allocator. If you see ``mempool supported``, it means that memory
pools are supported but were not enabled on startup. If you see ``mempool not supported``, it means that memory pools can't be used
on this device.
There is a configuration flag that controls whether memory pools should be automatically enabled during ``wp.init()``:
.. code:: python
import warp as wp
wp.config.enable_mempools_at_init = False
wp.init()
The flag defaults to ``True``, but can be set to ``False`` if desired. Changing this configuration flag after ``wp.init()`` is called has no effect.
After ``wp.init()``, you can check if the memory pool is enabled on each device like this:
.. code:: python
if wp.is_mempool_enabled("cuda:0"):
...
You can also independently control enablement on each device:
.. code:: python
if wp.is_mempool_supported("cuda:0"):
wp.set_mempool_enabled("cuda:0", True)
It's possible to temporarily enable or disable memory pools using a scoped manager:
.. code:: python
with wp.ScopedMempool("cuda:0", True):
a = wp.zeros(n, dtype=float, device="cuda:0")
with wp.ScopedMempool("cuda:0", False):
b = wp.zeros(n, dtype=float, device="cuda:0")
In the snippet above, array ``a`` will be allocated using the mempool allocator and array ``b`` will be allocated using the default allocator.
In most cases, it shouldn't be necessary to fiddle with these enablement functions, but they are there if you need them.
By default, Warp will enable memory pools on startup if they are supported, which will bring the benefits of improved allocation speed automatically.
Most Warp code should continue to function with or without mempool allocators, with the exception of memory allocations
during graph capture, which will raise an exception if memory pools are not enabled.
.. autofunction:: warp.is_mempool_supported
.. autofunction:: warp.is_mempool_enabled
.. autofunction:: warp.set_mempool_enabled
Allocation Performance
~~~~~~~~~~~~~~~~~~~~~~
Allocating and releasing memory are rather expensive operations that can add overhead to a program. We can't avoid them, since we need to allocate storage for our data somewhere, but there are some simple strategies that can reduce the overall impact of allocations on performance.
Consider the following example:
.. code:: python
for i in range(100):
a = wp.zeros(n, dtype=float, device="cuda:0")
wp.launch(kernel, dim=a.size, inputs=[a], device="cuda:0")
On each iteration of the loop, we allocate an array and run a kernel on the data. This program has 100 allocations and 100 deallocations. When we assign a new value to ``a``, the previous value gets garbage collected by Python, which triggers the deallocation.
Reusing Memory
^^^^^^^^^^^^^^
If the size of the array remains fixed, consider reusing the memory on subsequent iterations. We can allocate the array only once and just re-initialize its contents on each iteration:
.. code:: python
# pre-allocate the array
a = wp.empty(n, dtype=float, device="cuda:0")
for i in range(100):
# reset the contents
a.zero_()
wp.launch(kernel, dim=a.size, inputs=[a], device="cuda:0")
This works well if the array size does not change on each iteration. If the size changes but the upper bound is known, we can still pre-allocate a buffer large enough to store all the elements at any iteration.
.. code:: python
# pre-allocate a big enough buffer
buffer = wp.empty(MAX_N, dtype=float, device="cuda:0")
for i in range(100):
# get a buffer slice of size n <= MAX_N
n = get_size(i)
a = buffer[:n]
# reset the contents
a.zero_()
wp.launch(kernel, dim=a.size, inputs=[a], device="cuda:0")
Reusing memory this way can improve performance, but may also add undesirable complexity to our code. The mempool allocators have a useful feature that can improve allocation performance without modifying our original code in any way.
Release Threshold
^^^^^^^^^^^^^^^^^
The memory pool release threshold determines how much reserved memory the allocator should hold on to before releasing it back to the operating system. For programs that frequently allocate and release memory, setting a higher release threshold can improve the performance of allocations.
By default, the release threshold is set to 0. Setting it to a higher number will reduce the cost of allocations if memory was previously acquired and returned to the pool.
.. code:: python
# set the release threshold to reduce re-allocation overhead
wp.set_mempool_release_threshold("cuda:0", 1024**3)
for i in range(100):
a = wp.zeros(n, dtype=float, device="cuda:0")
wp.launch(kernel, dim=a.size, inputs=[a], device="cuda:0")
Threshold values between 0 and 1 are interpreted as fractions of available memory. For example, 0.5 means half of the device's physical memory and 1.0 means all of the memory. Greater values are interpreted as an absolute number of bytes. For example, 1024**3 means one GiB of memory.
This is a simple optimization that can improve the performance of programs without modifying the existing code in any way.
.. autofunction:: warp.set_mempool_release_threshold
Graph Allocations
~~~~~~~~~~~~~~~~~
Mempool allocators can be used in CUDA graphs, which means that you can capture Warp code that creates arrays:
.. code:: python
with wp.ScopedCapture() as capture:
a = wp.full(n, 42, dtype=float)
wp.capture_launch(capture.graph)
print(a)
Capturing allocations is similar to capturing other operations like kernel launches or memory copies. During capture, the operations don't actually execute, but are recorded. To execute the captured operations, we must launch the graph using :func:`wp.capture_launch() <capture_launch>`. This is important to keep in mind if you want to use an array that was allocated during graph capture. The array doesn't actually exist until the captured graph is launched. In the snippet above, we would get an error if we tried to print the array before calling :func:`wp.capture_launch() <capture_launch>`.
More generally, the ability to allocate memory during graph capture greatly increases the range of code that can be captured in a graph. This includes any code that creates temporary allocations. CUDA graphs can be used to re-run operations with minimal CPU overhead, which can yield dramatic performance improvements.
.. _mempool_access:
Memory Pool Access
~~~~~~~~~~~~~~~~~~
On multi-GPU systems that support :ref:`peer access<peer_access>`, we can enable directly accessing a memory pool from a different device:
.. code:: python
if wp.is_mempool_access_supported("cuda:0", "cuda:1"):
wp.set_mempool_access_enabled("cuda:0", "cuda:1", True):
This will allow the memory pool of device ``cuda:0`` to be directly accessed on device ``cuda:1``. Memory pool access is directional, which means that enabling access to ``cuda:0`` from ``cuda:1`` does not automatically enable access to ``cuda:1`` from ``cuda:0``.
The benefit of enabling memory pool access is that it allows direct memory transfers (DMA) between the devices. This is generally a faster way to copy data, since otherwise the transfer needs to be done using a CPU staging buffer.
The drawback is that enabling memory pool access can slightly reduce the performance of allocations and deallocations. However, for applications that rely on copying memory between devices, there should be a net benefit.
It's possible to temporarily enable or disable memory pool access using a scoped manager:
.. code:: python
with wp.ScopedMempoolAccess("cuda:0", "cuda:1", True):
a0 = wp.zeros(n, dtype=float, device="cuda:0")
a1 = wp.empty(n, dtype=float, device="cuda:1")
# use direct memory transfer between GPUs
wp.copy(a1, a0)
Note that memory pool access only applies to memory allocated using mempool allocators. For memory allocated using default CUDA allocators, we can enable CUDA peer access to get similar benefits.
Because enabling memory pool access can have drawbacks, Warp does not automatically enable it, even if it's supported. Programs that don't require copying data between GPUs are therefore not affected in any way.
.. autofunction:: warp.is_mempool_access_supported
.. autofunction:: warp.is_mempool_access_enabled
.. autofunction:: warp.set_mempool_access_enabled
Limitations
~~~~~~~~~~~
Mempool-to-Mempool Copies Between GPUs During Graph Capture
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Copying data between different GPUs will fail during graph capture if the source and destination are allocated using mempool allocators and mempool access is not enabled between devices. Note that this only applies to capturing mempool-to-mempool copies in a graph; copies done outside of graph capture are not affected. Copies within the same mempool (i.e., same device) are also not affected.
There are two workarounds. If mempool access is supported, you can simply enable mempool access between the devices prior to graph capture, as shown in :ref:`mempool_access`.
If mempool access is not supported, you will need to pre-allocate the arrays involved in the copy using the default CUDA allocators. This will need to be done before capture begins:
.. code:: python
# pre-allocate the arrays with mempools disabled
with wp.ScopedMempool("cuda:0", False):
a0 = wp.zeros(n, dtype=float, device="cuda:0")
with wp.ScopedMempool("cuda:1", False):
a1 = wp.empty(n, dtype=float, device="cuda:1")
with wp.ScopedCapture("cuda:1") as capture:
wp.copy(a1, a0)
wp.capture_launch(capture.graph)
This is due to a limitation in CUDA, which we envision being fixed in the future.
| 12,785 | reStructuredText | 47.615969 | 602 | 0.730153 |
NVIDIA/warp/docs/modules/render.rst | warp.render
===============================
.. currentmodule:: warp.render
The ``warp.render`` module provides a set of renderers that can be used for visualizing scenes involving shapes of various types.
Built on top of these stand-alone renderers, the ``warp.sim.render`` module provides renderers that can be used to visualize scenes directly from ``warp.sim.ModelBuilder`` objects and update them from ``warp.sim.State`` objects.
..
.. toctree::
:maxdepth: 2
Stand-alone renderers
---------------------
The ``OpenGLRenderer`` provides an interactive renderer to play back animations in real time, the ``UsdRenderer`` provides a renderer that exports the scene to a USD file that can be rendered in a renderer of your choice.
.. autoclass:: UsdRenderer
:members:
.. autoclass:: OpenGLRenderer
:members:
Simulation renderers
--------------------
Based on these renderers from ``warp.render``, the ``SimRendererUsd`` (which equals ``SimRenderer``) and ``SimRendererOpenGL`` classes from ``warp.sim.render`` are derived to populate the renderers directly from ``warp.sim.ModelBuilder`` scenes and update them from ``warp.sim.State`` objects.
.. currentmodule:: warp.sim.render
.. autoclass:: SimRendererUsd
:members:
.. autoclass:: SimRendererOpenGL
:members:
| 1,299 | reStructuredText | 32.333333 | 293 | 0.704388 |
NVIDIA/warp/docs/modules/interoperability.rst | Interoperability
================
Warp can interop with other Python-based frameworks such as NumPy through standard interface protocols.
NumPy
-----
Warp arrays may be converted to a NumPy array through the ``warp.array.numpy()`` method. When the Warp array lives on
the ``cpu`` device this will return a zero-copy view onto the underlying Warp allocation. If the array lives on a
``cuda`` device then it will first be copied back to a temporary buffer and copied to NumPy.
Warp CPU arrays also implement the ``__array_interface__`` protocol and so can be used to construct NumPy arrays
directly::
w = wp.array([1.0, 2.0, 3.0], dtype=float, device="cpu")
a = np.array(w)
print(a)
> [1. 2. 3.]
Data type conversion utilities are also available for convenience:
.. code:: python
warp_type = wp.float32
...
numpy_type = wp.dtype_to_numpy(warp_type)
...
a = wp.zeros(n, dtype=warp_type)
b = np.zeros(n, dtype=numpy_type)
To create Warp arrays from NumPy arrays, use :func:`warp.from_numpy`
or pass the NumPy array as the ``data`` argument of the :class:`warp.array` constructor directly.
.. autofunction:: warp.from_numpy
.. autofunction:: warp.dtype_from_numpy
.. autofunction:: warp.dtype_to_numpy
.. _pytorch-interop:
PyTorch
-------
Warp provides helper functions to convert arrays to/from PyTorch::
w = wp.array([1.0, 2.0, 3.0], dtype=float, device="cpu")
# convert to Torch tensor
t = wp.to_torch(w)
# convert from Torch tensor
w = wp.from_torch(t)
These helper functions allow the conversion of Warp arrays to/from PyTorch tensors without copying the underlying data.
At the same time, if available, gradient arrays and tensors are converted to/from PyTorch autograd tensors, allowing the use of Warp arrays
in PyTorch autograd computations.
.. autofunction:: warp.from_torch
.. autofunction:: warp.to_torch
.. autofunction:: warp.device_from_torch
.. autofunction:: warp.device_to_torch
.. autofunction:: warp.dtype_from_torch
.. autofunction:: warp.dtype_to_torch
To convert a PyTorch CUDA stream to a Warp CUDA stream and vice versa, Warp provides the following functions:
.. autofunction:: warp.stream_from_torch
.. autofunction:: warp.stream_to_torch
Example: Optimization using ``warp.from_torch()``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
An example usage of minimizing a loss function over an array of 2D points written in Warp via PyTorch's Adam optimizer
using :func:`warp.from_torch` is as follows::
import warp as wp
import torch
@wp.kernel()
def loss(xs: wp.array(dtype=float, ndim=2), l: wp.array(dtype=float)):
tid = wp.tid()
wp.atomic_add(l, 0, xs[tid, 0] ** 2.0 + xs[tid, 1] ** 2.0)
# indicate requires_grad so that Warp can accumulate gradients in the grad buffers
xs = torch.randn(100, 2, requires_grad=True)
l = torch.zeros(1, requires_grad=True)
opt = torch.optim.Adam([xs], lr=0.1)
wp_xs = wp.from_torch(xs)
wp_l = wp.from_torch(l)
tape = wp.Tape()
with tape:
# record the loss function kernel launch on the tape
wp.launch(loss, dim=len(xs), inputs=[wp_xs], outputs=[wp_l], device=wp_xs.device)
for i in range(500):
tape.zero()
tape.backward(loss=wp_l) # compute gradients
# now xs.grad will be populated with the gradients computed by Warp
opt.step() # update xs (and thereby wp_xs)
# these lines are only needed for evaluating the loss
# (the optimization just needs the gradient, not the loss value)
wp_l.zero_()
wp.launch(loss, dim=len(xs), inputs=[wp_xs], outputs=[wp_l], device=wp_xs.device)
print(f"{i}\tloss: {l.item()}")
Example: Optimization using ``warp.to_torch``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Less code is needed when we declare the optimization variables directly in Warp and use :func:`warp.to_torch` to convert them to PyTorch tensors.
Here, we revisit the same example from above where now only a single conversion to a torch tensor is needed to supply Adam with the optimization variables::
import warp as wp
import numpy as np
import torch
@wp.kernel()
def loss(xs: wp.array(dtype=float, ndim=2), l: wp.array(dtype=float)):
tid = wp.tid()
wp.atomic_add(l, 0, xs[tid, 0] ** 2.0 + xs[tid, 1] ** 2.0)
# initialize the optimization variables in Warp
xs = wp.array(np.random.randn(100, 2), dtype=wp.float32, requires_grad=True)
l = wp.zeros(1, dtype=wp.float32, requires_grad=True)
# just a single wp.to_torch call is needed, Adam optimizes using the Warp array gradients
opt = torch.optim.Adam([wp.to_torch(xs)], lr=0.1)
tape = wp.Tape()
with tape:
wp.launch(loss, dim=len(xs), inputs=[xs], outputs=[l], device=xs.device)
for i in range(500):
tape.zero()
tape.backward(loss=l)
opt.step()
l.zero_()
wp.launch(loss, dim=len(xs), inputs=[xs], outputs=[l], device=xs.device)
print(f"{i}\tloss: {l.numpy()[0]}")
Example: Optimization using ``torch.autograd.function``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
One can insert Warp kernel launches in a PyTorch graph by defining a :class:`torch.autograd.Function` class, which
requires forward and backward functions to be defined. After mapping incoming torch arrays to Warp arrays, a Warp kernel
may be launched in the usual way. In the backward pass, the same kernel's adjoint may be launched by
setting ``adjoint = True`` in :func:`wp.launch() <launch>`. Alternatively, the user may choose to rely on Warp's tape.
In the following example, we demonstrate how Warp may be used to evaluate the Rosenbrock function in an optimization context::
import warp as wp
import numpy as np
import torch
pvec2 = wp.types.vector(length=2, dtype=wp.float32)
# Define the Rosenbrock function
@wp.func
def rosenbrock(x: float, y: float):
return (1.0 - x) ** 2.0 + 100.0 * (y - x**2.0) ** 2.0
@wp.kernel
def eval_rosenbrock(
xs: wp.array(dtype=pvec2),
# outputs
z: wp.array(dtype=float),
):
i = wp.tid()
x = xs[i]
z[i] = rosenbrock(x[0], x[1])
class Rosenbrock(torch.autograd.Function):
@staticmethod
def forward(ctx, xy, num_points):
# ensure Torch operations complete before running Warp
wp.synchronize_device()
ctx.xy = wp.from_torch(xy, dtype=pvec2, requires_grad=True)
ctx.num_points = num_points
# allocate output
ctx.z = wp.zeros(num_points, requires_grad=True)
wp.launch(
kernel=eval_rosenbrock,
dim=ctx.num_points,
inputs=[ctx.xy],
outputs=[ctx.z]
)
# ensure Warp operations complete before returning data to Torch
wp.synchronize_device()
return wp.to_torch(ctx.z)
@staticmethod
def backward(ctx, adj_z):
# ensure Torch operations complete before running Warp
wp.synchronize_device()
# map incoming Torch grads to our output variables
ctx.z.grad = wp.from_torch(adj_z)
wp.launch(
kernel=eval_rosenbrock,
dim=ctx.num_points,
inputs=[ctx.xy],
outputs=[ctx.z],
adj_inputs=[ctx.xy.grad],
adj_outputs=[ctx.z.grad],
adjoint=True
)
# ensure Warp operations complete before returning data to Torch
wp.synchronize_device()
# return adjoint w.r.t. inputs
return (wp.to_torch(ctx.xy.grad), None)
num_points = 1500
learning_rate = 5e-2
torch_device = wp.device_to_torch(wp.get_device())
rng = np.random.default_rng(42)
xy = torch.tensor(rng.normal(size=(num_points, 2)), dtype=torch.float32, requires_grad=True, device=torch_device)
opt = torch.optim.Adam([xy], lr=learning_rate)
for _ in range(10000):
# step
opt.zero_grad()
z = Rosenbrock.apply(xy, num_points)
z.backward(torch.ones_like(z))
opt.step()
# minimum at (1, 1)
xy_np = xy.numpy(force=True)
print(np.mean(xy_np, axis=0))
Note that if Warp code is wrapped in a torch.autograd.function that gets called in ``torch.compile()``, it will automatically
exclude that function from compiler optimizations. If your script uses ``torch.compile()``, we recommend using Pytorch version 2.3.0+,
which has improvements that address this scenario.
CuPy/Numba
----------
Warp GPU arrays support the ``__cuda_array_interface__`` protocol for sharing data with other Python GPU frameworks.
Currently this is one-directional, so that Warp arrays can be used as input to any framework that also supports the
``__cuda_array_interface__`` protocol, but not the other way around.
.. _jax-interop:
JAX
---
Interoperability with JAX arrays is supported through the following methods.
Internally these use the DLPack protocol to exchange data in a zero-copy way with JAX::
warp_array = wp.from_jax(jax_array)
jax_array = wp.to_jax(warp_array)
It may be preferable to use the :ref:`DLPack` protocol directly for better performance and control over stream synchronization behaviour.
.. autofunction:: warp.from_jax
.. autofunction:: warp.to_jax
.. autofunction:: warp.device_from_jax
.. autofunction:: warp.device_to_jax
.. autofunction:: warp.dtype_from_jax
.. autofunction:: warp.dtype_to_jax
Using Warp kernels as JAX primitives
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. note::
This is an experimental feature under development.
Warp kernels can be used as JAX primitives, which can be used to call Warp kernels inside of jitted JAX functions::
import warp as wp
import jax
import jax.numpy as jp
# import experimental feature
from warp.jax_experimental import jax_kernel
@wp.kernel
def triple_kernel(input: wp.array(dtype=float), output: wp.array(dtype=float)):
tid = wp.tid()
output[tid] = 3.0 * input[tid]
# create a Jax primitive from a Warp kernel
jax_triple = jax_kernel(triple_kernel)
# use the Warp kernel in a Jax jitted function
@jax.jit
def f():
x = jp.arange(0, 64, dtype=jp.float32)
return jax_triple(x)
print(f())
Since this is an experimental feature, there are some limitations:
- All kernel arguments must be arrays.
- Kernel launch dimensions are inferred from the shape of the first argument.
- Input arguments are followed by output arguments in the Warp kernel definition.
- There must be at least one input argument and at least one output argument.
- Output shapes must match the launch dimensions (i.e., output shapes must match the shape of the first argument).
- All arrays must be contiguous.
- Only the CUDA backend is supported.
Here is an example of an operation with three inputs and two outputs::
import warp as wp
import jax
import jax.numpy as jp
# import experimental feature
from warp.jax_experimental import jax_kernel
# kernel with multiple inputs and outputs
@wp.kernel
def multiarg_kernel(
# inputs
a: wp.array(dtype=float),
b: wp.array(dtype=float),
c: wp.array(dtype=float),
# outputs
ab: wp.array(dtype=float),
bc: wp.array(dtype=float),
):
tid = wp.tid()
ab[tid] = a[tid] + b[tid]
bc[tid] = b[tid] + c[tid]
# create a Jax primitive from a Warp kernel
jax_multiarg = jax_kernel(multiarg_kernel)
# use the Warp kernel in a Jax jitted function with three inputs and two outputs
@jax.jit
def f():
a = jp.full(64, 1, dtype=jp.float32)
b = jp.full(64, 2, dtype=jp.float32)
c = jp.full(64, 3, dtype=jp.float32)
return jax_multiarg(a, b, c)
x, y = f()
print(x)
print(y)
.. _DLPack:
DLPack
------
Warp supports the DLPack protocol included in the Python Array API standard v2022.12.
See the `Python Specification for DLPack <https://dmlc.github.io/dlpack/latest/python_spec.html>`_ for reference.
The canonical way to import an external array into Warp is using the ``warp.from_dlpack()`` function::
warp_array = wp.from_dlpack(external_array)
The external array can be a PyTorch tensor, Jax array, or any other array type compatible with this version of the DLPack protocol.
For CUDA arrays, this approach requires the producer to perform stream synchronization which ensures that operations on the array
are ordered correctly. The ``warp.from_dlpack()`` function asks the producer to synchronize the current Warp stream on the device where
the array resides. Thus it should be safe to use the array in Warp kernels on that device without any additional synchronization.
The canonical way to export a Warp array to an external framework is to use the ``from_dlpack()`` function in that framework::
jax_array = jax.dlpack.from_dlpack(warp_array)
torch_tensor = torch.utils.dlpack.from_dlpack(warp_array)
For CUDA arrays, this will synchronize the current stream of the consumer framework with the current Warp stream on the array's device.
Thus it should be safe to use the wrapped array in the consumer framework, even if the array was previously used in a Warp kernel
on the device.
Alternatively, arrays can be shared by explicitly creating PyCapsules using a ``to_dlpack()`` function provided by the producer framework.
This approach may be used for older versions of frameworks that do not support the v2022.12 standard::
warp_array1 = wp.from_dlpack(jax.dlpack.to_dlpack(jax_array))
warp_array2 = wp.from_dlpack(torch.utils.dlpack.to_dlpack(torch_tensor))
jax_array = jax.dlpack.from_dlpack(wp.to_dlpack(warp_array))
torch_tensor = torch.utils.dlpack.from_dlpack(wp.to_dlpack(warp_array))
This approach is generally faster because it skips any stream synchronization, but another solution must be used to ensure correct
ordering of operations. In situations where no synchronization is required, using this approach can yield better performance.
This may be a good choice in situations like these:
- The external framework is using the synchronous CUDA default stream.
- Warp and the external framework are using the same CUDA stream.
- Another synchronization mechanism is already in place.
.. autofunction:: warp.from_dlpack
.. autofunction:: warp.to_dlpack
| 14,587 | reStructuredText | 35.108911 | 156 | 0.667923 |
NVIDIA/warp/docs/modules/concurrency.rst | Concurrency
===========
.. currentmodule:: warp
Asynchronous Operations
-----------------------
Kernel Launches
~~~~~~~~~~~~~~~
Kernels launched on a CUDA device are asynchronous with respect to the host (CPU Python thread). Launching a kernel schedules
its execution on the CUDA device, but the :func:`wp.launch() <launch>` function can return before the kernel execution
completes. This allows us to run some CPU computations while the CUDA kernel is executing, which is an
easy way to introduce parallelism into our programs.
.. code:: python
wp.launch(kernel1, dim=n, inputs=[a], device="cuda:0")
# do some CPU work while the CUDA kernel is running
do_cpu_work()
Kernels launched on different CUDA devices can execute concurrently. This can be used to tackle independent sub-tasks in parallel on different GPUs while using the CPU to do other useful work:
.. code:: python
# launch concurrent kernels on different devices
wp.launch(kernel1, dim=n, inputs=[a0], device="cuda:0")
wp.launch(kernel2, dim=n, inputs=[a1], device="cuda:1")
# do CPU work while kernels are running on both GPUs
do_cpu_work()
Launching kernels on the CPU is currently a synchronous operation. In other words, :func:`wp.launch() <launch>` will return only after the kernel has finished executing on the CPU. To run a CUDA kernel and a CPU kernel concurrently, the CUDA kernel should be launched first:
.. code:: python
# schedule a kernel on a CUDA device
wp.launch(kernel1, ..., device="cuda:0")
# run a kernel on the CPU while the CUDA kernel is running
wp.launch(kernel2, ..., device="cpu")
Graph Launches
~~~~~~~~~~~~~~
The concurrency rules for CUDA graph launches are similar to CUDA kernel launches, except that graphs are not available on the CPU.
.. code:: python
# capture work on cuda:0 in a graph
with wp.ScopedCapture(device="cuda:0") as capture0:
do_gpu0_work()
# capture work on cuda:1 in a graph
with wp.ScopedCapture(device="cuda:1") as capture1:
do_gpu1_work()
# launch captured graphs on the respective devices concurrently
wp.capture_launch(capture0.graph)
wp.capture_launch(capture1.graph)
# do some CPU work while the CUDA graphs are running
do_cpu_work()
Array Creation
~~~~~~~~~~~~~~
Creating CUDA arrays is also asynchronous with respect to the host. It involves allocating memory on the device
and initializing it, which is done under the hood using a kernel launch or an asynchronous CUDA memset operation.
.. code:: python
a0 = wp.zeros(n, dtype=float, device="cuda:0")
b0 = wp.ones(n, dtype=float, device="cuda:0")
a1 = wp.empty(n, dtype=float, device="cuda:1")
b1 = wp.full(n, 42.0, dtype=float, device="cuda:1")
In this snippet, arrays ``a0`` and ``b0`` are created on device ``cuda:0`` and arrays ``a1`` and ``b1`` are created
on device ``cuda:1``. The operations on the same device are sequential, but each device executes them independently of the
other device, so they can run concurrently.
Array Copying
~~~~~~~~~~~~~
Copying arrays between devices can also be asynchronous, but there are some details to be aware of.
Copying from host memory to a CUDA device and copying from a CUDA device to host memory is asynchronous only if the host array is pinned.
Pinned memory allows the CUDA driver to use direct memory transfers (DMA), which are generally faster and can be done without involving the CPU.
There are a couple of drawbacks to using pinned memory: allocation and deallocation is usually slower and there are system-specific limits
on how much pinned memory can be allocated on the system. For this reason, Warp CPU arrays are not pinned by default. You can request a pinned
allocation by passing the ``pinned=True`` flag when creating a CPU array. This is a good option for arrays that are used to copy data
between host and device, especially if asynchronous transfers are desired.
.. code:: python
h = wp.zeros(n, dtype=float, device="cpu")
p = wp.zeros(n, dtype=float, device="cpu", pinned=True)
d = wp.zeros(n, dtype=float, device="cuda:0")
# host-to-device copy
wp.copy(d, h) # synchronous
wp.copy(d, p) # asynchronous
# device-to-host copy
wp.copy(h, d) # synchronous
wp.copy(p, d) # asynchronous
# wait for asynchronous operations to complete
wp.synchronize_device("cuda:0")
Copying between CUDA arrays on the same device is always asynchronous with respect to the host, since it does not involve the CPU:
.. code:: python
a = wp.zeros(n, dtype=float, device="cuda:0")
b = wp.empty(n, dtype=float, device="cuda:0")
# asynchronous device-to-device copy
wp.copy(a, b)
# wait for transfer to complete
wp.synchronize_device("cuda:0")
Copying between CUDA arrays on different devices is also asynchronous with respect to the host. Peer-to-peer transfers require
extra care, because CUDA devices are also asynchronous with respect to each other. When copying an array from one GPU to another,
the destination GPU is used to perform the copy, so we need to ensure that prior work on the source GPU completes before the transfer.
.. code:: python
a0 = wp.zeros(n, dtype=float, device="cuda:0")
a1 = wp.empty(n, dtype=float, device="cuda:1")
# wait for outstanding work on the source device to complete to ensure the source array is ready
wp.synchronize_device("cuda:0")
# asynchronous peer-to-peer copy
wp.copy(a1, a0)
# wait for the copy to complete on the destination device
wp.synchronize_device("cuda:1")
Note that peer-to-peer transfers can be accelerated using :ref:`memory pool access <mempool_access>` or :ref:`peer access <peer_access>`, which enables DMA transfers between CUDA devices on supported systems.
.. _streams:
Streams
-------
A CUDA stream is a sequence of operations that execute in order on the GPU. Operations from different streams may run concurrently
and may be interleaved by the device scheduler.
Warp automatically creates a stream for each CUDA device during initialization. This becomes the current stream for the device.
All kernel launches and memory operations issued on that device are placed on the current stream.
Creating Streams
~~~~~~~~~~~~~~~~
A stream is tied to a particular CUDA device. New streams can be created using the :class:`wp.Stream <Stream>` constructor:
.. code:: python
s1 = wp.Stream("cuda:0") # create a stream on a specific CUDA device
s2 = wp.Stream() # create a stream on the default device
If the device parameter is omitted, the default device will be used, which can be managed using :class:`wp.ScopedDevice <ScopedDevice>`.
For interoperation with external code, it is possible to pass a CUDA stream handle to wrap an external stream:
.. code:: python
s3 = wp.Stream("cuda:0", cuda_stream=stream_handle)
The ``cuda_stream`` argument must be a native stream handle (``cudaStream_t`` or ``CUstream``) passed as a Python integer.
This mechanism is used internally for sharing streams with external frameworks like PyTorch or DLPack. The caller is responsible for ensuring
that the external stream does not get destroyed while it is referenced by a ``wp.Stream`` object.
Using Streams
~~~~~~~~~~~~~
Use :class:`wp.ScopedStream <ScopedStream>` to temporarily change the current stream on a device and schedule a sequence of operations on that stream:
.. code:: python
stream = wp.Stream("cuda:0")
with wp.ScopedStream(stream):
a = wp.zeros(n, dtype=float)
b = wp.empty(n, dtype=float)
wp.launch(kernel, dim=n, inputs=[a])
wp.copy(b, a)
Since streams are tied to a particular device, :class:`wp.ScopedStream <ScopedStream>` subsumes the functionality of :class:`wp.ScopedDevice <ScopedDevice>`. That's why we don't need to explicitly specify the ``device`` argument to each of the calls.
An important benefit of streams is that they can be used to overlap compute and data transfer operations on the same device,
which can improve the overall throughput of a program by doing those operations in parallel.
.. code:: python
with wp.ScopedDevice("cuda:0"):
a = wp.zeros(n, dtype=float)
b = wp.empty(n, dtype=float)
c = wp.ones(n, dtype=float, device="cpu", pinned=True)
compute_stream = wp.Stream()
transfer_stream = wp.Stream()
# asynchronous kernel launch on a stream
with wp.ScopedStream(compute_stream)
wp.launch(kernel, dim=a.size, inputs=[a])
# asynchronous host-to-device copy on another stream
with wp.ScopedStream(transfer_stream)
wp.copy(b, c)
The :func:`wp.get_stream() <get_stream>` function can be used to get the current stream on a device:
.. code:: python
s1 = wp.get_stream("cuda:0") # get the current stream on a specific device
s2 = wp.get_stream() # get the current stream on the default device
The :func:`wp.set_stream() <set_stream>` function can be used to set the current stream on a device:
.. code:: python
wp.set_stream(stream, device="cuda:0") # set the stream on a specific device
wp.set_stream(stream) # set the stream on the default device
In general, we recommend using :class:`wp.ScopedStream <ScopedStream>` rather than :func:`wp.set_stream() <set_stream>`.
Synchronization
~~~~~~~~~~~~~~~
The :func:`wp.synchronize_stream() <synchronize_stream>` function can be used to block the host thread until the given stream completes:
.. code:: python
wp.synchronize_stream(stream)
In a program that uses multiple streams, this gives a more fine-grained level of control over synchronization behavior
than :func:`wp.synchronize_device() <synchronize_device>`, which synchronizes all streams on the device.
For example, if a program has multiple compute and transfer streams, the host might only want to wait for one transfer stream
to complete, without waiting for the other streams. By synchronizing only one stream, we allow the others to continue running
concurrently with the host thread.
.. _cuda_events:
Events
~~~~~~
Functions like :func:`wp.synchronize_device() <synchronize_device>` or :func:`wp.synchronize_stream() <synchronize_stream>` block the CPU thread until work completes on a CUDA device, but they're not intended to synchronize multiple CUDA streams with each other.
CUDA events provide a mechanism for device-side synchronization between streams.
This kind of synchronization does not block the host thread, but it allows one stream to wait for work on another stream
to complete.
Like streams, events are tied to a particular device:
.. code:: python
e1 = wp.Event("cuda:0") # create an event on a specific CUDA device
e2 = wp.Event() # create an event on the default device
To wait for a stream to complete some work, we first record the event on that stream. Then we make another stream
wait on that event:
.. code:: python
stream1 = wp.Stream("cuda:0")
stream2 = wp.Stream("cuda:0")
event = wp.Event("cuda:0")
stream1.record_event(event)
stream2.wait_event(event)
Note that when recording events, the event must be from the same device as the recording stream.
When waiting for events, the waiting stream can be from another device. This allows using events to synchronize streams
on different GPUs.
If the ``record_event()`` method is called without an event argument, a temporary event will be created, recorded, and returned:
.. code:: python
event = stream1.record_event()
stream2.wait_event(event)
The ``wait_stream()`` method combines the acts of recording and waiting on an event in one call:
.. code:: python
stream2.wait_stream(stream1)
Warp also provides global functions :func:`wp.record_event() <record_event>`, :func:`wp.wait_event() <wait_event>`, and :func:`wp.wait_stream() <wait_stream>` which operate on the current
stream of the default device:
.. code:: python
wp.record_event(event) # record an event on the current stream
wp.wait_event(event) # make the current stream wait for an event
wp.wait_stream(stream) # make the current stream wait for another stream
These variants are convenient to use inside of :class:`wp.ScopedStream <ScopedStream>` and :class:`wp.ScopedDevice <ScopedDevice>` managers.
Here is a more complete example with a producer stream that copies data into an array and a consumer stream
that uses the array in a kernel:
.. code:: python
with wp.ScopedDevice("cuda:0"):
a = wp.empty(n, dtype=float)
b = wp.ones(n, dtype=float, device="cpu", pinned=True)
producer_stream = wp.Stream()
consumer_stream = wp.Stream()
with wp.ScopedStream(producer_stream)
# asynchronous host-to-device copy
wp.copy(a, b)
# record an event to create a synchronization point for the consumer stream
event = wp.record_event()
# do some unrelated work in the producer stream
do_other_producer_work()
with wp.ScopedStream(consumer_stream)
# do some unrelated work in the consumer stream
do_other_consumer_work()
# wait for the producer copy to complete
wp.wait_event(event)
# consume the array in a kernel
wp.launch(kernel, dim=a.size, inputs=[a])
The function :func:`wp.synchronize_event() <synchronize_event>` can be used to block the host thread until a recorded event completes. This is useful when the host wants to wait for a specific synchronization point on a stream, while allowing subsequent stream operations to continue executing asynchronously.
.. code:: python
with wp.ScopedDevice("cpu"):
# CPU buffers for readback
a_host = wp.empty(N, dtype=float, pinned=True)
b_host = wp.empty(N, dtype=float, pinned=True)
with wp.ScopedDevice("cuda:0"):
stream = wp.get_stream()
# initialize first GPU array
a = wp.full(N, 17, dtype=float)
# asynchronous readback
wp.copy(a_host, a)
# record event
a_event = stream.record_event()
# initialize second GPU array
b = wp.full(N, 42, dtype=float)
# asynchronous readback
wp.copy(b_host, b)
# record event
b_event = stream.record_event()
# wait for first array readback to complete
wp.synchronize_event(a_event)
# process first array on the CPU
assert np.array_equal(a_host.numpy(), np.full(N, fill_value=17.0))
# wait for second array readback to complete
wp.synchronize_event(b_event)
# process second array on the CPU
assert np.array_equal(b_host.numpy(), np.full(N, fill_value=42.0))
CUDA Default Stream
~~~~~~~~~~~~~~~~~~~
Warp avoids using the synchronous CUDA default stream, which is a special stream that synchronizes with all other streams
on the same device. This stream is currently only used during readback operations that are provided for convenience, such as ``array.numpy()`` and ``array.list()``.
.. code:: python
stream1 = wp.Stream("cuda:0")
stream2 = wp.Stream("cuda:0")
with wp.ScopedStream(stream1):
a = wp.zeros(n, dtype=float)
with wp.ScopedStream(stream2):
b = wp.ones(n, dtype=float)
print(a)
print(b)
In the snippet above, there are two arrays that are initialized on different CUDA streams. Printing those arrays triggers
a readback, which is done using the ``array.numpy()`` method. This readback happens on the synchronous CUDA default stream,
which means that no explicit synchronization is required. The reason for this is convenience - printing an array is useful
for debugging purposes, so it's nice not to worry about synchronization.
The drawback of this approach is that the CUDA default stream (and any methods that use it) cannot be used during graph capture.
The regular :func:`wp.copy() <copy>` function should be used to capture readback operations in a graph.
Explicit Streams Arguments
~~~~~~~~~~~~~~~~~~~~~~~~~~
Several Warp functions accept optional ``stream`` arguments. This allows directly specifying the stream without
using a :class:`wp.ScopedStream <ScopedStream>` manager. There are benefits and drawbacks to both approaches, which will be discussed below.
Functions that accept stream arguments directly include :func:`wp.launch() <launch>`, :func:`wp.capture_launch() <capture_launch>`, and :func:`wp.copy() <copy>`.
To launch a kernel on a specific stream:
.. code:: python
wp.launch(kernel, dim=n, inputs=[...], stream=my_stream)
When launching a kernel with an explicit ``stream`` argument, the ``device`` argument should be omitted, since the device is inferred
from the stream. If both ``stream`` and ``device`` are specified, the ``stream`` argument takes precedence.
To launch a graph on a specific stream:
.. code:: python
wp.capture_launch(graph, stream=my_stream)
For both kernel and graph launches, specifying the stream directly can be faster than using :class:`wp.ScopedStream <ScopedStream>`.
While :class:`wp.ScopedStream <ScopedStream>` is useful for scheduling a sequence of operations on a specific stream, there is some overhead
in setting and restoring the current stream on the device. This overhead is negligible for larger workloads,
but performance-sensitive code may benefit from specifying the stream directly instead of using :class:`wp.ScopedStream <ScopedStream>`, especially
for a single kernel or graph launch.
In addition to these performance considerations, specifying the stream directly can be useful when copying arrays between
two CUDA devices. By default, Warp uses the following rules to determine which stream will be used for the copy:
- If the destination array is on a CUDA device, use the current stream on the destination device.
- Otherwise, if the source array is on a CUDA device, use the current stream on the source device.
In the case of peer-to-peer copies, specifying the ``stream`` argument allows overriding these rules, and the copy can
be performed on a stream from any device.
.. code:: python
stream0 = wp.get_stream("cuda:0")
stream1 = wp.get_stream("cuda:1")
a0 = wp.zeros(n, dtype=float, device="cuda:0")
a1 = wp.empty(n, dtype=float, device="cuda:1")
# wait for the destination array to be ready
stream0.wait_stream(stream1)
# use the source device stream to do the copy
wp.copy(a1, a0, stream=stream0)
Notice that we use event synchronization to make the source stream wait for the destination stream prior to the copy.
This is due to the :ref:`stream-ordered memory pool allocators<mempool_allocators>` introduced in Warp 0.14.0. The allocation of the
empty array ``a1`` is scheduled on stream ``stream1``. To avoid use-before-alloc errors, we need to wait until the
allocation completes before using that array on a different stream.
Stream Usage Guidance
~~~~~~~~~~~~~~~~~~~~~
Stream synchronization can be a tricky business, even for experienced CUDA developers. Consider the following code:
.. code:: python
a = wp.zeros(n, dtype=float, device="cuda:0")
s = wp.Stream("cuda:0")
wp.launch(kernel, dim=a.size, inputs=[a], stream=s)
This snippet has a stream synchronization problem that is difficult to detect at first glance.
It's quite possible that the code will work just fine, but it introduces undefined behaviour,
which may lead to incorrect results that manifest only once in a while. The issue is that the kernel is launched
on stream ``s``, which is different than the stream used for creating array ``a``. The array is allocated and
initialized on the current stream of device ``cuda:0``, which means that it might not be ready when stream ``s``
begins executing the kernel that consumes the array.
The solution is to synchronize the streams, which can be done like this:
.. code:: python
a = wp.zeros(n, dtype=float, device="cuda:0")
s = wp.Stream("cuda:0")
# wait for the current stream on cuda:0 to finish initializing the array
s.wait_stream(wp.get_stream("cuda:0"))
wp.launch(kernel, dim=a.size, inputs=[a], stream=s)
The :class:`wp.ScopedStream <ScopedStream>` manager is designed to alleviate this common problem. It synchronizes the new stream with the
previous stream on the device. Its behavior is equivalent to inserting the ``wait_stream()`` call as shown above.
With :class:`wp.ScopedStream <ScopedStream>`, we don't need to explicitly sync the new stream with the previous stream:
.. code:: python
a = wp.zeros(n, dtype=float, device="cuda:0")
s = wp.Stream("cuda:0")
with wp.ScopedStream(s):
wp.launch(kernel, dim=a.size, inputs=[a])
This makes :class:`wp.ScopedStream <ScopedStream>` the recommended way of getting started with streams in Warp. Using explicit stream arguments
might be slightly more performant, but it requires more attention to stream synchronization mechanics.
If you are a stream novice, consider the following trajectory for integrating streams into your Warp programs:
- Level 1: Don't. You don't need to use streams to use Warp. Avoiding streams is a perfectly valid and respectable way to live. Many interesting and sophisticated algorithms can be developed without fancy stream juggling. Often it's better to focus on solving a problem in a simple and elegant way, unencumbered by the vagaries of low-level stream management.
- Level 2: Use :class:`wp.ScopedStream <ScopedStream>`. It helps to avoid some common hard-to-catch issues. There's a little bit of overhead, but it should be negligible if the GPU workloads are large enough. Consider adding streams into your program as a form of targeted optimization, especially if some areas like memory transfers ("feeding the beast") are a known bottleneck. Streams are great for overlapping memory transfers with compute workloads.
- Level 3: Use explicit stream arguments for kernel launches, array copying, etc. This will be the most performant approach that can get you close to the speed of light. You will need to take care of all stream synchronization yourself, but the results can be rewarding in the benchmarks.
.. _synchronization_guidance:
Synchronization Guidance
------------------------
The general rule with synchronization is to use as little of it as possible, but not less.
Excessive synchronization can severely limit the performance of programs. Synchronization means that a stream or thread
is waiting for something else to complete. While it's waiting, it's not doing any useful work, which means that any
outstanding work cannot start until the synchronization point is reached. This limits parallel execution, which is
often important for squeezing the most juice out of the collection of hardware components.
On the other hand, insufficient synchronization can lead to errors or incorrect results if operations execute out-of-order.
A fast program is no good if it can't guarantee correct results.
Host-side Synchronization
~~~~~~~~~~~~~~~~~~~~~~~~~
Host-side synchronization blocks the host thread (Python) until GPU work completes. This is necessary when
you are waiting for some GPU work to complete so that you can access the results on the CPU.
:func:`wp.synchronize() <synchronize>` is the most heavy-handed synchronization function, since it synchronizes all the devices in the system. It is almost never the right function to call if performance is important. However, it can sometimes be useful when debugging synchronization-related issues.
:func:`wp.synchronize_device(device) <synchronize_device>` synchronizes a single device, which is generally better and faster. This synchronizes all the streams on the specified device, including streams created by Warp and those created by any other framework.
:func:`wp.synchronize_stream(stream) <synchronize_stream>` synchronizes a single stream, which is better still. If the program uses multiple streams, you can wait for a specific one to finish without waiting for the others. This is handy if you have a readback stream that is copying data from the GPU to the CPU. You can wait for the transfer to complete and start processing it on the CPU while other streams are still chugging along on the GPU, in parallel with the host code.
:func:`wp.synchronize_event(event) <synchronize_event>` is the most specific host synchronization function. It blocks the host until an event previously recorded on a CUDA stream completes. This can be used to wait for a specific stream synchronization point to be reached, while allowing subsequent operations on that stream to continue asynchronously.
Device-side Synchronization
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Device-side synchronization uses CUDA events to make one stream wait for a synchronization point recorded on another stream (:func:`wp.record_event() <record_event>`, :func:`wp.wait_event() <wait_event>`, :func:`wp.wait_stream() <wait_stream>`).
These functions don't block the host thread, so the CPU can stay busy doing useful work, like preparing the next batch of data
to feed the beast. Events can be used to synchronize streams on the same device or even different CUDA devices, so you can
choreograph very sophisticated multi-stream and multi-device workloads that execute entirely on the available GPUs.
This allows keeping host-side synchronization to a minimum, perhaps only when reading back the final results.
Synchronization and Graph Capture
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A CUDA graph captures a sequence of operations on a CUDA stream that can be replayed multiple times with low overhead.
During capture, certain CUDA functions are not allowed, which includes host-side synchronization functions. Using the synchronous
CUDA default stream is also not allowed. The only form of synchronization allowed in CUDA graphs is event-based synchronization.
A CUDA graph capture must start and end on the same stream, but multiple streams can be used in the middle. This allows CUDA graphs to encompass multiple streams and even multiple GPUs. Events play a crucial role with multi-stream graph capture because they are used to fork and join new streams to the main capture stream, in addition to their regular synchronization duties.
Here's an example of capturing a multi-GPU graph using a stream on each device:
.. code:: python
stream0 = wp.Stream("cuda:0")
stream1 = wp.Stream("cuda:1")
# use stream0 as the main capture stream
with wp.ScopedCapture(stream=stream0) as capture:
# fork stream1, which adds it to the set of streams being captured
stream1.wait_stream(stream0)
# launch a kernel on stream0
wp.launch(kernel, ..., stream=stream0)
# launch a kernel on stream1
wp.launch(kernel, ..., stream=stream1)
# join stream1
stream0.wait_stream(stream1)
# launch the multi-GPU graph, which can execute the captured kernels concurrently
wp.capture_launch(capture.graph)
| 27,125 | reStructuredText | 44.898477 | 482 | 0.727779 |
NVIDIA/warp/docs/modules/fem.rst | warp.fem
=====================
.. currentmodule:: warp.fem
The ``warp.fem`` module is designed to facilitate solving physical systems described as differential
equations. For example, it can solve PDEs for diffusion, convection, fluid flow, and elasticity problems
using finite-element-based (FEM) Galerkin methods, and allows users to quickly experiment with various FEM
formulations and discretization schemes.
Integrands
----------
The core functionality of the FEM toolkit is the ability to integrate constant, linear, and bilinear forms
over various domains and using arbitrary interpolation basis.
The main mechanism is the :py:func:`.integrand` decorator, for instance: ::
@integrand
def linear_form(
s: Sample,
v: Field,
):
return v(s)
@integrand
def diffusion_form(s: Sample, u: Field, v: Field, nu: float):
return nu * wp.dot(
grad(u, s),
grad(v, s),
)
Integrands are normal Warp kernels, meaning any usual Warp function can be used.
However, they accept a few special parameters:
- :class:`.Sample` contains information about the current integration sample point, such as the element index and coordinates in element.
- :class:`.Field` designates an abstract field, which will be replaced at call time by the actual field type: for instance a :class:`.DiscreteField`, :class:`.field.TestField` or :class:`.field.TrialField` defined over an arbitrary :class:`.FunctionSpace`.
A field `u` can be evaluated at a given sample `s` using the :func:`.inner` operator, i.e, ``inner(u, s)``, or as a shortcut using the usual call operator, ``u(s)``.
Several other operators are available, such as :func:`.grad`; see the :ref:`Operators` section.
- :class:`.Domain` designates an abstract integration domain. Several operators are also provided for domains, for example in the example below evaluating the normal at the current sample position: ::
@integrand
def boundary_form(
s: Sample,
domain: Domain,
u: Field,
):
nor = normal(domain, s)
return wp.dot(u(s), nor)
Integrands cannot be used directly with :func:`warp.launch`, but must be called through :func:`.integrate` or :func:`.interpolate` instead.
The root integrand (`integrand` argument passed to :func:`integrate` or :func:`interpolate` call) will automatically get passed :class:`.Sample` and :class:`.Domain` parameters.
:class:`.Field` parameters must be passed as a dictionary in the `fields` argument of the launcher function, and all other standard Warp types arguments must be
passed as a dictionary in the `values` argument of the launcher function, for instance: ::
integrate(diffusion_form, fields={"u": trial, "v": test}, values={"nu": viscosity})
Basic workflow
--------------
The typical steps for solving a linear PDE are as follow:
- Define a :class:`.Geometry` (grid, mesh, etc). At the moment, 2D and 3D regular grids, NanoVDB volumes, and triangle, quadrilateral, tetrahedron and hexahedron unstructured meshes are supported.
- Define one or more :class:`.FunctionSpace`, by equipping the geometry elements with shape functions. See :func:`.make_polynomial_space`. At the moment, continuous/discontinuous Lagrange (:math:`P_{k[d]}, Q_{k[d]}`) and Serendipity (:math:`S_k`) shape functions of order :math:`k \leq 3` are supported.
- Define an integration :class:`.GeometryDomain`, for instance the geometry's cells (:class:`.Cells`) or boundary sides (:class:`.BoundarySides`).
- Integrate linear forms to build the system's right-hand-side. Define a test function over the function space using :func:`.make_test`,
a :class:`.Quadrature` formula (or let the module choose one based on the function space degree), and call :func:`.integrate` with the linear form integrand.
The result is a :class:`warp.array` containing the integration result for each of the function space degrees of freedom.
- Integrate bilinear forms to build the system's left-hand-side. Define a trial function over the function space using :func:`.make_trial`,
then call :func:`.integrate` with the bilinear form integrand.
The result is a :class:`warp.sparse.BsrMatrix` containing the integration result for each pair of test and trial function space degrees of freedom.
Note that the trial and test functions do not have to be defined over the same function space, so that Mixed FEM is supported.
- Solve the resulting linear system using the solver of your choice
The following excerpt from the introductory example ``warp/examples/fem/example_diffusion.py`` outlines this procedure: ::
# Grid geometry
geo = Grid2D(n=50, cell_size=2)
# Domain and function spaces
domain = Cells(geometry=geo)
scalar_space = make_polynomial_space(geo, degree=3)
# Right-hand-side (forcing term)
test = make_test(space=scalar_space, domain=domain)
rhs = integrate(linear_form, fields={"v": test})
# Weakly-imposed boundary conditions on Y sides
boundary = BoundarySides(geo)
bd_test = make_test(space=scalar_space, domain=boundary)
bd_trial = make_trial(space=scalar_space, domain=boundary)
bd_matrix = integrate(y_mass_form, fields={"u": bd_trial, "v": bd_test})
# Diffusion form
trial = make_trial(space=scalar_space, domain=domain)
matrix = integrate(diffusion_form, fields={"u": trial, "v": test}, values={"nu": viscosity})
# Assemble linear system (add diffusion and boundary condition matrices)
bsr_axpy(x=bd_matrix, y=matrix, alpha=boundary_strength, beta=1)
# Solve linear system using Conjugate Gradient
x = wp.zeros_like(rhs)
bsr_cg(matrix, b=rhs, x=x)
.. note::
The :func:`.integrate` function does not check that the passed integrands are actually linear or bilinear forms; it is up to the user to ensure that they are.
To solve non-linear PDEs, one can use an iterative procedure and pass the current value of the studied function :class:`.DiscreteField` argument to the integrand, on which
arbitrary operations are permitted. However, the result of the form must remain linear in the test and trial fields.
Introductory examples
---------------------
``warp.fem`` ships with a list of examples in the ``warp/examples/fem`` directory illustrating common model problems.
- ``example_diffusion.py``: 2D diffusion with homogeneous Neumann and Dirichlet boundary conditions
* ``example_diffusion_3d.py``: 3D variant of the diffusion problem
- ``example_convection_diffusion.py``: 2D convection-diffusion using semi-Lagrangian advection
* ``example_convection_diffusion_dg.py``: 2D convection-diffusion using Discontinuous Galerkin with upwind transport and Symmetric Interior Penalty
- ``example_burgers.py``: 2D inviscid Burgers using Discontinuous Galerkin with upwind transport and slope limiter
- ``example_stokes.py``: 2D incompressible Stokes flow using mixed :math:`P_k/P_{k-1}` or :math:`Q_k/P_{(k-1)d}` elements
- ``example_navier_stokes.py``: 2D Navier-Stokes flow using mixed :math:`P_k/P_{k-1}` elements
- ``example_mixed_elasticity.py``: 2D linear elasticity using mixed continuous/discontinuous :math:`S_k/P_{(k-1)d}` elements
Advanced usages
---------------
High-order (curved) geometries
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
It is possible to convert any :class:`.Geometry` (grids and explicit meshes) into a curved, high-order variant by deforming them
with an arbitrary-order displacement field using the :meth:`~.DiscreteField.make_deformed_geometry` method.
The process looks as follow: ::
# Define a base geometry
base_geo = fem.Grid3D(res=resolution)
# Define a displacement field on the base geometry
deformation_space = fem.make_polynomial_space(base_geo, degree=deformation_degree, dtype=wp.vec3)
deformation_field = deformation_space.make_field()
# Populate the field value by interpolating an expression
fem.interpolate(deformation_field_expr, dest=deformation_field)
# Construct the deformed geometry from the displacement field
deform_geo = deformation_field.make_deformed_geometry()
# Define new function spaces on the deformed geometry
scalar_space = fem.make_polynomial_space(deformed_geo, degree=scalar_space_degree)
See also ``example_deformed_geometry.py`` for a complete example.
Particle-based quadrature
^^^^^^^^^^^^^^^^^^^^^^^^^
The :class:`.PicQuadrature` provides a way to define Particle-In-Cell quadratures from a set or arbitrary particles,
which can be helpful to develop MPM-like methods.
The particles are automatically bucketed to the geometry cells when the quadrature is initialized.
This is illustrated by the ``example_stokes_transfer.py`` and ``example_apic_fluid.py`` examples.
Partitioning
^^^^^^^^^^^^
The FEM toolkit makes it possible to perform integration on a subset of the domain elements,
possibly re-indexing degrees of freedom so that the linear system contains the local ones only.
This is useful for distributed computation (see ``warp/examples/fem/example_diffusion_mgpu.py``), or simply to limit the simulation domain to a subset of active cells (see ``warp/examples/fem/example_stokes_transfer.py``).
A partition of the simulation geometry can be defined using subclasses of :class:`.GeometryPartition`
such as :class:`.LinearGeometryPartition` or :class:`.ExplicitGeometryPartition`.
Function spaces can then be partitioned according to the geometry partition using :func:`.make_space_partition`.
The resulting :class:`.SpacePartition` object allows translating between space-wide and partition-wide node indices,
and differentiating interior, frontier and exterior nodes.
Memory management
^^^^^^^^^^^^^^^^^
Several ``warp.fem`` functions require allocating temporary buffers to perform their computations.
If such functions are called many times in a tight loop, those many allocations and de-allocations may degrade performance.
To overcome this issue, a :class:`.cache.TemporaryStore` object may be created to persist and reuse temporary allocations across calls,
either globally using :func:`set_default_temporary_store` or at a per-function granularity using the corresponding argument.
.. _Operators:
Operators
---------
.. autofunction:: position(domain: Domain, s: Sample)
.. autofunction:: normal(domain: Domain, s: Sample)
.. autofunction:: lookup(domain: Domain, x)
.. autofunction:: measure(domain: Domain, s: Sample)
.. autofunction:: measure_ratio(domain: Domain, s: Sample)
.. autofunction:: deformation_gradient(domain: Domain, s: Sample)
.. autofunction:: degree(f: Field)
.. autofunction:: inner(f: Field, s: Sample)
.. autofunction:: outer(f: Field, s: Sample)
.. autofunction:: grad(f: Field, s: Sample)
.. autofunction:: grad_outer(f: Field, s: Sample)
.. autofunction:: div(f: Field, s: Sample)
.. autofunction:: div_outer(f: Field, s: Sample)
.. autofunction:: at_node(f: Field, s: Sample)
.. autofunction:: D(f: Field, s: Sample)
.. autofunction:: curl(f: Field, s: Sample)
.. autofunction:: jump(f: Field, s: Sample)
.. autofunction:: average(f: Field, s: Sample)
.. autofunction:: grad_jump(f: Field, s: Sample)
.. autofunction:: grad_average(f: Field, s: Sample)
.. autofunction:: warp.fem.operator.operator
Integration
-----------
.. autofunction:: integrate
.. autofunction:: interpolate
.. autofunction:: integrand
.. class:: Sample
Per-sample point context for evaluating fields and related operators in integrands.
.. autoclass:: Field
.. autoclass:: Domain
Geometry
--------
.. autoclass:: Grid2D
:show-inheritance:
.. autoclass:: Trimesh2D
:show-inheritance:
.. autoclass:: Quadmesh2D
:show-inheritance:
.. autoclass:: Grid3D
:show-inheritance:
.. autoclass:: Tetmesh
:show-inheritance:
.. autoclass:: Hexmesh
:show-inheritance:
.. autoclass:: Nanogrid
:show-inheritance:
.. autoclass:: LinearGeometryPartition
.. autoclass:: ExplicitGeometryPartition
.. autoclass:: Cells
:show-inheritance:
.. autoclass:: Sides
:show-inheritance:
.. autoclass:: BoundarySides
:show-inheritance:
.. autoclass:: FrontierSides
:show-inheritance:
.. autoclass:: Polynomial
:members:
.. autoclass:: RegularQuadrature
:show-inheritance:
.. autoclass:: NodalQuadrature
:show-inheritance:
.. autoclass:: ExplicitQuadrature
:show-inheritance:
.. autoclass:: PicQuadrature
:show-inheritance:
Function Spaces
---------------
.. autofunction:: make_polynomial_space
.. autofunction:: make_polynomial_basis_space
.. autofunction:: make_collocated_function_space
.. autofunction:: make_space_partition
.. autofunction:: make_space_restriction
.. autoclass:: ElementBasis
:members:
.. autoclass:: SymmetricTensorMapper
:show-inheritance:
.. autoclass:: SkewSymmetricTensorMapper
:show-inheritance:
.. autoclass:: PointBasisSpace
:show-inheritance:
Fields
------
.. autofunction:: make_test
.. autofunction:: make_trial
.. autofunction:: make_restriction
Boundary Conditions
-------------------
.. autofunction:: normalize_dirichlet_projector
.. autofunction:: project_linear_system
Memory management
-----------------
.. autofunction:: set_default_temporary_store
.. autofunction:: borrow_temporary
.. autofunction:: borrow_temporary_like
Interfaces
----------
Interface classes are not meant to be constructed directly, but can be derived from extend the built-in functionality.
.. autoclass:: Geometry
:members: cell_count, side_count, boundary_side_count
.. autoclass:: GeometryPartition
:members: cell_count, side_count, boundary_side_count, frontier_side_count
.. autoclass:: GeometryDomain
:members: ElementKind, element_kind, dimension, element_count
.. autoclass:: Quadrature
:members: domain, total_point_count
.. autoclass:: FunctionSpace
:members: dtype, topology, geometry, dimension, degree, trace, make_field
.. autoclass:: SpaceTopology
:members: dimension, geometry, node_count, element_node_indices, trace
.. autoclass:: BasisSpace
:members: topology, geometry, node_positions
.. autoclass:: warp.fem.space.shape.ShapeFunction
.. autoclass:: SpacePartition
:members: node_count, owned_node_count, interior_node_count, space_node_indices
.. autoclass:: SpaceRestriction
:members: node_count
.. autoclass:: DofMapper
.. autoclass:: FieldLike
.. autoclass:: DiscreteField
:show-inheritance:
:members: dof_values, trace, make_deformed_geometry
.. autoclass:: warp.fem.field.FieldRestriction
.. autoclass:: warp.fem.field.SpaceField
:show-inheritance:
.. autoclass:: warp.fem.field.TestField
:show-inheritance:
.. autoclass:: warp.fem.field.TrialField
:show-inheritance:
.. autoclass:: TemporaryStore
:members: clear
.. autoclass:: warp.fem.cache.Temporary
:members: array, detach, release
| 14,857 | reStructuredText | 36.520202 | 304 | 0.72417 |
adegirmenci/HBL-ICEbot/qcustomplot.h | /***************************************************************************
** **
** QCustomPlot, an easy to use, modern plotting widget for Qt **
** Copyright (C) 2011-2015 Emanuel Eichhammer **
** **
** This program is free software: you can redistribute it and/or modify **
** it under the terms of the GNU General Public License as published by **
** the Free Software Foundation, either version 3 of the License, or **
** (at your option) any later version. **
** **
** This program is distributed in the hope that it will be useful, **
** but WITHOUT ANY WARRANTY; without even the implied warranty of **
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the **
** GNU General Public License for more details. **
** **
** You should have received a copy of the GNU General Public License **
** along with this program. If not, see http://www.gnu.org/licenses/. **
** **
****************************************************************************
** Author: Emanuel Eichhammer **
** Website/Contact: http://www.qcustomplot.com/ **
** Date: 22.12.15 **
** Version: 1.3.2 **
****************************************************************************/
#ifndef QCUSTOMPLOT_H
#define QCUSTOMPLOT_H
#include <QObject>
#include <QPointer>
#include <QWidget>
#include <QPainter>
#include <QPaintEvent>
#include <QtGui/QMouseEvent>
#include <QPixmap>
#include <QVector>
#include <QString>
#include <QDateTime>
#include <QMultiMap>
#include <QFlags>
#include <QDebug>
#include <QVector2D>
#include <QStack>
#include <QCache>
#include <QMargins>
#include <qmath.h>
#include <limits>
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
# include <qnumeric.h>
# include <QPrinter>
# include <QPrintEngine>
#else
# include <QtNumeric>
# include <QtPrintSupport/QtPrintSupport>
#endif
class QCPPainter;
class QCustomPlot;
class QCPLayerable;
class QCPLayoutElement;
class QCPLayout;
class QCPAxis;
class QCPAxisRect;
class QCPAxisPainterPrivate;
class QCPAbstractPlottable;
class QCPGraph;
class QCPAbstractItem;
class QCPItemPosition;
class QCPLayer;
class QCPPlotTitle;
class QCPLegend;
class QCPAbstractLegendItem;
class QCPColorMap;
class QCPColorScale;
class QCPBars;
/*! \file */
// decl definitions for shared library compilation/usage:
#if defined(QCUSTOMPLOT_COMPILE_LIBRARY)
# define QCP_LIB_DECL Q_DECL_EXPORT
#elif defined(QCUSTOMPLOT_USE_LIBRARY)
# define QCP_LIB_DECL Q_DECL_IMPORT
#else
# define QCP_LIB_DECL
#endif
/*!
The QCP Namespace contains general enums and QFlags used throughout the QCustomPlot library
*/
namespace QCP
{
/*!
Defines the sides of a rectangular entity to which margins can be applied.
\see QCPLayoutElement::setAutoMargins, QCPAxisRect::setAutoMargins
*/
enum MarginSide { msLeft = 0x01 ///< <tt>0x01</tt> left margin
,msRight = 0x02 ///< <tt>0x02</tt> right margin
,msTop = 0x04 ///< <tt>0x04</tt> top margin
,msBottom = 0x08 ///< <tt>0x08</tt> bottom margin
,msAll = 0xFF ///< <tt>0xFF</tt> all margins
,msNone = 0x00 ///< <tt>0x00</tt> no margin
};
Q_DECLARE_FLAGS(MarginSides, MarginSide)
/*!
Defines what objects of a plot can be forcibly drawn antialiased/not antialiased. If an object is
neither forcibly drawn antialiased nor forcibly drawn not antialiased, it is up to the respective
element how it is drawn. Typically it provides a \a setAntialiased function for this.
\c AntialiasedElements is a flag of or-combined elements of this enum type.
\see QCustomPlot::setAntialiasedElements, QCustomPlot::setNotAntialiasedElements
*/
enum AntialiasedElement { aeAxes = 0x0001 ///< <tt>0x0001</tt> Axis base line and tick marks
,aeGrid = 0x0002 ///< <tt>0x0002</tt> Grid lines
,aeSubGrid = 0x0004 ///< <tt>0x0004</tt> Sub grid lines
,aeLegend = 0x0008 ///< <tt>0x0008</tt> Legend box
,aeLegendItems = 0x0010 ///< <tt>0x0010</tt> Legend items
,aePlottables = 0x0020 ///< <tt>0x0020</tt> Main lines of plottables (excluding error bars, see element \ref aeErrorBars)
,aeItems = 0x0040 ///< <tt>0x0040</tt> Main lines of items
,aeScatters = 0x0080 ///< <tt>0x0080</tt> Scatter symbols of plottables (excluding scatter symbols of type ssPixmap)
,aeErrorBars = 0x0100 ///< <tt>0x0100</tt> Error bars
,aeFills = 0x0200 ///< <tt>0x0200</tt> Borders of fills (e.g. under or between graphs)
,aeZeroLine = 0x0400 ///< <tt>0x0400</tt> Zero-lines, see \ref QCPGrid::setZeroLinePen
,aeAll = 0xFFFF ///< <tt>0xFFFF</tt> All elements
,aeNone = 0x0000 ///< <tt>0x0000</tt> No elements
};
Q_DECLARE_FLAGS(AntialiasedElements, AntialiasedElement)
/*!
Defines plotting hints that control various aspects of the quality and speed of plotting.
\see QCustomPlot::setPlottingHints
*/
enum PlottingHint { phNone = 0x000 ///< <tt>0x000</tt> No hints are set
,phFastPolylines = 0x001 ///< <tt>0x001</tt> Graph/Curve lines are drawn with a faster method. This reduces the quality
///< especially of the line segment joins. (Only relevant for solid line pens.)
,phForceRepaint = 0x002 ///< <tt>0x002</tt> causes an immediate repaint() instead of a soft update() when QCustomPlot::replot() is called with parameter \ref QCustomPlot::rpHint.
///< This is set by default to prevent the plot from freezing on fast consecutive replots (e.g. user drags ranges with mouse).
,phCacheLabels = 0x004 ///< <tt>0x004</tt> axis (tick) labels will be cached as pixmaps, increasing replot performance.
};
Q_DECLARE_FLAGS(PlottingHints, PlottingHint)
/*!
Defines the mouse interactions possible with QCustomPlot.
\c Interactions is a flag of or-combined elements of this enum type.
\see QCustomPlot::setInteractions
*/
enum Interaction { iRangeDrag = 0x001 ///< <tt>0x001</tt> Axis ranges are draggable (see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeDragAxes)
,iRangeZoom = 0x002 ///< <tt>0x002</tt> Axis ranges are zoomable with the mouse wheel (see \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes)
,iMultiSelect = 0x004 ///< <tt>0x004</tt> The user can select multiple objects by holding the modifier set by \ref QCustomPlot::setMultiSelectModifier while clicking
,iSelectPlottables = 0x008 ///< <tt>0x008</tt> Plottables are selectable (e.g. graphs, curves, bars,... see QCPAbstractPlottable)
,iSelectAxes = 0x010 ///< <tt>0x010</tt> Axes are selectable (or parts of them, see QCPAxis::setSelectableParts)
,iSelectLegend = 0x020 ///< <tt>0x020</tt> Legends are selectable (or their child items, see QCPLegend::setSelectableParts)
,iSelectItems = 0x040 ///< <tt>0x040</tt> Items are selectable (Rectangles, Arrows, Textitems, etc. see \ref QCPAbstractItem)
,iSelectOther = 0x080 ///< <tt>0x080</tt> All other objects are selectable (e.g. your own derived layerables, the plot title,...)
};
Q_DECLARE_FLAGS(Interactions, Interaction)
/*! \internal
Returns whether the specified \a value is considered an invalid data value for plottables (i.e.
is \e nan or \e +/-inf). This function is used to check data validity upon replots, when the
compiler flag \c QCUSTOMPLOT_CHECK_DATA is set.
*/
inline bool isInvalidData(double value)
{
return qIsNaN(value) || qIsInf(value);
}
/*! \internal
\overload
Checks two arguments instead of one.
*/
inline bool isInvalidData(double value1, double value2)
{
return isInvalidData(value1) || isInvalidData(value2);
}
/*! \internal
Sets the specified \a side of \a margins to \a value
\see getMarginValue
*/
inline void setMarginValue(QMargins &margins, QCP::MarginSide side, int value)
{
switch (side)
{
case QCP::msLeft: margins.setLeft(value); break;
case QCP::msRight: margins.setRight(value); break;
case QCP::msTop: margins.setTop(value); break;
case QCP::msBottom: margins.setBottom(value); break;
case QCP::msAll: margins = QMargins(value, value, value, value); break;
default: break;
}
}
/*! \internal
Returns the value of the specified \a side of \a margins. If \a side is \ref QCP::msNone or
\ref QCP::msAll, returns 0.
\see setMarginValue
*/
inline int getMarginValue(const QMargins &margins, QCP::MarginSide side)
{
switch (side)
{
case QCP::msLeft: return margins.left();
case QCP::msRight: return margins.right();
case QCP::msTop: return margins.top();
case QCP::msBottom: return margins.bottom();
default: break;
}
return 0;
}
} // end of namespace QCP
Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::AntialiasedElements)
Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::PlottingHints)
Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::MarginSides)
Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::Interactions)
class QCP_LIB_DECL QCPScatterStyle
{
Q_GADGET
public:
/*!
Defines the shape used for scatter points.
On plottables/items that draw scatters, the sizes of these visualizations (with exception of
\ref ssDot and \ref ssPixmap) can be controlled with the \ref setSize function. Scatters are
drawn with the pen and brush specified with \ref setPen and \ref setBrush.
*/
Q_ENUMS(ScatterShape)
enum ScatterShape { ssNone ///< no scatter symbols are drawn (e.g. in QCPGraph, data only represented with lines)
,ssDot ///< \enumimage{ssDot.png} a single pixel (use \ref ssDisc or \ref ssCircle if you want a round shape with a certain radius)
,ssCross ///< \enumimage{ssCross.png} a cross
,ssPlus ///< \enumimage{ssPlus.png} a plus
,ssCircle ///< \enumimage{ssCircle.png} a circle
,ssDisc ///< \enumimage{ssDisc.png} a circle which is filled with the pen's color (not the brush as with ssCircle)
,ssSquare ///< \enumimage{ssSquare.png} a square
,ssDiamond ///< \enumimage{ssDiamond.png} a diamond
,ssStar ///< \enumimage{ssStar.png} a star with eight arms, i.e. a combination of cross and plus
,ssTriangle ///< \enumimage{ssTriangle.png} an equilateral triangle, standing on baseline
,ssTriangleInverted ///< \enumimage{ssTriangleInverted.png} an equilateral triangle, standing on corner
,ssCrossSquare ///< \enumimage{ssCrossSquare.png} a square with a cross inside
,ssPlusSquare ///< \enumimage{ssPlusSquare.png} a square with a plus inside
,ssCrossCircle ///< \enumimage{ssCrossCircle.png} a circle with a cross inside
,ssPlusCircle ///< \enumimage{ssPlusCircle.png} a circle with a plus inside
,ssPeace ///< \enumimage{ssPeace.png} a circle, with one vertical and two downward diagonal lines
,ssPixmap ///< a custom pixmap specified by \ref setPixmap, centered on the data point coordinates
,ssCustom ///< custom painter operations are performed per scatter (As QPainterPath, see \ref setCustomPath)
};
QCPScatterStyle();
QCPScatterStyle(ScatterShape shape, double size=6);
QCPScatterStyle(ScatterShape shape, const QColor &color, double size);
QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size);
QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size);
QCPScatterStyle(const QPixmap &pixmap);
QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush=Qt::NoBrush, double size=6);
// getters:
double size() const { return mSize; }
ScatterShape shape() const { return mShape; }
QPen pen() const { return mPen; }
QBrush brush() const { return mBrush; }
QPixmap pixmap() const { return mPixmap; }
QPainterPath customPath() const { return mCustomPath; }
// setters:
void setSize(double size);
void setShape(ScatterShape shape);
void setPen(const QPen &pen);
void setBrush(const QBrush &brush);
void setPixmap(const QPixmap &pixmap);
void setCustomPath(const QPainterPath &customPath);
// non-property methods:
bool isNone() const { return mShape == ssNone; }
bool isPenDefined() const { return mPenDefined; }
void applyTo(QCPPainter *painter, const QPen &defaultPen) const;
void drawShape(QCPPainter *painter, QPointF pos) const;
void drawShape(QCPPainter *painter, double x, double y) const;
protected:
// property members:
double mSize;
ScatterShape mShape;
QPen mPen;
QBrush mBrush;
QPixmap mPixmap;
QPainterPath mCustomPath;
// non-property members:
bool mPenDefined;
};
Q_DECLARE_TYPEINFO(QCPScatterStyle, Q_MOVABLE_TYPE);
class QCP_LIB_DECL QCPPainter : public QPainter
{
Q_GADGET
public:
/*!
Defines special modes the painter can operate in. They disable or enable certain subsets of features/fixes/workarounds,
depending on whether they are wanted on the respective output device.
*/
enum PainterMode { pmDefault = 0x00 ///< <tt>0x00</tt> Default mode for painting on screen devices
,pmVectorized = 0x01 ///< <tt>0x01</tt> Mode for vectorized painting (e.g. PDF export). For example, this prevents some antialiasing fixes.
,pmNoCaching = 0x02 ///< <tt>0x02</tt> Mode for all sorts of exports (e.g. PNG, PDF,...). For example, this prevents using cached pixmap labels
,pmNonCosmetic = 0x04 ///< <tt>0x04</tt> Turns pen widths 0 to 1, i.e. disables cosmetic pens. (A cosmetic pen is always drawn with width 1 pixel in the vector image/pdf viewer, independent of zoom.)
};
Q_FLAGS(PainterMode PainterModes)
Q_DECLARE_FLAGS(PainterModes, PainterMode)
QCPPainter();
QCPPainter(QPaintDevice *device);
~QCPPainter();
// getters:
bool antialiasing() const { return testRenderHint(QPainter::Antialiasing); }
PainterModes modes() const { return mModes; }
// setters:
void setAntialiasing(bool enabled);
void setMode(PainterMode mode, bool enabled=true);
void setModes(PainterModes modes);
// methods hiding non-virtual base class functions (QPainter bug workarounds):
bool begin(QPaintDevice *device);
void setPen(const QPen &pen);
void setPen(const QColor &color);
void setPen(Qt::PenStyle penStyle);
void drawLine(const QLineF &line);
void drawLine(const QPointF &p1, const QPointF &p2) {drawLine(QLineF(p1, p2));}
void save();
void restore();
// non-virtual methods:
void makeNonCosmetic();
protected:
// property members:
PainterModes mModes;
bool mIsAntialiasing;
// non-property members:
QStack<bool> mAntialiasingStack;
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPainter::PainterModes)
class QCP_LIB_DECL QCPLayer : public QObject
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot)
Q_PROPERTY(QString name READ name)
Q_PROPERTY(int index READ index)
Q_PROPERTY(QList<QCPLayerable*> children READ children)
Q_PROPERTY(bool visible READ visible WRITE setVisible)
/// \endcond
public:
QCPLayer(QCustomPlot* parentPlot, const QString &layerName);
~QCPLayer();
// getters:
QCustomPlot *parentPlot() const { return mParentPlot; }
QString name() const { return mName; }
int index() const { return mIndex; }
QList<QCPLayerable*> children() const { return mChildren; }
bool visible() const { return mVisible; }
// setters:
void setVisible(bool visible);
protected:
// property members:
QCustomPlot *mParentPlot;
QString mName;
int mIndex;
QList<QCPLayerable*> mChildren;
bool mVisible;
// non-virtual methods:
void addChild(QCPLayerable *layerable, bool prepend);
void removeChild(QCPLayerable *layerable);
private:
Q_DISABLE_COPY(QCPLayer)
friend class QCustomPlot;
friend class QCPLayerable;
};
class QCP_LIB_DECL QCPLayerable : public QObject
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(bool visible READ visible WRITE setVisible)
Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot)
Q_PROPERTY(QCPLayerable* parentLayerable READ parentLayerable)
Q_PROPERTY(QCPLayer* layer READ layer WRITE setLayer NOTIFY layerChanged)
Q_PROPERTY(bool antialiased READ antialiased WRITE setAntialiased)
/// \endcond
public:
QCPLayerable(QCustomPlot *plot, QString targetLayer=QString(), QCPLayerable *parentLayerable=0);
~QCPLayerable();
// getters:
bool visible() const { return mVisible; }
QCustomPlot *parentPlot() const { return mParentPlot; }
QCPLayerable *parentLayerable() const { return mParentLayerable.data(); }
QCPLayer *layer() const { return mLayer; }
bool antialiased() const { return mAntialiased; }
// setters:
void setVisible(bool on);
Q_SLOT bool setLayer(QCPLayer *layer);
bool setLayer(const QString &layerName);
void setAntialiased(bool enabled);
// introduced virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
// non-property methods:
bool realVisibility() const;
signals:
void layerChanged(QCPLayer *newLayer);
protected:
// property members:
bool mVisible;
QCustomPlot *mParentPlot;
QPointer<QCPLayerable> mParentLayerable;
QCPLayer *mLayer;
bool mAntialiased;
// introduced virtual methods:
virtual void parentPlotInitialized(QCustomPlot *parentPlot);
virtual QCP::Interaction selectionCategory() const;
virtual QRect clipRect() const;
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const = 0;
virtual void draw(QCPPainter *painter) = 0;
// events:
virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged);
virtual void deselectEvent(bool *selectionStateChanged);
// non-property methods:
void initializeParentPlot(QCustomPlot *parentPlot);
void setParentLayerable(QCPLayerable* parentLayerable);
bool moveToLayer(QCPLayer *layer, bool prepend);
void applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const;
private:
Q_DISABLE_COPY(QCPLayerable)
friend class QCustomPlot;
friend class QCPAxisRect;
};
class QCP_LIB_DECL QCPRange
{
public:
double lower, upper;
QCPRange();
QCPRange(double lower, double upper);
bool operator==(const QCPRange& other) const { return lower == other.lower && upper == other.upper; }
bool operator!=(const QCPRange& other) const { return !(*this == other); }
QCPRange &operator+=(const double& value) { lower+=value; upper+=value; return *this; }
QCPRange &operator-=(const double& value) { lower-=value; upper-=value; return *this; }
QCPRange &operator*=(const double& value) { lower*=value; upper*=value; return *this; }
QCPRange &operator/=(const double& value) { lower/=value; upper/=value; return *this; }
friend inline const QCPRange operator+(const QCPRange&, double);
friend inline const QCPRange operator+(double, const QCPRange&);
friend inline const QCPRange operator-(const QCPRange& range, double value);
friend inline const QCPRange operator*(const QCPRange& range, double value);
friend inline const QCPRange operator*(double value, const QCPRange& range);
friend inline const QCPRange operator/(const QCPRange& range, double value);
double size() const;
double center() const;
void normalize();
void expand(const QCPRange &otherRange);
QCPRange expanded(const QCPRange &otherRange) const;
QCPRange sanitizedForLogScale() const;
QCPRange sanitizedForLinScale() const;
bool contains(double value) const;
static bool validRange(double lower, double upper);
static bool validRange(const QCPRange &range);
static const double minRange; //1e-280;
static const double maxRange; //1e280;
};
Q_DECLARE_TYPEINFO(QCPRange, Q_MOVABLE_TYPE);
/* documentation of inline functions */
/*! \fn QCPRange &QCPRange::operator+=(const double& value)
Adds \a value to both boundaries of the range.
*/
/*! \fn QCPRange &QCPRange::operator-=(const double& value)
Subtracts \a value from both boundaries of the range.
*/
/*! \fn QCPRange &QCPRange::operator*=(const double& value)
Multiplies both boundaries of the range by \a value.
*/
/*! \fn QCPRange &QCPRange::operator/=(const double& value)
Divides both boundaries of the range by \a value.
*/
/* end documentation of inline functions */
/*!
Adds \a value to both boundaries of the range.
*/
inline const QCPRange operator+(const QCPRange& range, double value)
{
QCPRange result(range);
result += value;
return result;
}
/*!
Adds \a value to both boundaries of the range.
*/
inline const QCPRange operator+(double value, const QCPRange& range)
{
QCPRange result(range);
result += value;
return result;
}
/*!
Subtracts \a value from both boundaries of the range.
*/
inline const QCPRange operator-(const QCPRange& range, double value)
{
QCPRange result(range);
result -= value;
return result;
}
/*!
Multiplies both boundaries of the range by \a value.
*/
inline const QCPRange operator*(const QCPRange& range, double value)
{
QCPRange result(range);
result *= value;
return result;
}
/*!
Multiplies both boundaries of the range by \a value.
*/
inline const QCPRange operator*(double value, const QCPRange& range)
{
QCPRange result(range);
result *= value;
return result;
}
/*!
Divides both boundaries of the range by \a value.
*/
inline const QCPRange operator/(const QCPRange& range, double value)
{
QCPRange result(range);
result /= value;
return result;
}
class QCP_LIB_DECL QCPMarginGroup : public QObject
{
Q_OBJECT
public:
QCPMarginGroup(QCustomPlot *parentPlot);
~QCPMarginGroup();
// non-virtual methods:
QList<QCPLayoutElement*> elements(QCP::MarginSide side) const { return mChildren.value(side); }
bool isEmpty() const;
void clear();
protected:
// non-property members:
QCustomPlot *mParentPlot;
QHash<QCP::MarginSide, QList<QCPLayoutElement*> > mChildren;
// non-virtual methods:
int commonMargin(QCP::MarginSide side) const;
void addChild(QCP::MarginSide side, QCPLayoutElement *element);
void removeChild(QCP::MarginSide side, QCPLayoutElement *element);
private:
Q_DISABLE_COPY(QCPMarginGroup)
friend class QCPLayoutElement;
};
class QCP_LIB_DECL QCPLayoutElement : public QCPLayerable
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QCPLayout* layout READ layout)
Q_PROPERTY(QRect rect READ rect)
Q_PROPERTY(QRect outerRect READ outerRect WRITE setOuterRect)
Q_PROPERTY(QMargins margins READ margins WRITE setMargins)
Q_PROPERTY(QMargins minimumMargins READ minimumMargins WRITE setMinimumMargins)
Q_PROPERTY(QSize minimumSize READ minimumSize WRITE setMinimumSize)
Q_PROPERTY(QSize maximumSize READ maximumSize WRITE setMaximumSize)
/// \endcond
public:
/*!
Defines the phases of the update process, that happens just before a replot. At each phase,
\ref update is called with the according UpdatePhase value.
*/
enum UpdatePhase { upPreparation ///< Phase used for any type of preparation that needs to be done before margin calculation and layout
,upMargins ///< Phase in which the margins are calculated and set
,upLayout ///< Final phase in which the layout system places the rects of the elements
};
Q_ENUMS(UpdatePhase)
explicit QCPLayoutElement(QCustomPlot *parentPlot=0);
virtual ~QCPLayoutElement();
// getters:
QCPLayout *layout() const { return mParentLayout; }
QRect rect() const { return mRect; }
QRect outerRect() const { return mOuterRect; }
QMargins margins() const { return mMargins; }
QMargins minimumMargins() const { return mMinimumMargins; }
QCP::MarginSides autoMargins() const { return mAutoMargins; }
QSize minimumSize() const { return mMinimumSize; }
QSize maximumSize() const { return mMaximumSize; }
QCPMarginGroup *marginGroup(QCP::MarginSide side) const { return mMarginGroups.value(side, (QCPMarginGroup*)0); }
QHash<QCP::MarginSide, QCPMarginGroup*> marginGroups() const { return mMarginGroups; }
// setters:
void setOuterRect(const QRect &rect);
void setMargins(const QMargins &margins);
void setMinimumMargins(const QMargins &margins);
void setAutoMargins(QCP::MarginSides sides);
void setMinimumSize(const QSize &size);
void setMinimumSize(int width, int height);
void setMaximumSize(const QSize &size);
void setMaximumSize(int width, int height);
void setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group);
// introduced virtual methods:
virtual void update(UpdatePhase phase);
virtual QSize minimumSizeHint() const;
virtual QSize maximumSizeHint() const;
virtual QList<QCPLayoutElement*> elements(bool recursive) const;
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
protected:
// property members:
QCPLayout *mParentLayout;
QSize mMinimumSize, mMaximumSize;
QRect mRect, mOuterRect;
QMargins mMargins, mMinimumMargins;
QCP::MarginSides mAutoMargins;
QHash<QCP::MarginSide, QCPMarginGroup*> mMarginGroups;
// introduced virtual methods:
virtual int calculateAutoMargin(QCP::MarginSide side);
// events:
virtual void mousePressEvent(QMouseEvent *event) {Q_UNUSED(event)}
virtual void mouseMoveEvent(QMouseEvent *event) {Q_UNUSED(event)}
virtual void mouseReleaseEvent(QMouseEvent *event) {Q_UNUSED(event)}
virtual void mouseDoubleClickEvent(QMouseEvent *event) {Q_UNUSED(event)}
virtual void wheelEvent(QWheelEvent *event) {Q_UNUSED(event)}
// reimplemented virtual methods:
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const { Q_UNUSED(painter) }
virtual void draw(QCPPainter *painter) { Q_UNUSED(painter) }
virtual void parentPlotInitialized(QCustomPlot *parentPlot);
private:
Q_DISABLE_COPY(QCPLayoutElement)
friend class QCustomPlot;
friend class QCPLayout;
friend class QCPMarginGroup;
};
class QCP_LIB_DECL QCPLayout : public QCPLayoutElement
{
Q_OBJECT
public:
explicit QCPLayout();
// reimplemented virtual methods:
virtual void update(UpdatePhase phase);
virtual QList<QCPLayoutElement*> elements(bool recursive) const;
// introduced virtual methods:
virtual int elementCount() const = 0;
virtual QCPLayoutElement* elementAt(int index) const = 0;
virtual QCPLayoutElement* takeAt(int index) = 0;
virtual bool take(QCPLayoutElement* element) = 0;
virtual void simplify();
// non-virtual methods:
bool removeAt(int index);
bool remove(QCPLayoutElement* element);
void clear();
protected:
// introduced virtual methods:
virtual void updateLayout();
// non-virtual methods:
void sizeConstraintsChanged() const;
void adoptElement(QCPLayoutElement *el);
void releaseElement(QCPLayoutElement *el);
QVector<int> getSectionSizes(QVector<int> maxSizes, QVector<int> minSizes, QVector<double> stretchFactors, int totalSize) const;
private:
Q_DISABLE_COPY(QCPLayout)
friend class QCPLayoutElement;
};
class QCP_LIB_DECL QCPLayoutGrid : public QCPLayout
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(int rowCount READ rowCount)
Q_PROPERTY(int columnCount READ columnCount)
Q_PROPERTY(QList<double> columnStretchFactors READ columnStretchFactors WRITE setColumnStretchFactors)
Q_PROPERTY(QList<double> rowStretchFactors READ rowStretchFactors WRITE setRowStretchFactors)
Q_PROPERTY(int columnSpacing READ columnSpacing WRITE setColumnSpacing)
Q_PROPERTY(int rowSpacing READ rowSpacing WRITE setRowSpacing)
/// \endcond
public:
explicit QCPLayoutGrid();
virtual ~QCPLayoutGrid();
// getters:
int rowCount() const;
int columnCount() const;
QList<double> columnStretchFactors() const { return mColumnStretchFactors; }
QList<double> rowStretchFactors() const { return mRowStretchFactors; }
int columnSpacing() const { return mColumnSpacing; }
int rowSpacing() const { return mRowSpacing; }
// setters:
void setColumnStretchFactor(int column, double factor);
void setColumnStretchFactors(const QList<double> &factors);
void setRowStretchFactor(int row, double factor);
void setRowStretchFactors(const QList<double> &factors);
void setColumnSpacing(int pixels);
void setRowSpacing(int pixels);
// reimplemented virtual methods:
virtual void updateLayout();
virtual int elementCount() const;
virtual QCPLayoutElement* elementAt(int index) const;
virtual QCPLayoutElement* takeAt(int index);
virtual bool take(QCPLayoutElement* element);
virtual QList<QCPLayoutElement*> elements(bool recursive) const;
virtual void simplify();
virtual QSize minimumSizeHint() const;
virtual QSize maximumSizeHint() const;
// non-virtual methods:
QCPLayoutElement *element(int row, int column) const;
bool addElement(int row, int column, QCPLayoutElement *element);
bool hasElement(int row, int column);
void expandTo(int newRowCount, int newColumnCount);
void insertRow(int newIndex);
void insertColumn(int newIndex);
protected:
// property members:
QList<QList<QCPLayoutElement*> > mElements;
QList<double> mColumnStretchFactors;
QList<double> mRowStretchFactors;
int mColumnSpacing, mRowSpacing;
// non-virtual methods:
void getMinimumRowColSizes(QVector<int> *minColWidths, QVector<int> *minRowHeights) const;
void getMaximumRowColSizes(QVector<int> *maxColWidths, QVector<int> *maxRowHeights) const;
private:
Q_DISABLE_COPY(QCPLayoutGrid)
};
class QCP_LIB_DECL QCPLayoutInset : public QCPLayout
{
Q_OBJECT
public:
/*!
Defines how the placement and sizing is handled for a certain element in a QCPLayoutInset.
*/
enum InsetPlacement { ipFree ///< The element may be positioned/sized arbitrarily, see \ref setInsetRect
,ipBorderAligned ///< The element is aligned to one of the layout sides, see \ref setInsetAlignment
};
explicit QCPLayoutInset();
virtual ~QCPLayoutInset();
// getters:
InsetPlacement insetPlacement(int index) const;
Qt::Alignment insetAlignment(int index) const;
QRectF insetRect(int index) const;
// setters:
void setInsetPlacement(int index, InsetPlacement placement);
void setInsetAlignment(int index, Qt::Alignment alignment);
void setInsetRect(int index, const QRectF &rect);
// reimplemented virtual methods:
virtual void updateLayout();
virtual int elementCount() const;
virtual QCPLayoutElement* elementAt(int index) const;
virtual QCPLayoutElement* takeAt(int index);
virtual bool take(QCPLayoutElement* element);
virtual void simplify() {}
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
// non-virtual methods:
void addElement(QCPLayoutElement *element, Qt::Alignment alignment);
void addElement(QCPLayoutElement *element, const QRectF &rect);
protected:
// property members:
QList<QCPLayoutElement*> mElements;
QList<InsetPlacement> mInsetPlacement;
QList<Qt::Alignment> mInsetAlignment;
QList<QRectF> mInsetRect;
private:
Q_DISABLE_COPY(QCPLayoutInset)
};
class QCP_LIB_DECL QCPLineEnding
{
Q_GADGET
public:
/*!
Defines the type of ending decoration for line-like items, e.g. an arrow.
\image html QCPLineEnding.png
The width and length of these decorations can be controlled with the functions \ref setWidth
and \ref setLength. Some decorations like \ref esDisc, \ref esSquare, \ref esDiamond and \ref esBar only
support a width, the length property is ignored.
\see QCPItemLine::setHead, QCPItemLine::setTail, QCPItemCurve::setHead, QCPItemCurve::setTail, QCPAxis::setLowerEnding, QCPAxis::setUpperEnding
*/
Q_ENUMS(EndingStyle)
enum EndingStyle { esNone ///< No ending decoration
,esFlatArrow ///< A filled arrow head with a straight/flat back (a triangle)
,esSpikeArrow ///< A filled arrow head with an indented back
,esLineArrow ///< A non-filled arrow head with open back
,esDisc ///< A filled circle
,esSquare ///< A filled square
,esDiamond ///< A filled diamond (45° rotated square)
,esBar ///< A bar perpendicular to the line
,esHalfBar ///< A bar perpendicular to the line, pointing out to only one side (to which side can be changed with \ref setInverted)
,esSkewedBar ///< A bar that is skewed (skew controllable via \ref setLength)
};
QCPLineEnding();
QCPLineEnding(EndingStyle style, double width=8, double length=10, bool inverted=false);
// getters:
EndingStyle style() const { return mStyle; }
double width() const { return mWidth; }
double length() const { return mLength; }
bool inverted() const { return mInverted; }
// setters:
void setStyle(EndingStyle style);
void setWidth(double width);
void setLength(double length);
void setInverted(bool inverted);
// non-property methods:
double boundingDistance() const;
double realLength() const;
void draw(QCPPainter *painter, const QVector2D &pos, const QVector2D &dir) const;
void draw(QCPPainter *painter, const QVector2D &pos, double angle) const;
protected:
// property members:
EndingStyle mStyle;
double mWidth, mLength;
bool mInverted;
};
Q_DECLARE_TYPEINFO(QCPLineEnding, Q_MOVABLE_TYPE);
class QCP_LIB_DECL QCPGrid :public QCPLayerable
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(bool subGridVisible READ subGridVisible WRITE setSubGridVisible)
Q_PROPERTY(bool antialiasedSubGrid READ antialiasedSubGrid WRITE setAntialiasedSubGrid)
Q_PROPERTY(bool antialiasedZeroLine READ antialiasedZeroLine WRITE setAntialiasedZeroLine)
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen subGridPen READ subGridPen WRITE setSubGridPen)
Q_PROPERTY(QPen zeroLinePen READ zeroLinePen WRITE setZeroLinePen)
/// \endcond
public:
QCPGrid(QCPAxis *parentAxis);
// getters:
bool subGridVisible() const { return mSubGridVisible; }
bool antialiasedSubGrid() const { return mAntialiasedSubGrid; }
bool antialiasedZeroLine() const { return mAntialiasedZeroLine; }
QPen pen() const { return mPen; }
QPen subGridPen() const { return mSubGridPen; }
QPen zeroLinePen() const { return mZeroLinePen; }
// setters:
void setSubGridVisible(bool visible);
void setAntialiasedSubGrid(bool enabled);
void setAntialiasedZeroLine(bool enabled);
void setPen(const QPen &pen);
void setSubGridPen(const QPen &pen);
void setZeroLinePen(const QPen &pen);
protected:
// property members:
bool mSubGridVisible;
bool mAntialiasedSubGrid, mAntialiasedZeroLine;
QPen mPen, mSubGridPen, mZeroLinePen;
// non-property members:
QCPAxis *mParentAxis;
// reimplemented virtual methods:
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const;
virtual void draw(QCPPainter *painter);
// non-virtual methods:
void drawGridLines(QCPPainter *painter) const;
void drawSubGridLines(QCPPainter *painter) const;
friend class QCPAxis;
};
class QCP_LIB_DECL QCPAxis : public QCPLayerable
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(AxisType axisType READ axisType)
Q_PROPERTY(QCPAxisRect* axisRect READ axisRect)
Q_PROPERTY(ScaleType scaleType READ scaleType WRITE setScaleType NOTIFY scaleTypeChanged)
Q_PROPERTY(double scaleLogBase READ scaleLogBase WRITE setScaleLogBase)
Q_PROPERTY(QCPRange range READ range WRITE setRange NOTIFY rangeChanged)
Q_PROPERTY(bool rangeReversed READ rangeReversed WRITE setRangeReversed)
Q_PROPERTY(bool autoTicks READ autoTicks WRITE setAutoTicks)
Q_PROPERTY(int autoTickCount READ autoTickCount WRITE setAutoTickCount)
Q_PROPERTY(bool autoTickLabels READ autoTickLabels WRITE setAutoTickLabels)
Q_PROPERTY(bool autoTickStep READ autoTickStep WRITE setAutoTickStep)
Q_PROPERTY(bool autoSubTicks READ autoSubTicks WRITE setAutoSubTicks)
Q_PROPERTY(bool ticks READ ticks WRITE setTicks)
Q_PROPERTY(bool tickLabels READ tickLabels WRITE setTickLabels)
Q_PROPERTY(int tickLabelPadding READ tickLabelPadding WRITE setTickLabelPadding)
Q_PROPERTY(LabelType tickLabelType READ tickLabelType WRITE setTickLabelType)
Q_PROPERTY(QFont tickLabelFont READ tickLabelFont WRITE setTickLabelFont)
Q_PROPERTY(QColor tickLabelColor READ tickLabelColor WRITE setTickLabelColor)
Q_PROPERTY(double tickLabelRotation READ tickLabelRotation WRITE setTickLabelRotation)
Q_PROPERTY(LabelSide tickLabelSide READ tickLabelSide WRITE setTickLabelSide)
Q_PROPERTY(QString dateTimeFormat READ dateTimeFormat WRITE setDateTimeFormat)
Q_PROPERTY(Qt::TimeSpec dateTimeSpec READ dateTimeSpec WRITE setDateTimeSpec)
Q_PROPERTY(QString numberFormat READ numberFormat WRITE setNumberFormat)
Q_PROPERTY(int numberPrecision READ numberPrecision WRITE setNumberPrecision)
Q_PROPERTY(double tickStep READ tickStep WRITE setTickStep)
Q_PROPERTY(QVector<double> tickVector READ tickVector WRITE setTickVector)
Q_PROPERTY(QVector<QString> tickVectorLabels READ tickVectorLabels WRITE setTickVectorLabels)
Q_PROPERTY(int tickLengthIn READ tickLengthIn WRITE setTickLengthIn)
Q_PROPERTY(int tickLengthOut READ tickLengthOut WRITE setTickLengthOut)
Q_PROPERTY(int subTickCount READ subTickCount WRITE setSubTickCount)
Q_PROPERTY(int subTickLengthIn READ subTickLengthIn WRITE setSubTickLengthIn)
Q_PROPERTY(int subTickLengthOut READ subTickLengthOut WRITE setSubTickLengthOut)
Q_PROPERTY(QPen basePen READ basePen WRITE setBasePen)
Q_PROPERTY(QPen tickPen READ tickPen WRITE setTickPen)
Q_PROPERTY(QPen subTickPen READ subTickPen WRITE setSubTickPen)
Q_PROPERTY(QFont labelFont READ labelFont WRITE setLabelFont)
Q_PROPERTY(QColor labelColor READ labelColor WRITE setLabelColor)
Q_PROPERTY(QString label READ label WRITE setLabel)
Q_PROPERTY(int labelPadding READ labelPadding WRITE setLabelPadding)
Q_PROPERTY(int padding READ padding WRITE setPadding)
Q_PROPERTY(int offset READ offset WRITE setOffset)
Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectionChanged)
Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectableChanged)
Q_PROPERTY(QFont selectedTickLabelFont READ selectedTickLabelFont WRITE setSelectedTickLabelFont)
Q_PROPERTY(QFont selectedLabelFont READ selectedLabelFont WRITE setSelectedLabelFont)
Q_PROPERTY(QColor selectedTickLabelColor READ selectedTickLabelColor WRITE setSelectedTickLabelColor)
Q_PROPERTY(QColor selectedLabelColor READ selectedLabelColor WRITE setSelectedLabelColor)
Q_PROPERTY(QPen selectedBasePen READ selectedBasePen WRITE setSelectedBasePen)
Q_PROPERTY(QPen selectedTickPen READ selectedTickPen WRITE setSelectedTickPen)
Q_PROPERTY(QPen selectedSubTickPen READ selectedSubTickPen WRITE setSelectedSubTickPen)
Q_PROPERTY(QCPLineEnding lowerEnding READ lowerEnding WRITE setLowerEnding)
Q_PROPERTY(QCPLineEnding upperEnding READ upperEnding WRITE setUpperEnding)
Q_PROPERTY(QCPGrid* grid READ grid)
/// \endcond
public:
/*!
Defines at which side of the axis rect the axis will appear. This also affects how the tick
marks are drawn, on which side the labels are placed etc.
*/
enum AxisType { atLeft = 0x01 ///< <tt>0x01</tt> Axis is vertical and on the left side of the axis rect
,atRight = 0x02 ///< <tt>0x02</tt> Axis is vertical and on the right side of the axis rect
,atTop = 0x04 ///< <tt>0x04</tt> Axis is horizontal and on the top side of the axis rect
,atBottom = 0x08 ///< <tt>0x08</tt> Axis is horizontal and on the bottom side of the axis rect
};
Q_FLAGS(AxisType AxisTypes)
Q_DECLARE_FLAGS(AxisTypes, AxisType)
/*!
When automatic tick label generation is enabled (\ref setAutoTickLabels), defines how the
coordinate of the tick is interpreted, i.e. translated into a string.
\see setTickLabelType
*/
enum LabelType { ltNumber ///< Tick coordinate is regarded as normal number and will be displayed as such. (see \ref setNumberFormat)
,ltDateTime ///< Tick coordinate is regarded as a date/time (seconds since 1970-01-01T00:00:00 UTC) and will be displayed and formatted as such. (for details, see \ref setDateTimeFormat)
};
Q_ENUMS(LabelType)
/*!
Defines on which side of the axis the tick labels (numbers) shall appear.
\see setTickLabelSide
*/
enum LabelSide { lsInside ///< Tick labels will be displayed inside the axis rect and clipped to the inner axis rect
,lsOutside ///< Tick labels will be displayed outside the axis rect
};
Q_ENUMS(LabelSide)
/*!
Defines the scale of an axis.
\see setScaleType
*/
enum ScaleType { stLinear ///< Linear scaling
,stLogarithmic ///< Logarithmic scaling with correspondingly transformed plots and (major) tick marks at every base power (see \ref setScaleLogBase).
};
Q_ENUMS(ScaleType)
/*!
Defines the selectable parts of an axis.
\see setSelectableParts, setSelectedParts
*/
enum SelectablePart { spNone = 0 ///< None of the selectable parts
,spAxis = 0x001 ///< The axis backbone and tick marks
,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually)
,spAxisLabel = 0x004 ///< The axis label
};
Q_FLAGS(SelectablePart SelectableParts)
Q_DECLARE_FLAGS(SelectableParts, SelectablePart)
explicit QCPAxis(QCPAxisRect *parent, AxisType type);
virtual ~QCPAxis();
// getters:
AxisType axisType() const { return mAxisType; }
QCPAxisRect *axisRect() const { return mAxisRect; }
ScaleType scaleType() const { return mScaleType; }
double scaleLogBase() const { return mScaleLogBase; }
const QCPRange range() const { return mRange; }
bool rangeReversed() const { return mRangeReversed; }
bool autoTicks() const { return mAutoTicks; }
int autoTickCount() const { return mAutoTickCount; }
bool autoTickLabels() const { return mAutoTickLabels; }
bool autoTickStep() const { return mAutoTickStep; }
bool autoSubTicks() const { return mAutoSubTicks; }
bool ticks() const { return mTicks; }
bool tickLabels() const { return mTickLabels; }
int tickLabelPadding() const;
LabelType tickLabelType() const { return mTickLabelType; }
QFont tickLabelFont() const { return mTickLabelFont; }
QColor tickLabelColor() const { return mTickLabelColor; }
double tickLabelRotation() const;
LabelSide tickLabelSide() const;
QString dateTimeFormat() const { return mDateTimeFormat; }
Qt::TimeSpec dateTimeSpec() const { return mDateTimeSpec; }
QString numberFormat() const;
int numberPrecision() const { return mNumberPrecision; }
double tickStep() const { return mTickStep; }
QVector<double> tickVector() const { return mTickVector; }
QVector<QString> tickVectorLabels() const { return mTickVectorLabels; }
int tickLengthIn() const;
int tickLengthOut() const;
int subTickCount() const { return mSubTickCount; }
int subTickLengthIn() const;
int subTickLengthOut() const;
QPen basePen() const { return mBasePen; }
QPen tickPen() const { return mTickPen; }
QPen subTickPen() const { return mSubTickPen; }
QFont labelFont() const { return mLabelFont; }
QColor labelColor() const { return mLabelColor; }
QString label() const { return mLabel; }
int labelPadding() const;
int padding() const { return mPadding; }
int offset() const;
SelectableParts selectedParts() const { return mSelectedParts; }
SelectableParts selectableParts() const { return mSelectableParts; }
QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; }
QFont selectedLabelFont() const { return mSelectedLabelFont; }
QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; }
QColor selectedLabelColor() const { return mSelectedLabelColor; }
QPen selectedBasePen() const { return mSelectedBasePen; }
QPen selectedTickPen() const { return mSelectedTickPen; }
QPen selectedSubTickPen() const { return mSelectedSubTickPen; }
QCPLineEnding lowerEnding() const;
QCPLineEnding upperEnding() const;
QCPGrid *grid() const { return mGrid; }
// setters:
Q_SLOT void setScaleType(QCPAxis::ScaleType type);
void setScaleLogBase(double base);
Q_SLOT void setRange(const QCPRange &range);
void setRange(double lower, double upper);
void setRange(double position, double size, Qt::AlignmentFlag alignment);
void setRangeLower(double lower);
void setRangeUpper(double upper);
void setRangeReversed(bool reversed);
void setAutoTicks(bool on);
void setAutoTickCount(int approximateCount);
void setAutoTickLabels(bool on);
void setAutoTickStep(bool on);
void setAutoSubTicks(bool on);
void setTicks(bool show);
void setTickLabels(bool show);
void setTickLabelPadding(int padding);
void setTickLabelType(LabelType type);
void setTickLabelFont(const QFont &font);
void setTickLabelColor(const QColor &color);
void setTickLabelRotation(double degrees);
void setTickLabelSide(LabelSide side);
void setDateTimeFormat(const QString &format);
void setDateTimeSpec(const Qt::TimeSpec &timeSpec);
void setNumberFormat(const QString &formatCode);
void setNumberPrecision(int precision);
void setTickStep(double step);
void setTickVector(const QVector<double> &vec);
void setTickVectorLabels(const QVector<QString> &vec);
void setTickLength(int inside, int outside=0);
void setTickLengthIn(int inside);
void setTickLengthOut(int outside);
void setSubTickCount(int count);
void setSubTickLength(int inside, int outside=0);
void setSubTickLengthIn(int inside);
void setSubTickLengthOut(int outside);
void setBasePen(const QPen &pen);
void setTickPen(const QPen &pen);
void setSubTickPen(const QPen &pen);
void setLabelFont(const QFont &font);
void setLabelColor(const QColor &color);
void setLabel(const QString &str);
void setLabelPadding(int padding);
void setPadding(int padding);
void setOffset(int offset);
void setSelectedTickLabelFont(const QFont &font);
void setSelectedLabelFont(const QFont &font);
void setSelectedTickLabelColor(const QColor &color);
void setSelectedLabelColor(const QColor &color);
void setSelectedBasePen(const QPen &pen);
void setSelectedTickPen(const QPen &pen);
void setSelectedSubTickPen(const QPen &pen);
Q_SLOT void setSelectableParts(const QCPAxis::SelectableParts &selectableParts);
Q_SLOT void setSelectedParts(const QCPAxis::SelectableParts &selectedParts);
void setLowerEnding(const QCPLineEnding &ending);
void setUpperEnding(const QCPLineEnding &ending);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
// non-property methods:
Qt::Orientation orientation() const { return mOrientation; }
void moveRange(double diff);
void scaleRange(double factor, double center);
void setScaleRatio(const QCPAxis *otherAxis, double ratio=1.0);
void rescale(bool onlyVisiblePlottables=false);
double pixelToCoord(double value) const;
double coordToPixel(double value) const;
SelectablePart getPartAt(const QPointF &pos) const;
QList<QCPAbstractPlottable*> plottables() const;
QList<QCPGraph*> graphs() const;
QList<QCPAbstractItem*> items() const;
static AxisType marginSideToAxisType(QCP::MarginSide side);
static Qt::Orientation orientation(AxisType type) { return type==atBottom||type==atTop ? Qt::Horizontal : Qt::Vertical; }
static AxisType opposite(AxisType type);
signals:
void ticksRequest();
void rangeChanged(const QCPRange &newRange);
void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange);
void scaleTypeChanged(QCPAxis::ScaleType scaleType);
void selectionChanged(const QCPAxis::SelectableParts &parts);
void selectableChanged(const QCPAxis::SelectableParts &parts);
protected:
// property members:
// axis base:
AxisType mAxisType;
QCPAxisRect *mAxisRect;
//int mOffset; // in QCPAxisPainter
int mPadding;
Qt::Orientation mOrientation;
SelectableParts mSelectableParts, mSelectedParts;
QPen mBasePen, mSelectedBasePen;
//QCPLineEnding mLowerEnding, mUpperEnding; // in QCPAxisPainter
// axis label:
//int mLabelPadding; // in QCPAxisPainter
QString mLabel;
QFont mLabelFont, mSelectedLabelFont;
QColor mLabelColor, mSelectedLabelColor;
// tick labels:
//int mTickLabelPadding; // in QCPAxisPainter
bool mTickLabels, mAutoTickLabels;
//double mTickLabelRotation; // in QCPAxisPainter
LabelType mTickLabelType;
QFont mTickLabelFont, mSelectedTickLabelFont;
QColor mTickLabelColor, mSelectedTickLabelColor;
QString mDateTimeFormat;
Qt::TimeSpec mDateTimeSpec;
int mNumberPrecision;
QLatin1Char mNumberFormatChar;
bool mNumberBeautifulPowers;
//bool mNumberMultiplyCross; // QCPAxisPainter
// ticks and subticks:
bool mTicks;
double mTickStep;
int mSubTickCount, mAutoTickCount;
bool mAutoTicks, mAutoTickStep, mAutoSubTicks;
//int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter
QPen mTickPen, mSelectedTickPen;
QPen mSubTickPen, mSelectedSubTickPen;
// scale and range:
QCPRange mRange;
bool mRangeReversed;
ScaleType mScaleType;
double mScaleLogBase, mScaleLogBaseLogInv;
// non-property members:
QCPGrid *mGrid;
QCPAxisPainterPrivate *mAxisPainter;
int mLowestVisibleTick, mHighestVisibleTick;
QVector<double> mTickVector;
QVector<QString> mTickVectorLabels;
QVector<double> mSubTickVector;
bool mCachedMarginValid;
int mCachedMargin;
// introduced virtual methods:
virtual void setupTickVectors();
virtual void generateAutoTicks();
virtual int calculateAutoSubTickCount(double tickStep) const;
virtual int calculateMargin();
// reimplemented virtual methods:
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const;
virtual void draw(QCPPainter *painter);
virtual QCP::Interaction selectionCategory() const;
// events:
virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged);
virtual void deselectEvent(bool *selectionStateChanged);
// non-virtual methods:
void visibleTickBounds(int &lowIndex, int &highIndex) const;
double baseLog(double value) const;
double basePow(double value) const;
QPen getBasePen() const;
QPen getTickPen() const;
QPen getSubTickPen() const;
QFont getTickLabelFont() const;
QFont getLabelFont() const;
QColor getTickLabelColor() const;
QColor getLabelColor() const;
private:
Q_DISABLE_COPY(QCPAxis)
friend class QCustomPlot;
friend class QCPGrid;
friend class QCPAxisRect;
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::SelectableParts)
Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::AxisTypes)
Q_DECLARE_METATYPE(QCPAxis::SelectablePart)
class QCPAxisPainterPrivate
{
public:
explicit QCPAxisPainterPrivate(QCustomPlot *parentPlot);
virtual ~QCPAxisPainterPrivate();
virtual void draw(QCPPainter *painter);
virtual int size() const;
void clearCache();
QRect axisSelectionBox() const { return mAxisSelectionBox; }
QRect tickLabelsSelectionBox() const { return mTickLabelsSelectionBox; }
QRect labelSelectionBox() const { return mLabelSelectionBox; }
// public property members:
QCPAxis::AxisType type;
QPen basePen;
QCPLineEnding lowerEnding, upperEnding; // directly accessed by QCPAxis setters/getters
int labelPadding; // directly accessed by QCPAxis setters/getters
QFont labelFont;
QColor labelColor;
QString label;
int tickLabelPadding; // directly accessed by QCPAxis setters/getters
double tickLabelRotation; // directly accessed by QCPAxis setters/getters
QCPAxis::LabelSide tickLabelSide; // directly accessed by QCPAxis setters/getters
bool substituteExponent;
bool numberMultiplyCross; // directly accessed by QCPAxis setters/getters
int tickLengthIn, tickLengthOut, subTickLengthIn, subTickLengthOut; // directly accessed by QCPAxis setters/getters
QPen tickPen, subTickPen;
QFont tickLabelFont;
QColor tickLabelColor;
QRect axisRect, viewportRect;
double offset; // directly accessed by QCPAxis setters/getters
bool abbreviateDecimalPowers;
bool reversedEndings;
QVector<double> subTickPositions;
QVector<double> tickPositions;
QVector<QString> tickLabels;
protected:
struct CachedLabel
{
QPointF offset;
QPixmap pixmap;
};
struct TickLabelData
{
QString basePart, expPart;
QRect baseBounds, expBounds, totalBounds, rotatedTotalBounds;
QFont baseFont, expFont;
};
QCustomPlot *mParentPlot;
QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters
QCache<QString, CachedLabel> mLabelCache;
QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox;
virtual QByteArray generateLabelParameterHash() const;
virtual void placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize);
virtual void drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const;
virtual TickLabelData getTickLabelData(const QFont &font, const QString &text) const;
virtual QPointF getTickLabelDrawOffset(const TickLabelData &labelData) const;
virtual void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const;
};
class QCP_LIB_DECL QCPAbstractPlottable : public QCPLayerable
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QString name READ name WRITE setName)
Q_PROPERTY(bool antialiasedFill READ antialiasedFill WRITE setAntialiasedFill)
Q_PROPERTY(bool antialiasedScatters READ antialiasedScatters WRITE setAntialiasedScatters)
Q_PROPERTY(bool antialiasedErrorBars READ antialiasedErrorBars WRITE setAntialiasedErrorBars)
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen)
Q_PROPERTY(QBrush brush READ brush WRITE setBrush)
Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush)
Q_PROPERTY(QCPAxis* keyAxis READ keyAxis WRITE setKeyAxis)
Q_PROPERTY(QCPAxis* valueAxis READ valueAxis WRITE setValueAxis)
Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged)
Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged)
/// \endcond
public:
QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis);
// getters:
QString name() const { return mName; }
bool antialiasedFill() const { return mAntialiasedFill; }
bool antialiasedScatters() const { return mAntialiasedScatters; }
bool antialiasedErrorBars() const { return mAntialiasedErrorBars; }
QPen pen() const { return mPen; }
QPen selectedPen() const { return mSelectedPen; }
QBrush brush() const { return mBrush; }
QBrush selectedBrush() const { return mSelectedBrush; }
QCPAxis *keyAxis() const { return mKeyAxis.data(); }
QCPAxis *valueAxis() const { return mValueAxis.data(); }
bool selectable() const { return mSelectable; }
bool selected() const { return mSelected; }
// setters:
void setName(const QString &name);
void setAntialiasedFill(bool enabled);
void setAntialiasedScatters(bool enabled);
void setAntialiasedErrorBars(bool enabled);
void setPen(const QPen &pen);
void setSelectedPen(const QPen &pen);
void setBrush(const QBrush &brush);
void setSelectedBrush(const QBrush &brush);
void setKeyAxis(QCPAxis *axis);
void setValueAxis(QCPAxis *axis);
Q_SLOT void setSelectable(bool selectable);
Q_SLOT void setSelected(bool selected);
// introduced virtual methods:
virtual void clearData() = 0;
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const = 0;
virtual bool addToLegend();
virtual bool removeFromLegend() const;
// non-property methods:
void rescaleAxes(bool onlyEnlarge=false) const;
void rescaleKeyAxis(bool onlyEnlarge=false) const;
void rescaleValueAxis(bool onlyEnlarge=false) const;
signals:
void selectionChanged(bool selected);
void selectableChanged(bool selectable);
protected:
/*!
Represents negative and positive sign domain for passing to \ref getKeyRange and \ref getValueRange.
*/
enum SignDomain { sdNegative ///< The negative sign domain, i.e. numbers smaller than zero
,sdBoth ///< Both sign domains, including zero, i.e. all (rational) numbers
,sdPositive ///< The positive sign domain, i.e. numbers greater than zero
};
// property members:
QString mName;
bool mAntialiasedFill, mAntialiasedScatters, mAntialiasedErrorBars;
QPen mPen, mSelectedPen;
QBrush mBrush, mSelectedBrush;
QPointer<QCPAxis> mKeyAxis, mValueAxis;
bool mSelectable, mSelected;
// reimplemented virtual methods:
virtual QRect clipRect() const;
virtual void draw(QCPPainter *painter) = 0;
virtual QCP::Interaction selectionCategory() const;
void applyDefaultAntialiasingHint(QCPPainter *painter) const;
// events:
virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged);
virtual void deselectEvent(bool *selectionStateChanged);
// introduced virtual methods:
virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const = 0;
virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const = 0;
virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const = 0;
// non-virtual methods:
void coordsToPixels(double key, double value, double &x, double &y) const;
const QPointF coordsToPixels(double key, double value) const;
void pixelsToCoords(double x, double y, double &key, double &value) const;
void pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const;
QPen mainPen() const;
QBrush mainBrush() const;
void applyFillAntialiasingHint(QCPPainter *painter) const;
void applyScattersAntialiasingHint(QCPPainter *painter) const;
void applyErrorBarsAntialiasingHint(QCPPainter *painter) const;
double distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const;
private:
Q_DISABLE_COPY(QCPAbstractPlottable)
friend class QCustomPlot;
friend class QCPAxis;
friend class QCPPlottableLegendItem;
};
class QCP_LIB_DECL QCPItemAnchor
{
public:
QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId=-1);
virtual ~QCPItemAnchor();
// getters:
QString name() const { return mName; }
virtual QPointF pixelPoint() const;
protected:
// property members:
QString mName;
// non-property members:
QCustomPlot *mParentPlot;
QCPAbstractItem *mParentItem;
int mAnchorId;
QSet<QCPItemPosition*> mChildrenX, mChildrenY;
// introduced virtual methods:
virtual QCPItemPosition *toQCPItemPosition() { return 0; }
// non-virtual methods:
void addChildX(QCPItemPosition* pos); // called from pos when this anchor is set as parent
void removeChildX(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted
void addChildY(QCPItemPosition* pos); // called from pos when this anchor is set as parent
void removeChildY(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted
private:
Q_DISABLE_COPY(QCPItemAnchor)
friend class QCPItemPosition;
};
class QCP_LIB_DECL QCPItemPosition : public QCPItemAnchor
{
public:
/*!
Defines the ways an item position can be specified. Thus it defines what the numbers passed to
\ref setCoords actually mean.
\see setType
*/
enum PositionType { ptAbsolute ///< Static positioning in pixels, starting from the top left corner of the viewport/widget.
,ptViewportRatio ///< Static positioning given by a fraction of the viewport size. For example, if you call setCoords(0, 0), the position will be at the top
///< left corner of the viewport/widget. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and
///< vertically at the top of the viewport/widget, etc.
,ptAxisRectRatio ///< Static positioning given by a fraction of the axis rect size (see \ref setAxisRect). For example, if you call setCoords(0, 0), the position will be at the top
///< left corner of the axis rect. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and
///< vertically at the top of the axis rect, etc. You can also go beyond the axis rect by providing negative coordinates or coordinates larger than 1.
,ptPlotCoords ///< Dynamic positioning at a plot coordinate defined by two axes (see \ref setAxes).
};
QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name);
virtual ~QCPItemPosition();
// getters:
PositionType type() const { return typeX(); }
PositionType typeX() const { return mPositionTypeX; }
PositionType typeY() const { return mPositionTypeY; }
QCPItemAnchor *parentAnchor() const { return parentAnchorX(); }
QCPItemAnchor *parentAnchorX() const { return mParentAnchorX; }
QCPItemAnchor *parentAnchorY() const { return mParentAnchorY; }
double key() const { return mKey; }
double value() const { return mValue; }
QPointF coords() const { return QPointF(mKey, mValue); }
QCPAxis *keyAxis() const { return mKeyAxis.data(); }
QCPAxis *valueAxis() const { return mValueAxis.data(); }
QCPAxisRect *axisRect() const;
virtual QPointF pixelPoint() const;
// setters:
void setType(PositionType type);
void setTypeX(PositionType type);
void setTypeY(PositionType type);
bool setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false);
bool setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false);
bool setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false);
void setCoords(double key, double value);
void setCoords(const QPointF &coords);
void setAxes(QCPAxis* keyAxis, QCPAxis* valueAxis);
void setAxisRect(QCPAxisRect *axisRect);
void setPixelPoint(const QPointF &pixelPoint);
protected:
// property members:
PositionType mPositionTypeX, mPositionTypeY;
QPointer<QCPAxis> mKeyAxis, mValueAxis;
QPointer<QCPAxisRect> mAxisRect;
double mKey, mValue;
QCPItemAnchor *mParentAnchorX, *mParentAnchorY;
// reimplemented virtual methods:
virtual QCPItemPosition *toQCPItemPosition() { return this; }
private:
Q_DISABLE_COPY(QCPItemPosition)
};
class QCP_LIB_DECL QCPAbstractItem : public QCPLayerable
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(bool clipToAxisRect READ clipToAxisRect WRITE setClipToAxisRect)
Q_PROPERTY(QCPAxisRect* clipAxisRect READ clipAxisRect WRITE setClipAxisRect)
Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged)
Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged)
/// \endcond
public:
QCPAbstractItem(QCustomPlot *parentPlot);
virtual ~QCPAbstractItem();
// getters:
bool clipToAxisRect() const { return mClipToAxisRect; }
QCPAxisRect *clipAxisRect() const;
bool selectable() const { return mSelectable; }
bool selected() const { return mSelected; }
// setters:
void setClipToAxisRect(bool clip);
void setClipAxisRect(QCPAxisRect *rect);
Q_SLOT void setSelectable(bool selectable);
Q_SLOT void setSelected(bool selected);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const = 0;
// non-virtual methods:
QList<QCPItemPosition*> positions() const { return mPositions; }
QList<QCPItemAnchor*> anchors() const { return mAnchors; }
QCPItemPosition *position(const QString &name) const;
QCPItemAnchor *anchor(const QString &name) const;
bool hasAnchor(const QString &name) const;
signals:
void selectionChanged(bool selected);
void selectableChanged(bool selectable);
protected:
// property members:
bool mClipToAxisRect;
QPointer<QCPAxisRect> mClipAxisRect;
QList<QCPItemPosition*> mPositions;
QList<QCPItemAnchor*> mAnchors;
bool mSelectable, mSelected;
// reimplemented virtual methods:
virtual QCP::Interaction selectionCategory() const;
virtual QRect clipRect() const;
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const;
virtual void draw(QCPPainter *painter) = 0;
// events:
virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged);
virtual void deselectEvent(bool *selectionStateChanged);
// introduced virtual methods:
virtual QPointF anchorPixelPoint(int anchorId) const;
// non-virtual methods:
double distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const;
double rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const;
QCPItemPosition *createPosition(const QString &name);
QCPItemAnchor *createAnchor(const QString &name, int anchorId);
private:
Q_DISABLE_COPY(QCPAbstractItem)
friend class QCustomPlot;
friend class QCPItemAnchor;
};
class QCP_LIB_DECL QCustomPlot : public QWidget
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QRect viewport READ viewport WRITE setViewport)
Q_PROPERTY(QPixmap background READ background WRITE setBackground)
Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled)
Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode)
Q_PROPERTY(QCPLayoutGrid* plotLayout READ plotLayout)
Q_PROPERTY(bool autoAddPlottableToLegend READ autoAddPlottableToLegend WRITE setAutoAddPlottableToLegend)
Q_PROPERTY(int selectionTolerance READ selectionTolerance WRITE setSelectionTolerance)
Q_PROPERTY(bool noAntialiasingOnDrag READ noAntialiasingOnDrag WRITE setNoAntialiasingOnDrag)
Q_PROPERTY(Qt::KeyboardModifier multiSelectModifier READ multiSelectModifier WRITE setMultiSelectModifier)
/// \endcond
public:
/*!
Defines how a layer should be inserted relative to an other layer.
\see addLayer, moveLayer
*/
enum LayerInsertMode { limBelow ///< Layer is inserted below other layer
,limAbove ///< Layer is inserted above other layer
};
Q_ENUMS(LayerInsertMode)
/*!
Defines with what timing the QCustomPlot surface is refreshed after a replot.
\see replot
*/
enum RefreshPriority { rpImmediate ///< The QCustomPlot surface is immediately refreshed, by calling QWidget::repaint() after the replot
,rpQueued ///< Queues the refresh such that it is performed at a slightly delayed point in time after the replot, by calling QWidget::update() after the replot
,rpHint ///< Whether to use immediate repaint or queued update depends on whether the plotting hint \ref QCP::phForceRepaint is set, see \ref setPlottingHints.
};
explicit QCustomPlot(QWidget *parent = 0);
virtual ~QCustomPlot();
// getters:
QRect viewport() const { return mViewport; }
QPixmap background() const { return mBackgroundPixmap; }
bool backgroundScaled() const { return mBackgroundScaled; }
Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; }
QCPLayoutGrid *plotLayout() const { return mPlotLayout; }
QCP::AntialiasedElements antialiasedElements() const { return mAntialiasedElements; }
QCP::AntialiasedElements notAntialiasedElements() const { return mNotAntialiasedElements; }
bool autoAddPlottableToLegend() const { return mAutoAddPlottableToLegend; }
const QCP::Interactions interactions() const { return mInteractions; }
int selectionTolerance() const { return mSelectionTolerance; }
bool noAntialiasingOnDrag() const { return mNoAntialiasingOnDrag; }
QCP::PlottingHints plottingHints() const { return mPlottingHints; }
Qt::KeyboardModifier multiSelectModifier() const { return mMultiSelectModifier; }
// setters:
void setViewport(const QRect &rect);
void setBackground(const QPixmap &pm);
void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding);
void setBackground(const QBrush &brush);
void setBackgroundScaled(bool scaled);
void setBackgroundScaledMode(Qt::AspectRatioMode mode);
void setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements);
void setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled=true);
void setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements);
void setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled=true);
void setAutoAddPlottableToLegend(bool on);
void setInteractions(const QCP::Interactions &interactions);
void setInteraction(const QCP::Interaction &interaction, bool enabled=true);
void setSelectionTolerance(int pixels);
void setNoAntialiasingOnDrag(bool enabled);
void setPlottingHints(const QCP::PlottingHints &hints);
void setPlottingHint(QCP::PlottingHint hint, bool enabled=true);
void setMultiSelectModifier(Qt::KeyboardModifier modifier);
// non-property methods:
// plottable interface:
QCPAbstractPlottable *plottable(int index);
QCPAbstractPlottable *plottable();
bool addPlottable(QCPAbstractPlottable *plottable);
bool removePlottable(QCPAbstractPlottable *plottable);
bool removePlottable(int index);
int clearPlottables();
int plottableCount() const;
QList<QCPAbstractPlottable*> selectedPlottables() const;
QCPAbstractPlottable *plottableAt(const QPointF &pos, bool onlySelectable=false) const;
bool hasPlottable(QCPAbstractPlottable *plottable) const;
// specialized interface for QCPGraph:
QCPGraph *graph(int index) const;
QCPGraph *graph() const;
QCPGraph *addGraph(QCPAxis *keyAxis=0, QCPAxis *valueAxis=0);
bool removeGraph(QCPGraph *graph);
bool removeGraph(int index);
int clearGraphs();
int graphCount() const;
QList<QCPGraph*> selectedGraphs() const;
// item interface:
QCPAbstractItem *item(int index) const;
QCPAbstractItem *item() const;
bool addItem(QCPAbstractItem* item);
bool removeItem(QCPAbstractItem *item);
bool removeItem(int index);
int clearItems();
int itemCount() const;
QList<QCPAbstractItem*> selectedItems() const;
QCPAbstractItem *itemAt(const QPointF &pos, bool onlySelectable=false) const;
bool hasItem(QCPAbstractItem *item) const;
// layer interface:
QCPLayer *layer(const QString &name) const;
QCPLayer *layer(int index) const;
QCPLayer *currentLayer() const;
bool setCurrentLayer(const QString &name);
bool setCurrentLayer(QCPLayer *layer);
int layerCount() const;
bool addLayer(const QString &name, QCPLayer *otherLayer=0, LayerInsertMode insertMode=limAbove);
bool removeLayer(QCPLayer *layer);
bool moveLayer(QCPLayer *layer, QCPLayer *otherLayer, LayerInsertMode insertMode=limAbove);
// axis rect/layout interface:
int axisRectCount() const;
QCPAxisRect* axisRect(int index=0) const;
QList<QCPAxisRect*> axisRects() const;
QCPLayoutElement* layoutElementAt(const QPointF &pos) const;
Q_SLOT void rescaleAxes(bool onlyVisiblePlottables=false);
QList<QCPAxis*> selectedAxes() const;
QList<QCPLegend*> selectedLegends() const;
Q_SLOT void deselectAll();
bool savePdf(const QString &fileName, bool noCosmeticPen=false, int width=0, int height=0, const QString &pdfCreator=QString(), const QString &pdfTitle=QString());
bool savePng(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1);
bool saveJpg(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1);
bool saveBmp(const QString &fileName, int width=0, int height=0, double scale=1.0);
bool saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality=-1);
QPixmap toPixmap(int width=0, int height=0, double scale=1.0);
void toPainter(QCPPainter *painter, int width=0, int height=0);
Q_SLOT void replot(QCustomPlot::RefreshPriority refreshPriority=QCustomPlot::rpHint);
QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2;
QCPLegend *legend;
signals:
void mouseDoubleClick(QMouseEvent *event);
void mousePress(QMouseEvent *event);
void mouseMove(QMouseEvent *event);
void mouseRelease(QMouseEvent *event);
void mouseWheel(QWheelEvent *event);
void plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event);
void plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event);
void itemClick(QCPAbstractItem *item, QMouseEvent *event);
void itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event);
void axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event);
void axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event);
void legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event);
void legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event);
void titleClick(QMouseEvent *event, QCPPlotTitle *title);
void titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title);
void selectionChangedByUser();
void beforeReplot();
void afterReplot();
protected:
// property members:
QRect mViewport;
QCPLayoutGrid *mPlotLayout;
bool mAutoAddPlottableToLegend;
QList<QCPAbstractPlottable*> mPlottables;
QList<QCPGraph*> mGraphs; // extra list of plottables also in mPlottables that are of type QCPGraph
QList<QCPAbstractItem*> mItems;
QList<QCPLayer*> mLayers;
QCP::AntialiasedElements mAntialiasedElements, mNotAntialiasedElements;
QCP::Interactions mInteractions;
int mSelectionTolerance;
bool mNoAntialiasingOnDrag;
QBrush mBackgroundBrush;
QPixmap mBackgroundPixmap;
QPixmap mScaledBackgroundPixmap;
bool mBackgroundScaled;
Qt::AspectRatioMode mBackgroundScaledMode;
QCPLayer *mCurrentLayer;
QCP::PlottingHints mPlottingHints;
Qt::KeyboardModifier mMultiSelectModifier;
// non-property members:
QPixmap mPaintBuffer;
QPoint mMousePressPos;
QPointer<QCPLayoutElement> mMouseEventElement;
bool mReplotting;
// reimplemented virtual methods:
virtual QSize minimumSizeHint() const;
virtual QSize sizeHint() const;
virtual void paintEvent(QPaintEvent *event);
virtual void resizeEvent(QResizeEvent *event);
virtual void mouseDoubleClickEvent(QMouseEvent *event);
virtual void mousePressEvent(QMouseEvent *event);
virtual void mouseMoveEvent(QMouseEvent *event);
virtual void mouseReleaseEvent(QMouseEvent *event);
virtual void wheelEvent(QWheelEvent *event);
// introduced virtual methods:
virtual void draw(QCPPainter *painter);
virtual void axisRemoved(QCPAxis *axis);
virtual void legendRemoved(QCPLegend *legend);
// non-virtual methods:
void updateLayerIndices() const;
QCPLayerable *layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails=0) const;
void drawBackground(QCPPainter *painter);
friend class QCPLegend;
friend class QCPAxis;
friend class QCPLayer;
friend class QCPAxisRect;
};
class QCP_LIB_DECL QCPColorGradient
{
Q_GADGET
public:
/*!
Defines the color spaces in which color interpolation between gradient stops can be performed.
\see setColorInterpolation
*/
enum ColorInterpolation { ciRGB ///< Color channels red, green and blue are linearly interpolated
,ciHSV ///< Color channels hue, saturation and value are linearly interpolated (The hue is interpolated over the shortest angle distance)
};
Q_ENUMS(ColorInterpolation)
/*!
Defines the available presets that can be loaded with \ref loadPreset. See the documentation
there for an image of the presets.
*/
enum GradientPreset { gpGrayscale ///< Continuous lightness from black to white (suited for non-biased data representation)
,gpHot ///< Continuous lightness from black over firey colors to white (suited for non-biased data representation)
,gpCold ///< Continuous lightness from black over icey colors to white (suited for non-biased data representation)
,gpNight ///< Continuous lightness from black over weak blueish colors to white (suited for non-biased data representation)
,gpCandy ///< Blue over pink to white
,gpGeography ///< Colors suitable to represent different elevations on geographical maps
,gpIon ///< Half hue spectrum from black over purple to blue and finally green (creates banding illusion but allows more precise magnitude estimates)
,gpThermal ///< Colors suitable for thermal imaging, ranging from dark blue over purple to orange, yellow and white
,gpPolar ///< Colors suitable to emphasize polarity around the center, with blue for negative, black in the middle and red for positive values
,gpSpectrum ///< An approximation of the visible light spectrum (creates banding illusion but allows more precise magnitude estimates)
,gpJet ///< Hue variation similar to a spectrum, often used in numerical visualization (creates banding illusion but allows more precise magnitude estimates)
,gpHues ///< Full hue cycle, with highest and lowest color red (suitable for periodic data, such as angles and phases, see \ref setPeriodic)
};
Q_ENUMS(GradientPreset)
QCPColorGradient(GradientPreset preset=gpCold);
bool operator==(const QCPColorGradient &other) const;
bool operator!=(const QCPColorGradient &other) const { return !(*this == other); }
// getters:
int levelCount() const { return mLevelCount; }
QMap<double, QColor> colorStops() const { return mColorStops; }
ColorInterpolation colorInterpolation() const { return mColorInterpolation; }
bool periodic() const { return mPeriodic; }
// setters:
void setLevelCount(int n);
void setColorStops(const QMap<double, QColor> &colorStops);
void setColorStopAt(double position, const QColor &color);
void setColorInterpolation(ColorInterpolation interpolation);
void setPeriodic(bool enabled);
// non-property methods:
void colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor=1, bool logarithmic=false);
QRgb color(double position, const QCPRange &range, bool logarithmic=false);
void loadPreset(GradientPreset preset);
void clearColorStops();
QCPColorGradient inverted() const;
protected:
void updateColorBuffer();
// property members:
int mLevelCount;
QMap<double, QColor> mColorStops;
ColorInterpolation mColorInterpolation;
bool mPeriodic;
// non-property members:
QVector<QRgb> mColorBuffer;
bool mColorBufferInvalidated;
};
class QCP_LIB_DECL QCPAxisRect : public QCPLayoutElement
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QPixmap background READ background WRITE setBackground)
Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled)
Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode)
Q_PROPERTY(Qt::Orientations rangeDrag READ rangeDrag WRITE setRangeDrag)
Q_PROPERTY(Qt::Orientations rangeZoom READ rangeZoom WRITE setRangeZoom)
/// \endcond
public:
explicit QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes=true);
virtual ~QCPAxisRect();
// getters:
QPixmap background() const { return mBackgroundPixmap; }
bool backgroundScaled() const { return mBackgroundScaled; }
Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; }
Qt::Orientations rangeDrag() const { return mRangeDrag; }
Qt::Orientations rangeZoom() const { return mRangeZoom; }
QCPAxis *rangeDragAxis(Qt::Orientation orientation);
QCPAxis *rangeZoomAxis(Qt::Orientation orientation);
double rangeZoomFactor(Qt::Orientation orientation);
// setters:
void setBackground(const QPixmap &pm);
void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding);
void setBackground(const QBrush &brush);
void setBackgroundScaled(bool scaled);
void setBackgroundScaledMode(Qt::AspectRatioMode mode);
void setRangeDrag(Qt::Orientations orientations);
void setRangeZoom(Qt::Orientations orientations);
void setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical);
void setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical);
void setRangeZoomFactor(double horizontalFactor, double verticalFactor);
void setRangeZoomFactor(double factor);
// non-property methods:
int axisCount(QCPAxis::AxisType type) const;
QCPAxis *axis(QCPAxis::AxisType type, int index=0) const;
QList<QCPAxis*> axes(QCPAxis::AxisTypes types) const;
QList<QCPAxis*> axes() const;
QCPAxis *addAxis(QCPAxis::AxisType type, QCPAxis *axis=0);
QList<QCPAxis*> addAxes(QCPAxis::AxisTypes types);
bool removeAxis(QCPAxis *axis);
QCPLayoutInset *insetLayout() const { return mInsetLayout; }
void setupFullAxesBox(bool connectRanges=false);
QList<QCPAbstractPlottable*> plottables() const;
QList<QCPGraph*> graphs() const;
QList<QCPAbstractItem*> items() const;
// read-only interface imitating a QRect:
int left() const { return mRect.left(); }
int right() const { return mRect.right(); }
int top() const { return mRect.top(); }
int bottom() const { return mRect.bottom(); }
int width() const { return mRect.width(); }
int height() const { return mRect.height(); }
QSize size() const { return mRect.size(); }
QPoint topLeft() const { return mRect.topLeft(); }
QPoint topRight() const { return mRect.topRight(); }
QPoint bottomLeft() const { return mRect.bottomLeft(); }
QPoint bottomRight() const { return mRect.bottomRight(); }
QPoint center() const { return mRect.center(); }
// reimplemented virtual methods:
virtual void update(UpdatePhase phase);
virtual QList<QCPLayoutElement*> elements(bool recursive) const;
protected:
// property members:
QBrush mBackgroundBrush;
QPixmap mBackgroundPixmap;
QPixmap mScaledBackgroundPixmap;
bool mBackgroundScaled;
Qt::AspectRatioMode mBackgroundScaledMode;
QCPLayoutInset *mInsetLayout;
Qt::Orientations mRangeDrag, mRangeZoom;
QPointer<QCPAxis> mRangeDragHorzAxis, mRangeDragVertAxis, mRangeZoomHorzAxis, mRangeZoomVertAxis;
double mRangeZoomFactorHorz, mRangeZoomFactorVert;
// non-property members:
QCPRange mDragStartHorzRange, mDragStartVertRange;
QCP::AntialiasedElements mAADragBackup, mNotAADragBackup;
QPoint mDragStart;
bool mDragging;
QHash<QCPAxis::AxisType, QList<QCPAxis*> > mAxes;
// reimplemented virtual methods:
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const;
virtual void draw(QCPPainter *painter);
virtual int calculateAutoMargin(QCP::MarginSide side);
// events:
virtual void mousePressEvent(QMouseEvent *event);
virtual void mouseMoveEvent(QMouseEvent *event);
virtual void mouseReleaseEvent(QMouseEvent *event);
virtual void wheelEvent(QWheelEvent *event);
// non-property methods:
void drawBackground(QCPPainter *painter);
void updateAxesOffset(QCPAxis::AxisType type);
private:
Q_DISABLE_COPY(QCPAxisRect)
friend class QCustomPlot;
};
class QCP_LIB_DECL QCPAbstractLegendItem : public QCPLayoutElement
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QCPLegend* parentLegend READ parentLegend)
Q_PROPERTY(QFont font READ font WRITE setFont)
Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor)
Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont)
Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor)
Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectionChanged)
Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectableChanged)
/// \endcond
public:
explicit QCPAbstractLegendItem(QCPLegend *parent);
// getters:
QCPLegend *parentLegend() const { return mParentLegend; }
QFont font() const { return mFont; }
QColor textColor() const { return mTextColor; }
QFont selectedFont() const { return mSelectedFont; }
QColor selectedTextColor() const { return mSelectedTextColor; }
bool selectable() const { return mSelectable; }
bool selected() const { return mSelected; }
// setters:
void setFont(const QFont &font);
void setTextColor(const QColor &color);
void setSelectedFont(const QFont &font);
void setSelectedTextColor(const QColor &color);
Q_SLOT void setSelectable(bool selectable);
Q_SLOT void setSelected(bool selected);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
signals:
void selectionChanged(bool selected);
void selectableChanged(bool selectable);
protected:
// property members:
QCPLegend *mParentLegend;
QFont mFont;
QColor mTextColor;
QFont mSelectedFont;
QColor mSelectedTextColor;
bool mSelectable, mSelected;
// reimplemented virtual methods:
virtual QCP::Interaction selectionCategory() const;
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const;
virtual QRect clipRect() const;
virtual void draw(QCPPainter *painter) = 0;
// events:
virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged);
virtual void deselectEvent(bool *selectionStateChanged);
private:
Q_DISABLE_COPY(QCPAbstractLegendItem)
friend class QCPLegend;
};
class QCP_LIB_DECL QCPPlottableLegendItem : public QCPAbstractLegendItem
{
Q_OBJECT
public:
QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable);
// getters:
QCPAbstractPlottable *plottable() { return mPlottable; }
protected:
// property members:
QCPAbstractPlottable *mPlottable;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter);
virtual QSize minimumSizeHint() const;
// non-virtual methods:
QPen getIconBorderPen() const;
QColor getTextColor() const;
QFont getFont() const;
};
class QCP_LIB_DECL QCPLegend : public QCPLayoutGrid
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QPen borderPen READ borderPen WRITE setBorderPen)
Q_PROPERTY(QBrush brush READ brush WRITE setBrush)
Q_PROPERTY(QFont font READ font WRITE setFont)
Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor)
Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize)
Q_PROPERTY(int iconTextPadding READ iconTextPadding WRITE setIconTextPadding)
Q_PROPERTY(QPen iconBorderPen READ iconBorderPen WRITE setIconBorderPen)
Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectionChanged)
Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectableChanged)
Q_PROPERTY(QPen selectedBorderPen READ selectedBorderPen WRITE setSelectedBorderPen)
Q_PROPERTY(QPen selectedIconBorderPen READ selectedIconBorderPen WRITE setSelectedIconBorderPen)
Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush)
Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont)
Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor)
/// \endcond
public:
/*!
Defines the selectable parts of a legend
\see setSelectedParts, setSelectableParts
*/
enum SelectablePart { spNone = 0x000 ///< <tt>0x000</tt> None
,spLegendBox = 0x001 ///< <tt>0x001</tt> The legend box (frame)
,spItems = 0x002 ///< <tt>0x002</tt> Legend items individually (see \ref selectedItems)
};
Q_FLAGS(SelectablePart SelectableParts)
Q_DECLARE_FLAGS(SelectableParts, SelectablePart)
explicit QCPLegend();
virtual ~QCPLegend();
// getters:
QPen borderPen() const { return mBorderPen; }
QBrush brush() const { return mBrush; }
QFont font() const { return mFont; }
QColor textColor() const { return mTextColor; }
QSize iconSize() const { return mIconSize; }
int iconTextPadding() const { return mIconTextPadding; }
QPen iconBorderPen() const { return mIconBorderPen; }
SelectableParts selectableParts() const { return mSelectableParts; }
SelectableParts selectedParts() const;
QPen selectedBorderPen() const { return mSelectedBorderPen; }
QPen selectedIconBorderPen() const { return mSelectedIconBorderPen; }
QBrush selectedBrush() const { return mSelectedBrush; }
QFont selectedFont() const { return mSelectedFont; }
QColor selectedTextColor() const { return mSelectedTextColor; }
// setters:
void setBorderPen(const QPen &pen);
void setBrush(const QBrush &brush);
void setFont(const QFont &font);
void setTextColor(const QColor &color);
void setIconSize(const QSize &size);
void setIconSize(int width, int height);
void setIconTextPadding(int padding);
void setIconBorderPen(const QPen &pen);
Q_SLOT void setSelectableParts(const SelectableParts &selectableParts);
Q_SLOT void setSelectedParts(const SelectableParts &selectedParts);
void setSelectedBorderPen(const QPen &pen);
void setSelectedIconBorderPen(const QPen &pen);
void setSelectedBrush(const QBrush &brush);
void setSelectedFont(const QFont &font);
void setSelectedTextColor(const QColor &color);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
// non-virtual methods:
QCPAbstractLegendItem *item(int index) const;
QCPPlottableLegendItem *itemWithPlottable(const QCPAbstractPlottable *plottable) const;
int itemCount() const;
bool hasItem(QCPAbstractLegendItem *item) const;
bool hasItemWithPlottable(const QCPAbstractPlottable *plottable) const;
bool addItem(QCPAbstractLegendItem *item);
bool removeItem(int index);
bool removeItem(QCPAbstractLegendItem *item);
void clearItems();
QList<QCPAbstractLegendItem*> selectedItems() const;
signals:
void selectionChanged(QCPLegend::SelectableParts parts);
void selectableChanged(QCPLegend::SelectableParts parts);
protected:
// property members:
QPen mBorderPen, mIconBorderPen;
QBrush mBrush;
QFont mFont;
QColor mTextColor;
QSize mIconSize;
int mIconTextPadding;
SelectableParts mSelectedParts, mSelectableParts;
QPen mSelectedBorderPen, mSelectedIconBorderPen;
QBrush mSelectedBrush;
QFont mSelectedFont;
QColor mSelectedTextColor;
// reimplemented virtual methods:
virtual void parentPlotInitialized(QCustomPlot *parentPlot);
virtual QCP::Interaction selectionCategory() const;
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const;
virtual void draw(QCPPainter *painter);
// events:
virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged);
virtual void deselectEvent(bool *selectionStateChanged);
// non-virtual methods:
QPen getBorderPen() const;
QBrush getBrush() const;
private:
Q_DISABLE_COPY(QCPLegend)
friend class QCustomPlot;
friend class QCPAbstractLegendItem;
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QCPLegend::SelectableParts)
Q_DECLARE_METATYPE(QCPLegend::SelectablePart)
class QCP_LIB_DECL QCPPlotTitle : public QCPLayoutElement
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QString text READ text WRITE setText)
Q_PROPERTY(QFont font READ font WRITE setFont)
Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor)
Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont)
Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor)
Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged)
Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged)
/// \endcond
public:
explicit QCPPlotTitle(QCustomPlot *parentPlot);
explicit QCPPlotTitle(QCustomPlot *parentPlot, const QString &text);
// getters:
QString text() const { return mText; }
QFont font() const { return mFont; }
QColor textColor() const { return mTextColor; }
QFont selectedFont() const { return mSelectedFont; }
QColor selectedTextColor() const { return mSelectedTextColor; }
bool selectable() const { return mSelectable; }
bool selected() const { return mSelected; }
// setters:
void setText(const QString &text);
void setFont(const QFont &font);
void setTextColor(const QColor &color);
void setSelectedFont(const QFont &font);
void setSelectedTextColor(const QColor &color);
Q_SLOT void setSelectable(bool selectable);
Q_SLOT void setSelected(bool selected);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
signals:
void selectionChanged(bool selected);
void selectableChanged(bool selectable);
protected:
// property members:
QString mText;
QFont mFont;
QColor mTextColor;
QFont mSelectedFont;
QColor mSelectedTextColor;
QRect mTextBoundingRect;
bool mSelectable, mSelected;
// reimplemented virtual methods:
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const;
virtual void draw(QCPPainter *painter);
virtual QSize minimumSizeHint() const;
virtual QSize maximumSizeHint() const;
// events:
virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged);
virtual void deselectEvent(bool *selectionStateChanged);
// non-virtual methods:
QFont mainFont() const;
QColor mainTextColor() const;
private:
Q_DISABLE_COPY(QCPPlotTitle)
};
class QCPColorScaleAxisRectPrivate : public QCPAxisRect
{
Q_OBJECT
public:
explicit QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale);
protected:
QCPColorScale *mParentColorScale;
QImage mGradientImage;
bool mGradientImageInvalidated;
// re-using some methods of QCPAxisRect to make them available to friend class QCPColorScale
using QCPAxisRect::calculateAutoMargin;
using QCPAxisRect::mousePressEvent;
using QCPAxisRect::mouseMoveEvent;
using QCPAxisRect::mouseReleaseEvent;
using QCPAxisRect::wheelEvent;
using QCPAxisRect::update;
virtual void draw(QCPPainter *painter);
void updateGradientImage();
Q_SLOT void axisSelectionChanged(QCPAxis::SelectableParts selectedParts);
Q_SLOT void axisSelectableChanged(QCPAxis::SelectableParts selectableParts);
friend class QCPColorScale;
};
class QCP_LIB_DECL QCPColorScale : public QCPLayoutElement
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QCPAxis::AxisType type READ type WRITE setType)
Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged)
Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged)
Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged)
Q_PROPERTY(QString label READ label WRITE setLabel)
Q_PROPERTY(int barWidth READ barWidth WRITE setBarWidth)
Q_PROPERTY(bool rangeDrag READ rangeDrag WRITE setRangeDrag)
Q_PROPERTY(bool rangeZoom READ rangeZoom WRITE setRangeZoom)
/// \endcond
public:
explicit QCPColorScale(QCustomPlot *parentPlot);
virtual ~QCPColorScale();
// getters:
QCPAxis *axis() const { return mColorAxis.data(); }
QCPAxis::AxisType type() const { return mType; }
QCPRange dataRange() const { return mDataRange; }
QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; }
QCPColorGradient gradient() const { return mGradient; }
QString label() const;
int barWidth () const { return mBarWidth; }
bool rangeDrag() const;
bool rangeZoom() const;
// setters:
void setType(QCPAxis::AxisType type);
Q_SLOT void setDataRange(const QCPRange &dataRange);
Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType);
Q_SLOT void setGradient(const QCPColorGradient &gradient);
void setLabel(const QString &str);
void setBarWidth(int width);
void setRangeDrag(bool enabled);
void setRangeZoom(bool enabled);
// non-property methods:
QList<QCPColorMap*> colorMaps() const;
void rescaleDataRange(bool onlyVisibleMaps);
// reimplemented virtual methods:
virtual void update(UpdatePhase phase);
signals:
void dataRangeChanged(QCPRange newRange);
void dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
void gradientChanged(QCPColorGradient newGradient);
protected:
// property members:
QCPAxis::AxisType mType;
QCPRange mDataRange;
QCPAxis::ScaleType mDataScaleType;
QCPColorGradient mGradient;
int mBarWidth;
// non-property members:
QPointer<QCPColorScaleAxisRectPrivate> mAxisRect;
QPointer<QCPAxis> mColorAxis;
// reimplemented virtual methods:
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const;
// events:
virtual void mousePressEvent(QMouseEvent *event);
virtual void mouseMoveEvent(QMouseEvent *event);
virtual void mouseReleaseEvent(QMouseEvent *event);
virtual void wheelEvent(QWheelEvent *event);
private:
Q_DISABLE_COPY(QCPColorScale)
friend class QCPColorScaleAxisRectPrivate;
};
/*! \file */
class QCP_LIB_DECL QCPData
{
public:
QCPData();
QCPData(double key, double value);
double key, value;
double keyErrorPlus, keyErrorMinus;
double valueErrorPlus, valueErrorMinus;
};
Q_DECLARE_TYPEINFO(QCPData, Q_MOVABLE_TYPE);
/*! \typedef QCPDataMap
Container for storing \ref QCPData items in a sorted fashion. The key of the map
is the key member of the QCPData instance.
This is the container in which QCPGraph holds its data.
\see QCPData, QCPGraph::setData
*/
typedef QMap<double, QCPData> QCPDataMap;
typedef QMapIterator<double, QCPData> QCPDataMapIterator;
typedef QMutableMapIterator<double, QCPData> QCPDataMutableMapIterator;
class QCP_LIB_DECL QCPGraph : public QCPAbstractPlottable
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle)
Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle)
Q_PROPERTY(ErrorType errorType READ errorType WRITE setErrorType)
Q_PROPERTY(QPen errorPen READ errorPen WRITE setErrorPen)
Q_PROPERTY(double errorBarSize READ errorBarSize WRITE setErrorBarSize)
Q_PROPERTY(bool errorBarSkipSymbol READ errorBarSkipSymbol WRITE setErrorBarSkipSymbol)
Q_PROPERTY(QCPGraph* channelFillGraph READ channelFillGraph WRITE setChannelFillGraph)
Q_PROPERTY(bool adaptiveSampling READ adaptiveSampling WRITE setAdaptiveSampling)
/// \endcond
public:
/*!
Defines how the graph's line is represented visually in the plot. The line is drawn with the
current pen of the graph (\ref setPen).
\see setLineStyle
*/
enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented
///< with symbols according to the scatter style, see \ref setScatterStyle)
,lsLine ///< data points are connected by a straight line
,lsStepLeft ///< line is drawn as steps where the step height is the value of the left data point
,lsStepRight ///< line is drawn as steps where the step height is the value of the right data point
,lsStepCenter ///< line is drawn as steps where the step is in between two data points
,lsImpulse ///< each data point is represented by a line parallel to the value axis, which reaches from the data point to the zero-value-line
};
Q_ENUMS(LineStyle)
/*!
Defines what kind of error bars are drawn for each data point
*/
enum ErrorType { etNone ///< No error bars are shown
,etKey ///< Error bars for the key dimension of the data point are shown
,etValue ///< Error bars for the value dimension of the data point are shown
,etBoth ///< Error bars for both key and value dimensions of the data point are shown
};
Q_ENUMS(ErrorType)
explicit QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis);
virtual ~QCPGraph();
// getters:
QCPDataMap *data() const { return mData; }
LineStyle lineStyle() const { return mLineStyle; }
QCPScatterStyle scatterStyle() const { return mScatterStyle; }
ErrorType errorType() const { return mErrorType; }
QPen errorPen() const { return mErrorPen; }
double errorBarSize() const { return mErrorBarSize; }
bool errorBarSkipSymbol() const { return mErrorBarSkipSymbol; }
QCPGraph *channelFillGraph() const { return mChannelFillGraph.data(); }
bool adaptiveSampling() const { return mAdaptiveSampling; }
// setters:
void setData(QCPDataMap *data, bool copy=false);
void setData(const QVector<double> &key, const QVector<double> &value);
void setDataKeyError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyError);
void setDataKeyError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyErrorMinus, const QVector<double> &keyErrorPlus);
void setDataValueError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &valueError);
void setDataValueError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &valueErrorMinus, const QVector<double> &valueErrorPlus);
void setDataBothError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyError, const QVector<double> &valueError);
void setDataBothError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyErrorMinus, const QVector<double> &keyErrorPlus, const QVector<double> &valueErrorMinus, const QVector<double> &valueErrorPlus);
void setLineStyle(LineStyle ls);
void setScatterStyle(const QCPScatterStyle &style);
void setErrorType(ErrorType errorType);
void setErrorPen(const QPen &pen);
void setErrorBarSize(double size);
void setErrorBarSkipSymbol(bool enabled);
void setChannelFillGraph(QCPGraph *targetGraph);
void setAdaptiveSampling(bool enabled);
// non-property methods:
void addData(const QCPDataMap &dataMap);
void addData(const QCPData &data);
void addData(double key, double value);
void addData(const QVector<double> &keys, const QVector<double> &values);
void removeDataBefore(double key);
void removeDataAfter(double key);
void removeData(double fromKey, double toKey);
void removeData(double key);
// reimplemented virtual methods:
virtual void clearData();
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
using QCPAbstractPlottable::rescaleAxes;
using QCPAbstractPlottable::rescaleKeyAxis;
using QCPAbstractPlottable::rescaleValueAxis;
void rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface
void rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface
void rescaleValueAxis(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface
protected:
// property members:
QCPDataMap *mData;
QPen mErrorPen;
LineStyle mLineStyle;
QCPScatterStyle mScatterStyle;
ErrorType mErrorType;
double mErrorBarSize;
bool mErrorBarSkipSymbol;
QPointer<QCPGraph> mChannelFillGraph;
bool mAdaptiveSampling;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter);
virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const;
virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const;
virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const;
virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const; // overloads base class interface
virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const; // overloads base class interface
// introduced virtual methods:
virtual void drawFill(QCPPainter *painter, QVector<QPointF> *lineData) const;
virtual void drawScatterPlot(QCPPainter *painter, QVector<QCPData> *scatterData) const;
virtual void drawLinePlot(QCPPainter *painter, QVector<QPointF> *lineData) const;
virtual void drawImpulsePlot(QCPPainter *painter, QVector<QPointF> *lineData) const;
// non-virtual methods:
void getPreparedData(QVector<QCPData> *lineData, QVector<QCPData> *scatterData) const;
void getPlotData(QVector<QPointF> *lineData, QVector<QCPData> *scatterData) const;
void getScatterPlotData(QVector<QCPData> *scatterData) const;
void getLinePlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const;
void getStepLeftPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const;
void getStepRightPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const;
void getStepCenterPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const;
void getImpulsePlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const;
void drawError(QCPPainter *painter, double x, double y, const QCPData &data) const;
void getVisibleDataBounds(QCPDataMap::const_iterator &lower, QCPDataMap::const_iterator &upper) const;
int countDataInBounds(const QCPDataMap::const_iterator &lower, const QCPDataMap::const_iterator &upper, int maxCount) const;
void addFillBasePoints(QVector<QPointF> *lineData) const;
void removeFillBasePoints(QVector<QPointF> *lineData) const;
QPointF lowerFillBasePoint(double lowerKey) const;
QPointF upperFillBasePoint(double upperKey) const;
const QPolygonF getChannelFillPolygon(const QVector<QPointF> *lineData) const;
int findIndexBelowX(const QVector<QPointF> *data, double x) const;
int findIndexAboveX(const QVector<QPointF> *data, double x) const;
int findIndexBelowY(const QVector<QPointF> *data, double y) const;
int findIndexAboveY(const QVector<QPointF> *data, double y) const;
double pointDistance(const QPointF &pixelPoint) const;
friend class QCustomPlot;
friend class QCPLegend;
};
/*! \file */
class QCP_LIB_DECL QCPCurveData
{
public:
QCPCurveData();
QCPCurveData(double t, double key, double value);
double t, key, value;
};
Q_DECLARE_TYPEINFO(QCPCurveData, Q_MOVABLE_TYPE);
/*! \typedef QCPCurveDataMap
Container for storing \ref QCPCurveData items in a sorted fashion. The key of the map
is the t member of the QCPCurveData instance.
This is the container in which QCPCurve holds its data.
\see QCPCurveData, QCPCurve::setData
*/
typedef QMap<double, QCPCurveData> QCPCurveDataMap;
typedef QMapIterator<double, QCPCurveData> QCPCurveDataMapIterator;
typedef QMutableMapIterator<double, QCPCurveData> QCPCurveDataMutableMapIterator;
class QCP_LIB_DECL QCPCurve : public QCPAbstractPlottable
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle)
Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle)
/// \endcond
public:
/*!
Defines how the curve's line is represented visually in the plot. The line is drawn with the
current pen of the curve (\ref setPen).
\see setLineStyle
*/
enum LineStyle { lsNone ///< No line is drawn between data points (e.g. only scatters)
,lsLine ///< Data points are connected with a straight line
};
explicit QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis);
virtual ~QCPCurve();
// getters:
QCPCurveDataMap *data() const { return mData; }
QCPScatterStyle scatterStyle() const { return mScatterStyle; }
LineStyle lineStyle() const { return mLineStyle; }
// setters:
void setData(QCPCurveDataMap *data, bool copy=false);
void setData(const QVector<double> &t, const QVector<double> &key, const QVector<double> &value);
void setData(const QVector<double> &key, const QVector<double> &value);
void setScatterStyle(const QCPScatterStyle &style);
void setLineStyle(LineStyle style);
// non-property methods:
void addData(const QCPCurveDataMap &dataMap);
void addData(const QCPCurveData &data);
void addData(double t, double key, double value);
void addData(double key, double value);
void addData(const QVector<double> &ts, const QVector<double> &keys, const QVector<double> &values);
void removeDataBefore(double t);
void removeDataAfter(double t);
void removeData(double fromt, double tot);
void removeData(double t);
// reimplemented virtual methods:
virtual void clearData();
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
protected:
// property members:
QCPCurveDataMap *mData;
QCPScatterStyle mScatterStyle;
LineStyle mLineStyle;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter);
virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const;
virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const;
virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const;
// introduced virtual methods:
virtual void drawScatterPlot(QCPPainter *painter, const QVector<QPointF> *pointData) const;
// non-virtual methods:
void getCurveData(QVector<QPointF> *lineData) const;
int getRegion(double x, double y, double rectLeft, double rectTop, double rectRight, double rectBottom) const;
QPointF getOptimizedPoint(int prevRegion, double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const;
QVector<QPointF> getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const;
bool mayTraverse(int prevRegion, int currentRegion) const;
bool getTraverse(double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom, QPointF &crossA, QPointF &crossB) const;
void getTraverseCornerPoints(int prevRegion, int currentRegion, double rectLeft, double rectTop, double rectRight, double rectBottom, QVector<QPointF> &beforeTraverse, QVector<QPointF> &afterTraverse) const;
double pointDistance(const QPointF &pixelPoint) const;
friend class QCustomPlot;
friend class QCPLegend;
};
/*! \file */
class QCP_LIB_DECL QCPBarsGroup : public QObject
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(SpacingType spacingType READ spacingType WRITE setSpacingType)
Q_PROPERTY(double spacing READ spacing WRITE setSpacing)
/// \endcond
public:
/*!
Defines the ways the spacing between bars in the group can be specified. Thus it defines what
the number passed to \ref setSpacing actually means.
\see setSpacingType, setSpacing
*/
enum SpacingType { stAbsolute ///< Bar spacing is in absolute pixels
,stAxisRectRatio ///< Bar spacing is given by a fraction of the axis rect size
,stPlotCoords ///< Bar spacing is in key coordinates and thus scales with the key axis range
};
QCPBarsGroup(QCustomPlot *parentPlot);
~QCPBarsGroup();
// getters:
SpacingType spacingType() const { return mSpacingType; }
double spacing() const { return mSpacing; }
// setters:
void setSpacingType(SpacingType spacingType);
void setSpacing(double spacing);
// non-virtual methods:
QList<QCPBars*> bars() const { return mBars; }
QCPBars* bars(int index) const;
int size() const { return mBars.size(); }
bool isEmpty() const { return mBars.isEmpty(); }
void clear();
bool contains(QCPBars *bars) const { return mBars.contains(bars); }
void append(QCPBars *bars);
void insert(int i, QCPBars *bars);
void remove(QCPBars *bars);
protected:
// non-property members:
QCustomPlot *mParentPlot;
SpacingType mSpacingType;
double mSpacing;
QList<QCPBars*> mBars;
// non-virtual methods:
void registerBars(QCPBars *bars);
void unregisterBars(QCPBars *bars);
// virtual methods:
double keyPixelOffset(const QCPBars *bars, double keyCoord);
double getPixelSpacing(const QCPBars *bars, double keyCoord);
private:
Q_DISABLE_COPY(QCPBarsGroup)
friend class QCPBars;
};
class QCP_LIB_DECL QCPBarData
{
public:
QCPBarData();
QCPBarData(double key, double value);
double key, value;
};
Q_DECLARE_TYPEINFO(QCPBarData, Q_MOVABLE_TYPE);
/*! \typedef QCPBarDataMap
Container for storing \ref QCPBarData items in a sorted fashion. The key of the map
is the key member of the QCPBarData instance.
This is the container in which QCPBars holds its data.
\see QCPBarData, QCPBars::setData
*/
typedef QMap<double, QCPBarData> QCPBarDataMap;
typedef QMapIterator<double, QCPBarData> QCPBarDataMapIterator;
typedef QMutableMapIterator<double, QCPBarData> QCPBarDataMutableMapIterator;
class QCP_LIB_DECL QCPBars : public QCPAbstractPlottable
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(double width READ width WRITE setWidth)
Q_PROPERTY(WidthType widthType READ widthType WRITE setWidthType)
Q_PROPERTY(QCPBarsGroup* barsGroup READ barsGroup WRITE setBarsGroup)
Q_PROPERTY(double baseValue READ baseValue WRITE setBaseValue)
Q_PROPERTY(QCPBars* barBelow READ barBelow)
Q_PROPERTY(QCPBars* barAbove READ barAbove)
/// \endcond
public:
/*!
Defines the ways the width of the bar can be specified. Thus it defines what the number passed
to \ref setWidth actually means.
\see setWidthType, setWidth
*/
enum WidthType { wtAbsolute ///< Bar width is in absolute pixels
,wtAxisRectRatio ///< Bar width is given by a fraction of the axis rect size
,wtPlotCoords ///< Bar width is in key coordinates and thus scales with the key axis range
};
Q_ENUMS(WidthType)
explicit QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis);
virtual ~QCPBars();
// getters:
double width() const { return mWidth; }
WidthType widthType() const { return mWidthType; }
QCPBarsGroup *barsGroup() const { return mBarsGroup; }
double baseValue() const { return mBaseValue; }
QCPBars *barBelow() const { return mBarBelow.data(); }
QCPBars *barAbove() const { return mBarAbove.data(); }
QCPBarDataMap *data() const { return mData; }
// setters:
void setWidth(double width);
void setWidthType(WidthType widthType);
void setBarsGroup(QCPBarsGroup *barsGroup);
void setBaseValue(double baseValue);
void setData(QCPBarDataMap *data, bool copy=false);
void setData(const QVector<double> &key, const QVector<double> &value);
// non-property methods:
void moveBelow(QCPBars *bars);
void moveAbove(QCPBars *bars);
void addData(const QCPBarDataMap &dataMap);
void addData(const QCPBarData &data);
void addData(double key, double value);
void addData(const QVector<double> &keys, const QVector<double> &values);
void removeDataBefore(double key);
void removeDataAfter(double key);
void removeData(double fromKey, double toKey);
void removeData(double key);
// reimplemented virtual methods:
virtual void clearData();
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
protected:
// property members:
QCPBarDataMap *mData;
double mWidth;
WidthType mWidthType;
QCPBarsGroup *mBarsGroup;
double mBaseValue;
QPointer<QCPBars> mBarBelow, mBarAbove;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter);
virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const;
virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const;
virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const;
// non-virtual methods:
void getVisibleDataBounds(QCPBarDataMap::const_iterator &lower, QCPBarDataMap::const_iterator &upperEnd) const;
QPolygonF getBarPolygon(double key, double value) const;
void getPixelWidth(double key, double &lower, double &upper) const;
double getStackedBaseValue(double key, bool positive) const;
static void connectBars(QCPBars* lower, QCPBars* upper);
friend class QCustomPlot;
friend class QCPLegend;
friend class QCPBarsGroup;
};
/*! \file */
class QCP_LIB_DECL QCPStatisticalBox : public QCPAbstractPlottable
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(double key READ key WRITE setKey)
Q_PROPERTY(double minimum READ minimum WRITE setMinimum)
Q_PROPERTY(double lowerQuartile READ lowerQuartile WRITE setLowerQuartile)
Q_PROPERTY(double median READ median WRITE setMedian)
Q_PROPERTY(double upperQuartile READ upperQuartile WRITE setUpperQuartile)
Q_PROPERTY(double maximum READ maximum WRITE setMaximum)
Q_PROPERTY(QVector<double> outliers READ outliers WRITE setOutliers)
Q_PROPERTY(double width READ width WRITE setWidth)
Q_PROPERTY(double whiskerWidth READ whiskerWidth WRITE setWhiskerWidth)
Q_PROPERTY(QPen whiskerPen READ whiskerPen WRITE setWhiskerPen)
Q_PROPERTY(QPen whiskerBarPen READ whiskerBarPen WRITE setWhiskerBarPen)
Q_PROPERTY(QPen medianPen READ medianPen WRITE setMedianPen)
Q_PROPERTY(QCPScatterStyle outlierStyle READ outlierStyle WRITE setOutlierStyle)
/// \endcond
public:
explicit QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis);
// getters:
double key() const { return mKey; }
double minimum() const { return mMinimum; }
double lowerQuartile() const { return mLowerQuartile; }
double median() const { return mMedian; }
double upperQuartile() const { return mUpperQuartile; }
double maximum() const { return mMaximum; }
QVector<double> outliers() const { return mOutliers; }
double width() const { return mWidth; }
double whiskerWidth() const { return mWhiskerWidth; }
QPen whiskerPen() const { return mWhiskerPen; }
QPen whiskerBarPen() const { return mWhiskerBarPen; }
QPen medianPen() const { return mMedianPen; }
QCPScatterStyle outlierStyle() const { return mOutlierStyle; }
// setters:
void setKey(double key);
void setMinimum(double value);
void setLowerQuartile(double value);
void setMedian(double value);
void setUpperQuartile(double value);
void setMaximum(double value);
void setOutliers(const QVector<double> &values);
void setData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum);
void setWidth(double width);
void setWhiskerWidth(double width);
void setWhiskerPen(const QPen &pen);
void setWhiskerBarPen(const QPen &pen);
void setMedianPen(const QPen &pen);
void setOutlierStyle(const QCPScatterStyle &style);
// non-property methods:
virtual void clearData();
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
protected:
// property members:
QVector<double> mOutliers;
double mKey, mMinimum, mLowerQuartile, mMedian, mUpperQuartile, mMaximum;
double mWidth;
double mWhiskerWidth;
QPen mWhiskerPen, mWhiskerBarPen, mMedianPen;
QCPScatterStyle mOutlierStyle;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter);
virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const;
virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const;
virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const;
// introduced virtual methods:
virtual void drawQuartileBox(QCPPainter *painter, QRectF *quartileBox=0) const;
virtual void drawMedian(QCPPainter *painter) const;
virtual void drawWhiskers(QCPPainter *painter) const;
virtual void drawOutliers(QCPPainter *painter) const;
friend class QCustomPlot;
friend class QCPLegend;
};
class QCP_LIB_DECL QCPColorMapData
{
public:
QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange);
~QCPColorMapData();
QCPColorMapData(const QCPColorMapData &other);
QCPColorMapData &operator=(const QCPColorMapData &other);
// getters:
int keySize() const { return mKeySize; }
int valueSize() const { return mValueSize; }
QCPRange keyRange() const { return mKeyRange; }
QCPRange valueRange() const { return mValueRange; }
QCPRange dataBounds() const { return mDataBounds; }
double data(double key, double value);
double cell(int keyIndex, int valueIndex);
// setters:
void setSize(int keySize, int valueSize);
void setKeySize(int keySize);
void setValueSize(int valueSize);
void setRange(const QCPRange &keyRange, const QCPRange &valueRange);
void setKeyRange(const QCPRange &keyRange);
void setValueRange(const QCPRange &valueRange);
void setData(double key, double value, double z);
void setCell(int keyIndex, int valueIndex, double z);
// non-property methods:
void recalculateDataBounds();
void clear();
void fill(double z);
bool isEmpty() const { return mIsEmpty; }
void coordToCell(double key, double value, int *keyIndex, int *valueIndex) const;
void cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const;
protected:
// property members:
int mKeySize, mValueSize;
QCPRange mKeyRange, mValueRange;
bool mIsEmpty;
// non-property members:
double *mData;
QCPRange mDataBounds;
bool mDataModified;
friend class QCPColorMap;
};
class QCP_LIB_DECL QCPColorMap : public QCPAbstractPlottable
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged)
Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged)
Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged)
Q_PROPERTY(bool interpolate READ interpolate WRITE setInterpolate)
Q_PROPERTY(bool tightBoundary READ tightBoundary WRITE setTightBoundary)
Q_PROPERTY(QCPColorScale* colorScale READ colorScale WRITE setColorScale)
/// \endcond
public:
explicit QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis);
virtual ~QCPColorMap();
// getters:
QCPColorMapData *data() const { return mMapData; }
QCPRange dataRange() const { return mDataRange; }
QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; }
bool interpolate() const { return mInterpolate; }
bool tightBoundary() const { return mTightBoundary; }
QCPColorGradient gradient() const { return mGradient; }
QCPColorScale *colorScale() const { return mColorScale.data(); }
// setters:
void setData(QCPColorMapData *data, bool copy=false);
Q_SLOT void setDataRange(const QCPRange &dataRange);
Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType);
Q_SLOT void setGradient(const QCPColorGradient &gradient);
void setInterpolate(bool enabled);
void setTightBoundary(bool enabled);
void setColorScale(QCPColorScale *colorScale);
// non-property methods:
void rescaleDataRange(bool recalculateDataBounds=false);
Q_SLOT void updateLegendIcon(Qt::TransformationMode transformMode=Qt::SmoothTransformation, const QSize &thumbSize=QSize(32, 18));
// reimplemented virtual methods:
virtual void clearData();
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
signals:
void dataRangeChanged(QCPRange newRange);
void dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
void gradientChanged(QCPColorGradient newGradient);
protected:
// property members:
QCPRange mDataRange;
QCPAxis::ScaleType mDataScaleType;
QCPColorMapData *mMapData;
QCPColorGradient mGradient;
bool mInterpolate;
bool mTightBoundary;
QPointer<QCPColorScale> mColorScale;
// non-property members:
QImage mMapImage, mUndersampledMapImage;
QPixmap mLegendIcon;
bool mMapImageInvalidated;
// introduced virtual methods:
virtual void updateMapImage();
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter);
virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const;
virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const;
virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const;
friend class QCustomPlot;
friend class QCPLegend;
};
/*! \file */
class QCP_LIB_DECL QCPFinancialData
{
public:
QCPFinancialData();
QCPFinancialData(double key, double open, double high, double low, double close);
double key, open, high, low, close;
};
Q_DECLARE_TYPEINFO(QCPFinancialData, Q_MOVABLE_TYPE);
/*! \typedef QCPFinancialDataMap
Container for storing \ref QCPFinancialData items in a sorted fashion. The key of the map
is the key member of the QCPFinancialData instance.
This is the container in which QCPFinancial holds its data.
\see QCPFinancial, QCPFinancial::setData
*/
typedef QMap<double, QCPFinancialData> QCPFinancialDataMap;
typedef QMapIterator<double, QCPFinancialData> QCPFinancialDataMapIterator;
typedef QMutableMapIterator<double, QCPFinancialData> QCPFinancialDataMutableMapIterator;
class QCP_LIB_DECL QCPFinancial : public QCPAbstractPlottable
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(ChartStyle chartStyle READ chartStyle WRITE setChartStyle)
Q_PROPERTY(double width READ width WRITE setWidth)
Q_PROPERTY(bool twoColored READ twoColored WRITE setTwoColored)
Q_PROPERTY(QBrush brushPositive READ brushPositive WRITE setBrushPositive)
Q_PROPERTY(QBrush brushNegative READ brushNegative WRITE setBrushNegative)
Q_PROPERTY(QPen penPositive READ penPositive WRITE setPenPositive)
Q_PROPERTY(QPen penNegative READ penNegative WRITE setPenNegative)
/// \endcond
public:
/*!
Defines the possible representations of OHLC data in the plot.
\see setChartStyle
*/
enum ChartStyle { csOhlc ///< Open-High-Low-Close bar representation
,csCandlestick ///< Candlestick representation
};
Q_ENUMS(ChartStyle)
explicit QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis);
virtual ~QCPFinancial();
// getters:
QCPFinancialDataMap *data() const { return mData; }
ChartStyle chartStyle() const { return mChartStyle; }
double width() const { return mWidth; }
bool twoColored() const { return mTwoColored; }
QBrush brushPositive() const { return mBrushPositive; }
QBrush brushNegative() const { return mBrushNegative; }
QPen penPositive() const { return mPenPositive; }
QPen penNegative() const { return mPenNegative; }
// setters:
void setData(QCPFinancialDataMap *data, bool copy=false);
void setData(const QVector<double> &key, const QVector<double> &open, const QVector<double> &high, const QVector<double> &low, const QVector<double> &close);
void setChartStyle(ChartStyle style);
void setWidth(double width);
void setTwoColored(bool twoColored);
void setBrushPositive(const QBrush &brush);
void setBrushNegative(const QBrush &brush);
void setPenPositive(const QPen &pen);
void setPenNegative(const QPen &pen);
// non-property methods:
void addData(const QCPFinancialDataMap &dataMap);
void addData(const QCPFinancialData &data);
void addData(double key, double open, double high, double low, double close);
void addData(const QVector<double> &key, const QVector<double> &open, const QVector<double> &high, const QVector<double> &low, const QVector<double> &close);
void removeDataBefore(double key);
void removeDataAfter(double key);
void removeData(double fromKey, double toKey);
void removeData(double key);
// reimplemented virtual methods:
virtual void clearData();
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
// static methods:
static QCPFinancialDataMap timeSeriesToOhlc(const QVector<double> &time, const QVector<double> &value, double timeBinSize, double timeBinOffset = 0);
protected:
// property members:
QCPFinancialDataMap *mData;
ChartStyle mChartStyle;
double mWidth;
bool mTwoColored;
QBrush mBrushPositive, mBrushNegative;
QPen mPenPositive, mPenNegative;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter);
virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const;
virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const;
virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const;
// non-virtual methods:
void drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end);
void drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end);
double ohlcSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const;
double candlestickSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const;
void getVisibleDataBounds(QCPFinancialDataMap::const_iterator &lower, QCPFinancialDataMap::const_iterator &upper) const;
friend class QCustomPlot;
friend class QCPLegend;
};
class QCP_LIB_DECL QCPItemStraightLine : public QCPAbstractItem
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen)
/// \endcond
public:
QCPItemStraightLine(QCustomPlot *parentPlot);
virtual ~QCPItemStraightLine();
// getters:
QPen pen() const { return mPen; }
QPen selectedPen() const { return mSelectedPen; }
// setters;
void setPen(const QPen &pen);
void setSelectedPen(const QPen &pen);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
QCPItemPosition * const point1;
QCPItemPosition * const point2;
protected:
// property members:
QPen mPen, mSelectedPen;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter);
// non-virtual methods:
double distToStraightLine(const QVector2D &point1, const QVector2D &vec, const QVector2D &point) const;
QLineF getRectClippedStraightLine(const QVector2D &point1, const QVector2D &vec, const QRect &rect) const;
QPen mainPen() const;
};
class QCP_LIB_DECL QCPItemLine : public QCPAbstractItem
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen)
Q_PROPERTY(QCPLineEnding head READ head WRITE setHead)
Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail)
/// \endcond
public:
QCPItemLine(QCustomPlot *parentPlot);
virtual ~QCPItemLine();
// getters:
QPen pen() const { return mPen; }
QPen selectedPen() const { return mSelectedPen; }
QCPLineEnding head() const { return mHead; }
QCPLineEnding tail() const { return mTail; }
// setters;
void setPen(const QPen &pen);
void setSelectedPen(const QPen &pen);
void setHead(const QCPLineEnding &head);
void setTail(const QCPLineEnding &tail);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
QCPItemPosition * const start;
QCPItemPosition * const end;
protected:
// property members:
QPen mPen, mSelectedPen;
QCPLineEnding mHead, mTail;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter);
// non-virtual methods:
QLineF getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const;
QPen mainPen() const;
};
class QCP_LIB_DECL QCPItemCurve : public QCPAbstractItem
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen)
Q_PROPERTY(QCPLineEnding head READ head WRITE setHead)
Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail)
/// \endcond
public:
QCPItemCurve(QCustomPlot *parentPlot);
virtual ~QCPItemCurve();
// getters:
QPen pen() const { return mPen; }
QPen selectedPen() const { return mSelectedPen; }
QCPLineEnding head() const { return mHead; }
QCPLineEnding tail() const { return mTail; }
// setters;
void setPen(const QPen &pen);
void setSelectedPen(const QPen &pen);
void setHead(const QCPLineEnding &head);
void setTail(const QCPLineEnding &tail);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
QCPItemPosition * const start;
QCPItemPosition * const startDir;
QCPItemPosition * const endDir;
QCPItemPosition * const end;
protected:
// property members:
QPen mPen, mSelectedPen;
QCPLineEnding mHead, mTail;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter);
// non-virtual methods:
QPen mainPen() const;
};
class QCP_LIB_DECL QCPItemRect : public QCPAbstractItem
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen)
Q_PROPERTY(QBrush brush READ brush WRITE setBrush)
Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush)
/// \endcond
public:
QCPItemRect(QCustomPlot *parentPlot);
virtual ~QCPItemRect();
// getters:
QPen pen() const { return mPen; }
QPen selectedPen() const { return mSelectedPen; }
QBrush brush() const { return mBrush; }
QBrush selectedBrush() const { return mSelectedBrush; }
// setters;
void setPen(const QPen &pen);
void setSelectedPen(const QPen &pen);
void setBrush(const QBrush &brush);
void setSelectedBrush(const QBrush &brush);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
QCPItemPosition * const topLeft;
QCPItemPosition * const bottomRight;
QCPItemAnchor * const top;
QCPItemAnchor * const topRight;
QCPItemAnchor * const right;
QCPItemAnchor * const bottom;
QCPItemAnchor * const bottomLeft;
QCPItemAnchor * const left;
protected:
enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft};
// property members:
QPen mPen, mSelectedPen;
QBrush mBrush, mSelectedBrush;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter);
virtual QPointF anchorPixelPoint(int anchorId) const;
// non-virtual methods:
QPen mainPen() const;
QBrush mainBrush() const;
};
class QCP_LIB_DECL QCPItemText : public QCPAbstractItem
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QColor color READ color WRITE setColor)
Q_PROPERTY(QColor selectedColor READ selectedColor WRITE setSelectedColor)
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen)
Q_PROPERTY(QBrush brush READ brush WRITE setBrush)
Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush)
Q_PROPERTY(QFont font READ font WRITE setFont)
Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont)
Q_PROPERTY(QString text READ text WRITE setText)
Q_PROPERTY(Qt::Alignment positionAlignment READ positionAlignment WRITE setPositionAlignment)
Q_PROPERTY(Qt::Alignment textAlignment READ textAlignment WRITE setTextAlignment)
Q_PROPERTY(double rotation READ rotation WRITE setRotation)
Q_PROPERTY(QMargins padding READ padding WRITE setPadding)
/// \endcond
public:
QCPItemText(QCustomPlot *parentPlot);
virtual ~QCPItemText();
// getters:
QColor color() const { return mColor; }
QColor selectedColor() const { return mSelectedColor; }
QPen pen() const { return mPen; }
QPen selectedPen() const { return mSelectedPen; }
QBrush brush() const { return mBrush; }
QBrush selectedBrush() const { return mSelectedBrush; }
QFont font() const { return mFont; }
QFont selectedFont() const { return mSelectedFont; }
QString text() const { return mText; }
Qt::Alignment positionAlignment() const { return mPositionAlignment; }
Qt::Alignment textAlignment() const { return mTextAlignment; }
double rotation() const { return mRotation; }
QMargins padding() const { return mPadding; }
// setters;
void setColor(const QColor &color);
void setSelectedColor(const QColor &color);
void setPen(const QPen &pen);
void setSelectedPen(const QPen &pen);
void setBrush(const QBrush &brush);
void setSelectedBrush(const QBrush &brush);
void setFont(const QFont &font);
void setSelectedFont(const QFont &font);
void setText(const QString &text);
void setPositionAlignment(Qt::Alignment alignment);
void setTextAlignment(Qt::Alignment alignment);
void setRotation(double degrees);
void setPadding(const QMargins &padding);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
QCPItemPosition * const position;
QCPItemAnchor * const topLeft;
QCPItemAnchor * const top;
QCPItemAnchor * const topRight;
QCPItemAnchor * const right;
QCPItemAnchor * const bottomRight;
QCPItemAnchor * const bottom;
QCPItemAnchor * const bottomLeft;
QCPItemAnchor * const left;
protected:
enum AnchorIndex {aiTopLeft, aiTop, aiTopRight, aiRight, aiBottomRight, aiBottom, aiBottomLeft, aiLeft};
// property members:
QColor mColor, mSelectedColor;
QPen mPen, mSelectedPen;
QBrush mBrush, mSelectedBrush;
QFont mFont, mSelectedFont;
QString mText;
Qt::Alignment mPositionAlignment;
Qt::Alignment mTextAlignment;
double mRotation;
QMargins mPadding;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter);
virtual QPointF anchorPixelPoint(int anchorId) const;
// non-virtual methods:
QPointF getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const;
QFont mainFont() const;
QColor mainColor() const;
QPen mainPen() const;
QBrush mainBrush() const;
};
class QCP_LIB_DECL QCPItemEllipse : public QCPAbstractItem
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen)
Q_PROPERTY(QBrush brush READ brush WRITE setBrush)
Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush)
/// \endcond
public:
QCPItemEllipse(QCustomPlot *parentPlot);
virtual ~QCPItemEllipse();
// getters:
QPen pen() const { return mPen; }
QPen selectedPen() const { return mSelectedPen; }
QBrush brush() const { return mBrush; }
QBrush selectedBrush() const { return mSelectedBrush; }
// setters;
void setPen(const QPen &pen);
void setSelectedPen(const QPen &pen);
void setBrush(const QBrush &brush);
void setSelectedBrush(const QBrush &brush);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
QCPItemPosition * const topLeft;
QCPItemPosition * const bottomRight;
QCPItemAnchor * const topLeftRim;
QCPItemAnchor * const top;
QCPItemAnchor * const topRightRim;
QCPItemAnchor * const right;
QCPItemAnchor * const bottomRightRim;
QCPItemAnchor * const bottom;
QCPItemAnchor * const bottomLeftRim;
QCPItemAnchor * const left;
QCPItemAnchor * const center;
protected:
enum AnchorIndex {aiTopLeftRim, aiTop, aiTopRightRim, aiRight, aiBottomRightRim, aiBottom, aiBottomLeftRim, aiLeft, aiCenter};
// property members:
QPen mPen, mSelectedPen;
QBrush mBrush, mSelectedBrush;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter);
virtual QPointF anchorPixelPoint(int anchorId) const;
// non-virtual methods:
QPen mainPen() const;
QBrush mainBrush() const;
};
class QCP_LIB_DECL QCPItemPixmap : public QCPAbstractItem
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap)
Q_PROPERTY(bool scaled READ scaled WRITE setScaled)
Q_PROPERTY(Qt::AspectRatioMode aspectRatioMode READ aspectRatioMode)
Q_PROPERTY(Qt::TransformationMode transformationMode READ transformationMode)
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen)
/// \endcond
public:
QCPItemPixmap(QCustomPlot *parentPlot);
virtual ~QCPItemPixmap();
// getters:
QPixmap pixmap() const { return mPixmap; }
bool scaled() const { return mScaled; }
Qt::AspectRatioMode aspectRatioMode() const { return mAspectRatioMode; }
Qt::TransformationMode transformationMode() const { return mTransformationMode; }
QPen pen() const { return mPen; }
QPen selectedPen() const { return mSelectedPen; }
// setters;
void setPixmap(const QPixmap &pixmap);
void setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode=Qt::KeepAspectRatio, Qt::TransformationMode transformationMode=Qt::SmoothTransformation);
void setPen(const QPen &pen);
void setSelectedPen(const QPen &pen);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
QCPItemPosition * const topLeft;
QCPItemPosition * const bottomRight;
QCPItemAnchor * const top;
QCPItemAnchor * const topRight;
QCPItemAnchor * const right;
QCPItemAnchor * const bottom;
QCPItemAnchor * const bottomLeft;
QCPItemAnchor * const left;
protected:
enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft};
// property members:
QPixmap mPixmap;
QPixmap mScaledPixmap;
bool mScaled;
bool mScaledPixmapInvalidated;
Qt::AspectRatioMode mAspectRatioMode;
Qt::TransformationMode mTransformationMode;
QPen mPen, mSelectedPen;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter);
virtual QPointF anchorPixelPoint(int anchorId) const;
// non-virtual methods:
void updateScaledPixmap(QRect finalRect=QRect(), bool flipHorz=false, bool flipVert=false);
QRect getFinalRect(bool *flippedHorz=0, bool *flippedVert=0) const;
QPen mainPen() const;
};
class QCP_LIB_DECL QCPItemTracer : public QCPAbstractItem
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen)
Q_PROPERTY(QBrush brush READ brush WRITE setBrush)
Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush)
Q_PROPERTY(double size READ size WRITE setSize)
Q_PROPERTY(TracerStyle style READ style WRITE setStyle)
Q_PROPERTY(QCPGraph* graph READ graph WRITE setGraph)
Q_PROPERTY(double graphKey READ graphKey WRITE setGraphKey)
Q_PROPERTY(bool interpolating READ interpolating WRITE setInterpolating)
/// \endcond
public:
/*!
The different visual appearances a tracer item can have. Some styles size may be controlled with \ref setSize.
\see setStyle
*/
enum TracerStyle { tsNone ///< The tracer is not visible
,tsPlus ///< A plus shaped crosshair with limited size
,tsCrosshair ///< A plus shaped crosshair which spans the complete axis rect
,tsCircle ///< A circle
,tsSquare ///< A square
};
Q_ENUMS(TracerStyle)
QCPItemTracer(QCustomPlot *parentPlot);
virtual ~QCPItemTracer();
// getters:
QPen pen() const { return mPen; }
QPen selectedPen() const { return mSelectedPen; }
QBrush brush() const { return mBrush; }
QBrush selectedBrush() const { return mSelectedBrush; }
double size() const { return mSize; }
TracerStyle style() const { return mStyle; }
QCPGraph *graph() const { return mGraph; }
double graphKey() const { return mGraphKey; }
bool interpolating() const { return mInterpolating; }
// setters;
void setPen(const QPen &pen);
void setSelectedPen(const QPen &pen);
void setBrush(const QBrush &brush);
void setSelectedBrush(const QBrush &brush);
void setSize(double size);
void setStyle(TracerStyle style);
void setGraph(QCPGraph *graph);
void setGraphKey(double key);
void setInterpolating(bool enabled);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
// non-virtual methods:
void updatePosition();
QCPItemPosition * const position;
protected:
// property members:
QPen mPen, mSelectedPen;
QBrush mBrush, mSelectedBrush;
double mSize;
TracerStyle mStyle;
QCPGraph *mGraph;
double mGraphKey;
bool mInterpolating;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter);
// non-virtual methods:
QPen mainPen() const;
QBrush mainBrush() const;
};
class QCP_LIB_DECL QCPItemBracket : public QCPAbstractItem
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen)
Q_PROPERTY(double length READ length WRITE setLength)
Q_PROPERTY(BracketStyle style READ style WRITE setStyle)
/// \endcond
public:
enum BracketStyle { bsSquare ///< A brace with angled edges
,bsRound ///< A brace with round edges
,bsCurly ///< A curly brace
,bsCalligraphic ///< A curly brace with varying stroke width giving a calligraphic impression
};
QCPItemBracket(QCustomPlot *parentPlot);
virtual ~QCPItemBracket();
// getters:
QPen pen() const { return mPen; }
QPen selectedPen() const { return mSelectedPen; }
double length() const { return mLength; }
BracketStyle style() const { return mStyle; }
// setters;
void setPen(const QPen &pen);
void setSelectedPen(const QPen &pen);
void setLength(double length);
void setStyle(BracketStyle style);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const;
QCPItemPosition * const left;
QCPItemPosition * const right;
QCPItemAnchor * const center;
protected:
// property members:
enum AnchorIndex {aiCenter};
QPen mPen, mSelectedPen;
double mLength;
BracketStyle mStyle;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter);
virtual QPointF anchorPixelPoint(int anchorId) const;
// non-virtual methods:
QPen mainPen() const;
};
#endif // QCUSTOMPLOT_H
| 149,287 | C | 38.609445 | 236 | 0.737365 |
adegirmenci/HBL-ICEbot/icebot_definitions.h | #ifndef ICEBOT_DEFINITIONS
#define ICEBOT_DEFINITIONS
//*****************************************************************************//
//
// Author: Alperen Degirmenci
//
// Date: 11/29/2015
// Last Update: 09/07/2016
//
// COPYRIGHT: COPYRIGHT HARVARD BIOROBOTICS LABORATORY - 2015, 2016
//
//*****************************************************************************//
//
// DESCRIPTION: icebot_definitions.h
//
// Header file containing definitions of constants and structures required.
//
//*****************************************************************************//
#include "../AscensionWidget/3DGAPI/ATC3DG.h"
// Alternative to using Boost for value of Pi
//const long double PI = 3.141592653589793238L;
//const double PI = 3.141592653589793;
//const float PI = 3.1415927;
enum LOG_TYPES
{
LOG_INFO = 0, // regular messages
LOG_WARNING, // warnings
LOG_ERROR, // errors
LOG_FATAL // fatal errors
};
enum LOG_SOURCE
{
SRC_EM = 0,
SRC_EPOS,
SRC_FRMGRAB,
SRC_EPIPHAN,
SRC_LABJACK,
SRC_OMNI,
SRC_DATALOGGER,
SRC_CONTROLLER,
SRC_GUI,
SRC_UNKNOWN
};
// **********************
// ******** EM ********
// **********************
enum EM_ERROR_CODES
{
EM_SUCCESS = 0, //
EM_FAIL,
EM_BELOW_MIN_SAMPLE_RATE,
EM_ABOVE_MAX_SAMPLE_RATE,
EM_CANT_MUTATE_WHILE_RUNNING,
EM_FREQ_SET_FAILURE,
EM_SET_DATA_FORMAT_TYPE_FAILURE
};
enum EM_EVENT_IDS
{
EM_INITIALIZE_BEGIN = 0,
EM_INITIALIZE_FAILED,
EM_INITIALIZED,
EM_SENSORS_DETECTED,
EM_TRANSMITTER_SET,
EM_FREQ_DETECTED,
EM_FREQ_SET,
EM_FREQ_SET_FAILED,
EM_ACQUISITION_STARTED,
EM_START_ACQUISITION_FAILED,
EM_ACQUIRE_FAILED,
EM_ACQUISITION_STOPPED,
EM_STOP_ACQUISITION_FAILED,
EM_DISCONNECT_FAILED,
EM_DISCONNECTED,
EM_EPOCH_SET,
EM_EPOCH_SET_FAILED,
EM_SET_DATA_FORMAT_TYPE,
EM_SET_DATA_FORMAT_TYPE_FAILED
};
enum EM_SENSOR_IDS
{
EM_SENSOR_BB = 0,
EM_SENSOR_BT,
EM_SENSOR_INST,
EM_SENSOR_CHEST
};
static const char* const EM_SENSOR_NAMES[] = {"BB", "BT", "INST", "CHEST"};
static const int EM_DEFAULT_SAMPLE_RATE = 150;
static const int EM_MIN_SAMPLE_RATE = 20;
static const int EM_MAX_SAMPLE_RATE = 250;
#define EM_DELTA_T_SIZE 151
//typedef DOUBLE_POSITION_QUATERNION_TIME_Q_RECORD EM_RECORD_TYPE;
// typedef DOUBLE_POSITION_MATRIX_TIME_Q_RECORD EM_RECORD_TYPE;
// Preferred EM reading type is : DOUBLE_POSITION_QUATERNION_TIME_Q_RECORD
// **********************
// ******** EPOS ********
// **********************
enum EPOS_ERROR_CODES
{
EPOS_SUCCESS = 0,
EPOS_FAIL,
EPOS_FAILED_TO_CONNECT
};
enum EPOS_EVENT_IDS
{
EPOS_INITIALIZE_BEGIN = 0,
EPOS_INITIALIZE_FAILED,
EPOS_INITIALIZED,
EPOS_SERVO_LOOP_STARTED,
EPOS_SERVO_LOOP_STOPPED,
EPOS_SERVO_TO_POS_FAILED,
EPOS_EPOCH_SET,
EPOS_EPOCH_SET_FAILED,
EPOS_DISABLE_MOTOR_FAILED,
EPOS_DISABLE_MOTOR_SUCCESS,
EPOS_DEVICE_CANT_CONNECT,
EPOS_UPDATE_QC_FAILED,
EPOS_HALT_FAILED,
EPOS_DISCONNECTED,
EPOS_DISCONNECT_FAILED
};
enum EPOS_DATA_IDS
{
EPOS_COMMANDED = 0,
EPOS_READ
};
enum EPOS_MOTOR_STATUS
{
EPOS_MOTOR_DISABLED = 0,
EPOS_MOTOR_ENABLED,
EPOS_MOTOR_FAULT,
EPOS_MOTOR_CANT_CONNECT,
EPOS_INVALID_MOTOR_ID
};
// enum EPOS_MOTOR_IDS
// {
// TRANS_MOTOR_ID = 1,
// PITCH_MOTOR_ID,
// YAW_MOTOR_ID,
// ROLL_MOTOR_ID
// };
static const int EPOS_NUM_MOTORS = 4;
static const int TRANS_MOTOR_ID = 1;
static const int PITCH_MOTOR_ID = 2;
static const int YAW_MOTOR_ID = 3;
static const int ROLL_MOTOR_ID = 4;
static const int EPOS_MOTOR_IDS[EPOS_NUM_MOTORS] = {TRANS_MOTOR_ID, PITCH_MOTOR_ID, YAW_MOTOR_ID, ROLL_MOTOR_ID};
static const int TRANS_AXIS_ID = 0;
static const int PITCH_AXIS_ID = 1;
static const int YAW_AXIS_ID = 2;
static const int ROLL_AXIS_ID = 3;
static const int EPOS_AXIS_IDS[EPOS_NUM_MOTORS] = {TRANS_AXIS_ID, PITCH_AXIS_ID, YAW_AXIS_ID, ROLL_AXIS_ID};
// original values from Alienware
//static const int EPOS_VELOCITY[EPOS_NUM_MOTORS] = {5000, 5000, 5000, 5000};
//static const int EPOS_ACCEL[EPOS_NUM_MOTORS] = {20000, 50000, 50000, 50000};
//static const int EPOS_DECEL[EPOS_NUM_MOTORS] = {20000, 30000, 30000, 30000};
// better values
static const int EPOS_VELOCITY[EPOS_NUM_MOTORS] = {5000, 10000, 10000, 10000};
static const int EPOS_ACCEL[EPOS_NUM_MOTORS] = {50000, 80000, 80000, 80000};
static const int EPOS_DECEL[EPOS_NUM_MOTORS] = {50000, 70000, 70000, 70000};
// values for mapping
//static const int EPOS_VELOCITY[EPOS_NUM_MOTORS] = {5000, 5000, 5000, 5000};
//static const int EPOS_ACCEL[EPOS_NUM_MOTORS] = {50000, 30000, 30000, 30000};
//static const int EPOS_DECEL[EPOS_NUM_MOTORS] = {50000, 20000, 20000, 20000};
static const long EPOS_TRANS_MIN = -320000;
static const long EPOS_TRANS_MAX = 320000;
static const long EPOS_PITCH_MIN = -45000;
static const long EPOS_PITCH_MAX = 45000;
static const long EPOS_YAW_MIN = -45000;
static const long EPOS_YAW_MAX = 45000;
static const long EPOS_ROLL_MIN = -1381000;
static const long EPOS_ROLL_MAX = 1381000;
static const int EPOS_MOTOR_LIMITS[EPOS_NUM_MOTORS][2] =
{ {EPOS_TRANS_MIN, EPOS_TRANS_MAX},
{EPOS_PITCH_MIN, EPOS_PITCH_MAX},
{EPOS_YAW_MIN, EPOS_YAW_MAX},
{EPOS_ROLL_MIN, EPOS_ROLL_MAX} };
static const long EPOS_TRANS_RAD2QC = -8503937;
static const long EPOS_PITCH_RAD2QC = 45837;
static const long EPOS_YAW_RAD2QC = -45837;
static const long EPOS_ROLL_RAD2QC = -45837;
// ***********************
// ****** LabJack ******
// ***********************
// enum LABJACK_ERROR_CODES ---- use LJ_ERROR codes instead from LabJackUD.h
enum LABJACK_EVENT_IDS
{
LABJACK_CONNECT_BEGIN = 0,
LABJACK_CONNECT_FAILED,
LABJACK_CONNECTED,
LABJACK_INITIALIZE_BEGIN,
LABJACK_INITIALIZE_FAILED,
LABJACK_INITIALIZED,
LABJACK_LOOP_STARTED,
LABJACK_LOOP_STOPPED,
LABJACK_EPOCH_SET,
LABJACK_EPOCH_SET_FAILED,
LABJACK_DISCONNECTED,
LABJACK_DISCONNECT_FAILED
};
// ***********************
// ****** FrmGrab ******
// ***********************
enum FRMGRAB_ERROR_CODES
{
FRMGRAB_SUCCESS = 0, //
FRMGRAB_FAIL,
FRMGRAB_CANT_MUTATE_WHILE_RUNNING
};
enum FRMGRAB_EVENT_IDS
{
FRMGRAB_CONNECT_BEGIN = 0,
FRMGRAB_CONNECT_FAILED,
FRMGRAB_CONNECTED,
FRMGRAB_INITIALIZE_BEGIN,
FRMGRAB_INITIALIZE_FAILED,
FRMGRAB_INITIALIZED,
FRMGRAB_LOOP_STARTED,
FRMGRAB_LOOP_STOPPED,
FRMGRAB_LIVE_FEED_STARTED,
FRMGRAB_LIVE_FEED_STOPPED,
FRMGRAB_EPOCH_SET,
FRMGRAB_EPOCH_SET_FAILED,
FRMGRAB_DISCONNECTED,
FRMGRAB_DISCONNECT_FAILED
};
static const int FRMGRAB_IM_WIDTH = 1920; // 640;
static const int FRMGRAB_IM_HEIGHT = 1080; // 480;
static const int FRMGRAB_FPS = 60;
// **************************
// ****** CONTROLLER ******
// **************************
#define PERIOD_FILTER_SIZE 150
static const double PITCH_WP = 7.3896;
static const double PITCH_WY = 1.2693;
static const double PITCH_BIAS = 0.2529;
static const double PITCH_SUM = 8.9118;
static const double YAW_WY = 5.9987;
static const double YAW_WP = 0.3187;
static const double YAW_BIAS = -0.1743;
static const double YAW_SUM = 6.1431;
enum CONTROLLER_ERROR_CODES
{
CONTROLLER_SUCCESS = 0, //
CONTROLLER_FAIL,
CONTROLLER_CANT_MUTATE_WHILE_RUNNING
};
enum CONTROLLER_EVENT_IDS
{
CONTROLLER_INITIALIZE_BEGIN = 0,
CONTROLLER_INITIALIZE_FAILED,
CONTROLLER_INITIALIZED,
CONTROLLER_LOOP_STARTED,
CONTROLLER_LOOP_STOPPED,
CONTROLLER_RESP_MODEL_INIT_BEGIN,
CONTROLLER_RESP_MODEL_INITIALIZED,
CONTROLLER_RESP_MODEL_INIT_FAILED,
CONTROLLER_RESP_MODEL_STOPPED,
CONTROLLER_RESETBB_SUCCESS,
CONTROLLER_EPOCH_SET,
CONTROLLER_EPOCH_SET_FAILED,
CONTROLLER_RESET,
CONTROLLER_RESET_FAILED,
CONTROLLER_SWEEP_STARTED,
CONTROLLER_SWEEP_ABORTED
};
enum CONTROLLER_DATA_IDS
{
CONTROLLER_DXYZPSI = 0, // 4 values
CONTROLLER_USER_XYZDXYZPSI, // 7 values
CONTROLLER_CURR_PSY_GAMMA, // 2 values
CONTROLLER_T_BB_CT_curTipPos, // 16 values
CONTROLLER_CURR_TASK, // 4 values
CONTROLLER_PERIOD, // 1 value
CONTROLLER_BIRD4_MODEL_PARAMS, // 19 = 10 polar + 9 rect
CONTROLLER_RESETBB, // 16 values
CONTROLLER_MODES, // 6 values
CONTROLLER_USANGLE, // 1 value
CONTROLLER_SWEEP_START, // 4 values
CONTROLLER_NEXT_SWEEP,
CONTROLLER_SWEEP_CONVERGED
};
enum CONTROLLER_SPACES
{
JOINT_SPACE = 0,
CONFIG_SPACE,
TASK_SPACE
};
enum CONTROLLER_SPACE_VARIABLES
{
JOINT_SPACE_TRANS = 0,
JOINT_SPACE_PITCH,
JOINT_SPACE_YAW,
JOINT_SPACE_ROLL,
CONFIG_SPACE_ALPHA,
CONFIG_SPACE_THETA,
CONFIG_SPACE_GAMMA,
CONFIG_SPACE_D,
TASK_SPACE_X,
TASK_SPACE_Y,
TASK_SPACE_Z,
TASK_SPACE_DEL_PSI
};
// Mode flags
enum COORD_FRAME_MODE
{
COORD_FRAME_WORLD = 0,
COORD_FRAME_MOBILE
};
enum TETHER_MODE
{
MODE_TETHETERED = 0,
MODE_RELATIVE
};
enum INST_TRACK_STATE
{
INST_TRACK_OFF = 0,
INST_TRACK_ON
};
enum INST_TRACK_MODE
{
INST_TRACK_POSITION = 0,
INST_TRACK_IMAGER
};
enum EKF_STATE
{
EKF_OFF = 0,
EKF_ON
};
enum IN_VIVO_MODE
{
IN_VIVO_OFF = 0,
IN_VIVO_ON
};
enum MODEL_PLOT_INDEX
{
RESP_MODEL_PLOT_BIRD4 = 0,
RESP_MODEL_PLOT_CT
};
enum SWEEP_MODES
{
SWEEP_INACTIVE = 0,
SWEEP_WAIT_TO_CONVERGE,
SWEEP_CONVERGED,
SWEEP_CONVERGED_ACQUIRING,
SWEEP_NEXT,
SWEEP_DONE
};
static const int CONTROLLER_LOOP_TIMER_MSEC = 1;
// *************************
// ****** FILTERING ******
// *************************
#define FILTER_ORDER 50 // LPF filter order
#define SAMPLE_DELTA_TIME 0.005992 //0.006667 // delta time b/w EM readings
#define HEART_RATE 100 // animal heartrate
#define N_HARMONICS 4 // number of Fourier decomp harmonics
#define N_STATES N_HARMONICS*2 + 2 // number of states
#define N_RECT N_STATES - 1 // NUM_STATES of Rectangular components
#define N_POLAR N_STATES // NUM_STATES of Polar components
#define N_SAMPLES 2750 // CYCLE_DATA_SIZE
#define EDGE_EFFECT 35 // extent of edge effects
#define N_FILTERED N_SAMPLES - 2*EDGE_EFFECT // Filtered data length
#define BREATH_RATE 5.0 // respiration period (seconds)
#define PEAK_THRESHOLD 0.80 // For peak detection
// ***********************
// ***** DATA LOGGER *****
// ***********************
static const int DATALOG_NUM_FILES = 8;
static const unsigned short DATALOG_EM_ID = 0;
static const unsigned short DATALOG_ECG_ID = 1;
static const unsigned short DATALOG_EPOS_ID = 2;
static const unsigned short DATALOG_FrmGrab_ID = 3;
static const unsigned short DATALOG_Log_ID = 4;
static const unsigned short DATALOG_Error_ID = 5;
static const unsigned short DATALOG_Note_ID = 6;
static const unsigned short DATALOG_Control_ID = 7;
static const unsigned short DATALOG_FILE_IDS[DATALOG_NUM_FILES] =
{DATALOG_EM_ID,
DATALOG_ECG_ID,
DATALOG_EPOS_ID,
DATALOG_FrmGrab_ID,
DATALOG_Log_ID,
DATALOG_Error_ID,
DATALOG_Note_ID,
DATALOG_Control_ID};
enum DATALOG_EVENT_IDS
{
DATALOG_INITIALIZE_BEGIN = 0,
DATALOG_INITIALIZE_FAILED,
DATALOG_INITIALIZED,
DATALOG_FILE_OPENED,
DATALOG_FILE_CLOSED,
DATALOG_FOLDER_ERROR,
DATALOG_FILE_ERROR,
DATALOG_FILE_DATA_LOGGED,
DATALOG_EM_FILE_OPENED,
DATALOG_EM_FILE_CLOSED,
DATALOG_EM_FILE_DATA_LOGGED,
DATALOG_ECG_FILE_OPENED,
DATALOG_ECG_FILE_CLOSED,
DATALOG_ECG_FILE_DATA_LOGGED,
DATALOG_EPOS_FILE_OPENED,
DATALOG_EPOS_FILE_CLOSED,
DATALOG_EPOS_FILE_DATA_LOGGED,
DATALOG_FRMGRAB_FILE_OPENED,
DATALOG_FRMGRAB_FILE_CLOSED,
DATALOG_FRMGRAB_FILE_DATA_LOGGED,
DATALOG_LOG_FILE_OPENED,
DATALOG_LOG_FILE_CLOSED,
DATALOG_LOG_FILE_DATA_LOGGED,
DATALOG_ERROR_FILE_OPENED,
DATALOG_ERROR_FILE_CLOSED,
DATALOG_ERROR_FILE_DATA_LOGGED,
DATALOG_NOTE_FILE_OPENED,
DATALOG_NOTE_FILE_CLOSED,
DATALOG_NOTE_FILE_DATA_LOGGED,
DATALOG_CONTROL_FILE_OPENED,
DATALOG_CONTROL_FILE_CLOSED,
DATALOG_CONTROL_FILE_DATA_LOGGED,
DATALOG_EPOCH_SET,
DATALOG_EPOCH_SET_FAILED,
DATALOG_LOGGING_STARTED,
DATALOG_LOGGING_STOPPED,
DATALOG_CLOSED
};
// ************************
// ***** FRAME SERVER *****
// ************************
enum FRMSRVR_EVENT_IDS
{
FRMSRVR_STARTED = 0,
FRMSRVR_START_FAILED,
FRMSRVR_CLOSED,
FRMSRVR_CLOSE_FAILED,
FRMSRVR_NEW_CONNECTION,
FRMSRVR_SOCKET_NOT_READABLE,
FRMSRVR_FRAME_RECEIVED,
FRMSRVR_EPOCH_SET,
FRMSRVR_EPOCH_SET_FAILED
};
// ************************
// ***** FRAME CLIENT *****
// ************************
enum FRMCLNT_EVENT_IDS
{
FRMCLNT_CONNECTED = 0,
FRMCLNT_CONNECTION_FAILED,
FRMCLNT_DISCONNECTED,
FRMCLNT_DISCONNECTION_FAILED,
FRMCLNT_SOCKET_NOT_WRITABLE,
FRMCLNT_FRAME_SENT,
FRMCLNT_EPOCH_SET,
FRMCLNT_EPOCH_SET_FAILED,
FRMCLNT_FIRST_FRAME_NOT_RECEIVED
};
// *************************
// ***** VOLUME SERVER *****
// *************************
enum VOLSRVR_EVENT_IDS
{
VOLSRVR_STARTED = 0,
VOLSRVR_START_FAILED,
VOLSRVR_CLOSED,
VOLSRVR_CLOSE_FAILED,
VOLSRVR_NEW_CONNECTION,
VOLSRVR_SOCKET_NOT_READABLE,
VOLSRVR_VOLUME_RECEIVED,
VOLSRVR_EPOCH_SET,
VOLSRVR_EPOCH_SET_FAILED
};
// *************************
// ***** VOLUME CLIENT *****
// *************************
enum VOLCLNT_EVENT_IDS
{
VOLCLNT_CONNECTED = 0,
VOLCLNT_CONNECTION_FAILED,
VOLCLNT_DISCONNECTED,
VOLCLNT_DISCONNECTION_FAILED,
VOLCLNT_SOCKET_NOT_WRITABLE,
VOLCLNT_VOLUME_SENT,
VOLCLNT_EPOCH_SET,
VOLCLNT_EPOCH_SET_FAILED,
VOLCLNT_NOT_READY
};
#endif // ICEBOT_DEFINITIONS
// NEVER PASS EIGEN TYPES BY VALUE TO FUNCTIONS, ALWAYS PASS BY REFERENCE - BUT IT'S OK IF FUNCTIONS RETURN EIGEN TYPES BY VALUE
// IF USING VECTOR/LIST/DEQUE/ETC TO STORE EIGEN FIXED TYPES (LIKE TRANSFORM), USE THE EIGEN::ALIGNED_ALLOCATOR IN DECLARING THE CONTAINER TYPE
| 14,708 | C | 25.266071 | 143 | 0.610076 |
adegirmenci/HBL-ICEbot/icebot_gui.cpp | #include "icebot_gui.h"
#include "ui_icebot_gui.h"
ICEbot_GUI::ICEbot_GUI(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::ICEbot_GUI)
{
ui->setupUi(this);
qDebug() << "Setting up GUI connections.";
// EM Data to DataLogger
connect(ui->emWidget->m_worker, SIGNAL(logData(QTime,int,DOUBLE_POSITION_MATRIX_TIME_Q_RECORD)),
ui->dataLogWidget->m_worker, SLOT(logEMdata(QTime,int,DOUBLE_POSITION_MATRIX_TIME_Q_RECORD)));
// LabJack Data to DataLogger
connect(ui->labjackWidget->m_worker, SIGNAL(logData(qint64,std::vector<double>)),
ui->dataLogWidget->m_worker, SLOT(logLabJackData(qint64,std::vector<double>)));
// FrameGrabber Data to DataLogger
connect(ui->frmGrabWidget->m_worker, SIGNAL(pleaseSaveImage(std::shared_ptr<Frame>)),
ui->dataLogWidget->m_worker, SLOT(logFrmGrabImage(std::shared_ptr<Frame>)));
// EPOS Data to DataLogger
connect(ui->eposWidget->m_worker, SIGNAL(logData(QTime,int,int,long)),
ui->dataLogWidget->m_worker, SLOT(logEPOSdata(QTime,int,int,long)));
connect(ui->eposWidget->m_worker, SIGNAL(logData(QTime,int,std::vector<long>)),
ui->dataLogWidget->m_worker, SLOT(logEPOSdata(QTime,int,std::vector<long>)));
// Controller to DataLogger
connect(ui->controlWidget->m_worker, SIGNAL(logData(QTime,int,int,std::vector<double>)),
ui->dataLogWidget->m_worker, SLOT(logControllerData(QTime,int,int,std::vector<double>)));
// Events to DataLogger
connect(ui->emWidget->m_worker, SIGNAL(logEvent(int,int,QTime,int)),
ui->dataLogWidget->m_worker, SLOT(logEvent(int,int,QTime,int)));
connect(ui->eposWidget->m_worker, SIGNAL(logEvent(int,int,QTime,int)),
ui->dataLogWidget->m_worker, SLOT(logEvent(int,int,QTime,int)));
connect(ui->frmGrabWidget->m_worker, SIGNAL(logEvent(int,int,QTime,int)),
ui->dataLogWidget->m_worker, SLOT(logEvent(int,int,QTime,int)));
connect(ui->labjackWidget->m_worker, SIGNAL(logEvent(int,int,QTime,int)),
ui->dataLogWidget->m_worker, SLOT(logEvent(int,int,QTime,int)));
connect(ui->controlWidget->m_worker, SIGNAL(logEvent(int,int,QTime,int)),
ui->dataLogWidget->m_worker, SLOT(logEvent(int,int,QTime,int)));
// Errors to DataLogger
connect(ui->emWidget->m_worker, SIGNAL(logError(int,int,QTime,int,QString)),
ui->dataLogWidget->m_worker, SLOT(logError(int,int,QTime,int,QString)));
connect(ui->eposWidget->m_worker, SIGNAL(logError(int,int,QTime,int,QString)),
ui->dataLogWidget->m_worker, SLOT(logError(int,int,QTime,int,QString)));
connect(ui->frmGrabWidget->m_worker, SIGNAL(logError(int,int,QTime,int,QString)),
ui->dataLogWidget->m_worker, SLOT(logError(int,int,QTime,int,QString)));
connect(ui->labjackWidget->m_worker, SIGNAL(logError(int,int,QTime,int,QString)),
ui->dataLogWidget->m_worker, SLOT(logError(int,int,QTime,int,QString)));
connect(ui->controlWidget->m_worker, SIGNAL(logError(int,int,QTime,int,QString)),
ui->dataLogWidget->m_worker, SLOT(logError(int,int,QTime,int,QString)));
// EM to SceneVizWidget
// connect(ui->emWidget->m_worker, SIGNAL(logData(QTime,int,DOUBLE_POSITION_MATRIX_TIME_Q_RECORD)),
// ui->sceneVizWidget->m_modifier, SLOT(receiveEMreading(QTime,int,DOUBLE_POSITION_MATRIX_TIME_Q_RECORD)));
connect(ui->emWidget->m_worker, SIGNAL(sendLatestReading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD>)),
ui->sceneVizWidget->m_modifier, SLOT(receiveEMreading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD>)));
// EM to Controller
//connect(ui->emWidget->m_worker, SIGNAL(logData(QTime,int,DOUBLE_POSITION_QUATERNION_TIME_Q_RECORD)),
// ui->controlWidget->m_worker, SLOT(receiveEMdata(QTime,int,DOUBLE_POSITION_QUATERNION_TIME_Q_RECORD)));
connect(ui->emWidget->m_worker, SIGNAL(sendLatestReading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD>)),
ui->controlWidget->m_worker, SLOT(receiveLatestEMreading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD>)));
// inter-process communication
connect(ui->frmGrabWidget->m_worker, SIGNAL(imageAcquired(std::shared_ptr<Frame>)),
ui->frameClientWidget->m_worker, SLOT(receiveFrame(std::shared_ptr<Frame>)));
// connect(ui->emWidget->m_worker, SIGNAL(logData(QTime,int,DOUBLE_POSITION_MATRIX_TIME_Q_RECORD)),
// ui->frameClientWidget->m_worker, SLOT(receiveEMreading(QTime,int,DOUBLE_POSITION_MATRIX_TIME_Q_RECORD)));
// connect(ui->emWidget->m_worker, SIGNAL(sendLatestReading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD>)),
// ui->frameClientWidget->m_worker, SLOT(receiveLatestEMreading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD>)));
connect(ui->controlWidget->m_worker, SIGNAL(send_CT_toFrameClient(std::vector<double>,double)),
ui->frameClientWidget->m_worker, SLOT(receive_T_CT(std::vector<double>,double)));
connect(ui->controlWidget->m_worker, SIGNAL(toggleFrameClientContinuousStreaming(bool)),
ui->frameClientWidget->m_worker, SLOT(toggleContinuousSteaming(bool)));
connect(ui->labjackWidget->m_hrWidget, SIGNAL(reportPhase(qint64,double)),
ui->frameClientWidget->m_worker, SLOT(receivePhase(qint64,double)));
// Controller to EPOS
connect(ui->controlWidget->m_worker, SIGNAL(setEPOSservoTargetPos(std::vector<long>,bool)),
ui->eposWidget->m_worker, SLOT(setServoTargetPos(std::vector<long>,bool)));
// Controller to frame grabber
// FIXME: don't forget to uncomment this
connect(ui->controlWidget, SIGNAL(startControlCycle()), ui->frmGrabWidget, SLOT(controlStarted()));
connect(ui->controlWidget, SIGNAL(stopControlCycle()), ui->frmGrabWidget, SLOT(controlStopped()));
// get current date time
m_epoch = QDateTime::currentDateTime();
qDebug() << "Setting epoch.";
// set date time of widgets
ui->emWidget->m_worker->setEpoch(m_epoch);
ui->frmGrabWidget->m_worker->setEpoch(m_epoch);
ui->eposWidget->m_worker->setEpoch(m_epoch);
ui->labjackWidget->m_worker->setEpoch(m_epoch);
ui->frameClientWidget->m_worker->setEpoch(m_epoch);
qDebug() << "GUI ready.";
}
ICEbot_GUI::~ICEbot_GUI()
{
delete ui;
}
void ICEbot_GUI::closeEvent(QCloseEvent *event)
{
event->accept();
qApp->quit();
}
| 6,405 | C++ | 52.383333 | 128 | 0.693365 |
adegirmenci/HBL-ICEbot/icebot_gui.h | #ifndef ICEBOT_GUI_H
#define ICEBOT_GUI_H
#include <QMainWindow>
#include <QDebug>
#include <QCloseEvent>
#include <QDateTime>
namespace Ui {
class ICEbot_GUI;
}
class ICEbot_GUI : public QMainWindow
{
Q_OBJECT
public:
explicit ICEbot_GUI(QWidget *parent = 0);
~ICEbot_GUI();
private slots:
private:
Ui::ICEbot_GUI *ui;
void closeEvent(QCloseEvent *event);
QDateTime m_epoch;
};
#endif // ICEBOT_GUI_H
| 437 | C | 11.882353 | 45 | 0.681922 |
adegirmenci/HBL-ICEbot/qcustomplot.cpp | /***************************************************************************
** **
** QCustomPlot, an easy to use, modern plotting widget for Qt **
** Copyright (C) 2011-2015 Emanuel Eichhammer **
** **
** This program is free software: you can redistribute it and/or modify **
** it under the terms of the GNU General Public License as published by **
** the Free Software Foundation, either version 3 of the License, or **
** (at your option) any later version. **
** **
** This program is distributed in the hope that it will be useful, **
** but WITHOUT ANY WARRANTY; without even the implied warranty of **
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the **
** GNU General Public License for more details. **
** **
** You should have received a copy of the GNU General Public License **
** along with this program. If not, see http://www.gnu.org/licenses/. **
** **
****************************************************************************
** Author: Emanuel Eichhammer **
** Website/Contact: http://www.qcustomplot.com/ **
** Date: 22.12.15 **
** Version: 1.3.2 **
****************************************************************************/
#include "qcustomplot.h"
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPPainter
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPPainter
\brief QPainter subclass used internally
This QPainter subclass is used to provide some extended functionality e.g. for tweaking position
consistency between antialiased and non-antialiased painting. Further it provides workarounds
for QPainter quirks.
\warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and
restore. So while it is possible to pass a QCPPainter instance to a function that expects a
QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because
it will call the base class implementations of the functions actually hidden by QCPPainter).
*/
/*!
Creates a new QCPPainter instance and sets default values
*/
QCPPainter::QCPPainter() :
QPainter(),
mModes(pmDefault),
mIsAntialiasing(false)
{
// don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and
// a call to begin() will follow
}
/*!
Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just
like the analogous QPainter constructor, begins painting on \a device immediately.
Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5.
*/
QCPPainter::QCPPainter(QPaintDevice *device) :
QPainter(device),
mModes(pmDefault),
mIsAntialiasing(false)
{
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions.
if (isActive())
setRenderHint(QPainter::NonCosmeticDefaultPen);
#endif
}
QCPPainter::~QCPPainter()
{
}
/*!
Sets the pen of the painter and applies certain fixes to it, depending on the mode of this
QCPPainter.
\note this function hides the non-virtual base class implementation.
*/
void QCPPainter::setPen(const QPen &pen)
{
QPainter::setPen(pen);
if (mModes.testFlag(pmNonCosmetic))
makeNonCosmetic();
}
/*! \overload
Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of
this QCPPainter.
\note this function hides the non-virtual base class implementation.
*/
void QCPPainter::setPen(const QColor &color)
{
QPainter::setPen(color);
if (mModes.testFlag(pmNonCosmetic))
makeNonCosmetic();
}
/*! \overload
Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of
this QCPPainter.
\note this function hides the non-virtual base class implementation.
*/
void QCPPainter::setPen(Qt::PenStyle penStyle)
{
QPainter::setPen(penStyle);
if (mModes.testFlag(pmNonCosmetic))
makeNonCosmetic();
}
/*! \overload
Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when
antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to
integer coordinates and then passes it to the original drawLine.
\note this function hides the non-virtual base class implementation.
*/
void QCPPainter::drawLine(const QLineF &line)
{
if (mIsAntialiasing || mModes.testFlag(pmVectorized))
QPainter::drawLine(line);
else
QPainter::drawLine(line.toLine());
}
/*!
Sets whether painting uses antialiasing or not. Use this method instead of using setRenderHint
with QPainter::Antialiasing directly, as it allows QCPPainter to regain pixel exactness between
antialiased and non-antialiased painting (Since Qt < 5.0 uses slightly different coordinate systems for
AA/Non-AA painting).
*/
void QCPPainter::setAntialiasing(bool enabled)
{
setRenderHint(QPainter::Antialiasing, enabled);
if (mIsAntialiasing != enabled)
{
mIsAntialiasing = enabled;
if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs
{
if (mIsAntialiasing)
translate(0.5, 0.5);
else
translate(-0.5, -0.5);
}
}
}
/*!
Sets the mode of the painter. This controls whether the painter shall adjust its
fixes/workarounds optimized for certain output devices.
*/
void QCPPainter::setModes(QCPPainter::PainterModes modes)
{
mModes = modes;
}
/*!
Sets the QPainter::NonCosmeticDefaultPen in Qt versions before Qt5 after beginning painting on \a
device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5,
all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that
behaviour.
The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets
the render hint as appropriate.
\note this function hides the non-virtual base class implementation.
*/
bool QCPPainter::begin(QPaintDevice *device)
{
bool result = QPainter::begin(device);
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions.
if (result)
setRenderHint(QPainter::NonCosmeticDefaultPen);
#endif
return result;
}
/*! \overload
Sets the mode of the painter. This controls whether the painter shall adjust its
fixes/workarounds optimized for certain output devices.
*/
void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled)
{
if (!enabled && mModes.testFlag(mode))
mModes &= ~mode;
else if (enabled && !mModes.testFlag(mode))
mModes |= mode;
}
/*!
Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to
QPainter, the save/restore functions are reimplemented to also save/restore those members.
\note this function hides the non-virtual base class implementation.
\see restore
*/
void QCPPainter::save()
{
mAntialiasingStack.push(mIsAntialiasing);
QPainter::save();
}
/*!
Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to
QPainter, the save/restore functions are reimplemented to also save/restore those members.
\note this function hides the non-virtual base class implementation.
\see save
*/
void QCPPainter::restore()
{
if (!mAntialiasingStack.isEmpty())
mIsAntialiasing = mAntialiasingStack.pop();
else
qDebug() << Q_FUNC_INFO << "Unbalanced save/restore";
QPainter::restore();
}
/*!
Changes the pen width to 1 if it currently is 0. This function is called in the \ref setPen
overrides when the \ref pmNonCosmetic mode is set.
*/
void QCPPainter::makeNonCosmetic()
{
if (qFuzzyIsNull(pen().widthF()))
{
QPen p = pen();
p.setWidth(1);
QPainter::setPen(p);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPScatterStyle
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPScatterStyle
\brief Represents the visual appearance of scatter points
This class holds information about shape, color and size of scatter points. In plottables like
QCPGraph it is used to store how scatter points shall be drawn. For example, \ref
QCPGraph::setScatterStyle takes a QCPScatterStyle instance.
A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a
fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can
be controlled with \ref setSize.
\section QCPScatterStyle-defining Specifying a scatter style
You can set all these configurations either by calling the respective functions on an instance:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-1
Or you can use one of the various constructors that take different parameter combinations, making
it easy to specify a scatter style in a single call, like so:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-2
\section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable
There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref
QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref
isPenDefined will return false. It leads to scatter points that inherit the pen from the
plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line
color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes
it very convenient to set up typical scatter settings:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-shortcreation
Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works
because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly
into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size)
constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref
ScatterShape, where actually a QCPScatterStyle is expected.
\section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps
QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points.
For custom shapes, you can provide a QPainterPath with the desired shape to the \ref
setCustomPath function or call the constructor that takes a painter path. The scatter shape will
automatically be set to \ref ssCustom.
For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the
constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap.
Note that \ref setSize does not influence the appearance of the pixmap.
*/
/* start documentation of inline functions */
/*! \fn bool QCPScatterStyle::isNone() const
Returns whether the scatter shape is \ref ssNone.
\see setShape
*/
/*! \fn bool QCPScatterStyle::isPenDefined() const
Returns whether a pen has been defined for this scatter style.
The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those are
\ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen is
left undefined, the scatter color will be inherited from the plottable that uses this scatter
style.
\see setPen
*/
/* end documentation of inline functions */
/*!
Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined.
Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
from the plottable that uses this scatter style.
*/
QCPScatterStyle::QCPScatterStyle() :
mSize(6),
mShape(ssNone),
mPen(Qt::NoPen),
mBrush(Qt::NoBrush),
mPenDefined(false)
{
}
/*!
Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or
brush is defined.
Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
from the plottable that uses this scatter style.
*/
QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) :
mSize(size),
mShape(shape),
mPen(Qt::NoPen),
mBrush(Qt::NoBrush),
mPenDefined(false)
{
}
/*!
Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
and size to \a size. No brush is defined, i.e. the scatter point will not be filled.
*/
QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) :
mSize(size),
mShape(shape),
mPen(QPen(color)),
mBrush(Qt::NoBrush),
mPenDefined(true)
{
}
/*!
Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
the brush color to \a fill (with a solid pattern), and size to \a size.
*/
QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) :
mSize(size),
mShape(shape),
mPen(QPen(color)),
mBrush(QBrush(fill)),
mPenDefined(true)
{
}
/*!
Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the
brush to \a brush, and size to \a size.
\warning In some cases it might be tempting to directly use a pen style like <tt>Qt::NoPen</tt> as \a pen
and a color like <tt>Qt::blue</tt> as \a brush. Notice however, that the corresponding call\n
<tt>QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)</tt>\n
doesn't necessarily lead C++ to use this constructor in some cases, but might mistake
<tt>Qt::NoPen</tt> for a QColor and use the
\ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size)
constructor instead (which will lead to an unexpected look of the scatter points). To prevent
this, be more explicit with the parameter types. For example, use <tt>QBrush(Qt::blue)</tt>
instead of just <tt>Qt::blue</tt>, to clearly point out to the compiler that this constructor is
wanted.
*/
QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) :
mSize(size),
mShape(shape),
mPen(pen),
mBrush(brush),
mPenDefined(pen.style() != Qt::NoPen)
{
}
/*!
Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape
is set to \ref ssPixmap.
*/
QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) :
mSize(5),
mShape(ssPixmap),
mPen(Qt::NoPen),
mBrush(Qt::NoBrush),
mPixmap(pixmap),
mPenDefined(false)
{
}
/*!
Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The
scatter shape is set to \ref ssCustom.
The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly
different meaning than for built-in scatter points: The custom path will be drawn scaled by a
factor of \a size/6.0. Since the default \a size is 6, the custom path will appear at a its
natural size by default. To double the size of the path for example, set \a size to 12.
*/
QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) :
mSize(size),
mShape(ssCustom),
mPen(pen),
mBrush(brush),
mCustomPath(customPath),
mPenDefined(pen.style() != Qt::NoPen)
{
}
/*!
Sets the size (pixel diameter) of the drawn scatter points to \a size.
\see setShape
*/
void QCPScatterStyle::setSize(double size)
{
mSize = size;
}
/*!
Sets the shape to \a shape.
Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref
ssPixmap and \ref ssCustom, respectively.
\see setSize
*/
void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape)
{
mShape = shape;
}
/*!
Sets the pen that will be used to draw scatter points to \a pen.
If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after
a call to this function, even if \a pen is <tt>Qt::NoPen</tt>.
\see setBrush
*/
void QCPScatterStyle::setPen(const QPen &pen)
{
mPenDefined = true;
mPen = pen;
}
/*!
Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter
shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does.
\see setPen
*/
void QCPScatterStyle::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
Sets the pixmap that will be drawn as scatter point to \a pixmap.
Note that \ref setSize does not influence the appearance of the pixmap.
The scatter shape is automatically set to \ref ssPixmap.
*/
void QCPScatterStyle::setPixmap(const QPixmap &pixmap)
{
setShape(ssPixmap);
mPixmap = pixmap;
}
/*!
Sets the custom shape that will be drawn as scatter point to \a customPath.
The scatter shape is automatically set to \ref ssCustom.
*/
void QCPScatterStyle::setCustomPath(const QPainterPath &customPath)
{
setShape(ssCustom);
mCustomPath = customPath;
}
/*!
Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an
undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead.
This function is used by plottables (or any class that wants to draw scatters) just before a
number of scatters with this style shall be drawn with the \a painter.
\see drawShape
*/
void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const
{
painter->setPen(mPenDefined ? mPen : defaultPen);
painter->setBrush(mBrush);
}
/*!
Draws the scatter shape with \a painter at position \a pos.
This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be
called before scatter points are drawn with \ref drawShape.
\see applyTo
*/
void QCPScatterStyle::drawShape(QCPPainter *painter, QPointF pos) const
{
drawShape(painter, pos.x(), pos.y());
}
/*! \overload
Draws the scatter shape with \a painter at position \a x and \a y.
*/
void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const
{
double w = mSize/2.0;
switch (mShape)
{
case ssNone: break;
case ssDot:
{
painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y));
break;
}
case ssCross:
{
painter->drawLine(QLineF(x-w, y-w, x+w, y+w));
painter->drawLine(QLineF(x-w, y+w, x+w, y-w));
break;
}
case ssPlus:
{
painter->drawLine(QLineF(x-w, y, x+w, y));
painter->drawLine(QLineF( x, y+w, x, y-w));
break;
}
case ssCircle:
{
painter->drawEllipse(QPointF(x , y), w, w);
break;
}
case ssDisc:
{
QBrush b = painter->brush();
painter->setBrush(painter->pen().color());
painter->drawEllipse(QPointF(x , y), w, w);
painter->setBrush(b);
break;
}
case ssSquare:
{
painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
break;
}
case ssDiamond:
{
painter->drawLine(QLineF(x-w, y, x, y-w));
painter->drawLine(QLineF( x, y-w, x+w, y));
painter->drawLine(QLineF(x+w, y, x, y+w));
painter->drawLine(QLineF( x, y+w, x-w, y));
break;
}
case ssStar:
{
painter->drawLine(QLineF(x-w, y, x+w, y));
painter->drawLine(QLineF( x, y+w, x, y-w));
painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707));
painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707));
break;
}
case ssTriangle:
{
painter->drawLine(QLineF(x-w, y+0.755*w, x+w, y+0.755*w));
painter->drawLine(QLineF(x+w, y+0.755*w, x, y-0.977*w));
painter->drawLine(QLineF( x, y-0.977*w, x-w, y+0.755*w));
break;
}
case ssTriangleInverted:
{
painter->drawLine(QLineF(x-w, y-0.755*w, x+w, y-0.755*w));
painter->drawLine(QLineF(x+w, y-0.755*w, x, y+0.977*w));
painter->drawLine(QLineF( x, y+0.977*w, x-w, y-0.755*w));
break;
}
case ssCrossSquare:
{
painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95));
painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w));
painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
break;
}
case ssPlusSquare:
{
painter->drawLine(QLineF(x-w, y, x+w*0.95, y));
painter->drawLine(QLineF( x, y+w, x, y-w));
painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
break;
}
case ssCrossCircle:
{
painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670));
painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707));
painter->drawEllipse(QPointF(x, y), w, w);
break;
}
case ssPlusCircle:
{
painter->drawLine(QLineF(x-w, y, x+w, y));
painter->drawLine(QLineF( x, y+w, x, y-w));
painter->drawEllipse(QPointF(x, y), w, w);
break;
}
case ssPeace:
{
painter->drawLine(QLineF(x, y-w, x, y+w));
painter->drawLine(QLineF(x, y, x-w*0.707, y+w*0.707));
painter->drawLine(QLineF(x, y, x+w*0.707, y+w*0.707));
painter->drawEllipse(QPointF(x, y), w, w);
break;
}
case ssPixmap:
{
painter->drawPixmap(x-mPixmap.width()*0.5, y-mPixmap.height()*0.5, mPixmap);
break;
}
case ssCustom:
{
QTransform oldTransform = painter->transform();
painter->translate(x, y);
painter->scale(mSize/6.0, mSize/6.0);
painter->drawPath(mCustomPath);
painter->setTransform(oldTransform);
break;
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLayer
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLayer
\brief A layer that may contain objects, to control the rendering order
The Layering system of QCustomPlot is the mechanism to control the rendering order of the
elements inside the plot.
It is based on the two classes QCPLayer and QCPLayerable. QCustomPlot holds an ordered list of
one or more instances of QCPLayer (see QCustomPlot::addLayer, QCustomPlot::layer,
QCustomPlot::moveLayer, etc.). When replotting, QCustomPlot goes through the list of layers
bottom to top and successively draws the layerables of the layers.
A QCPLayer contains an ordered list of QCPLayerable instances. QCPLayerable is an abstract base
class from which almost all visible objects derive, like axes, grids, graphs, items, etc.
Initially, QCustomPlot has five layers: "background", "grid", "main", "axes" and "legend" (in
that order). The top two layers "axes" and "legend" contain the default axes and legend, so they
will be drawn on top. In the middle, there is the "main" layer. It is initially empty and set as
the current layer (see QCustomPlot::setCurrentLayer). This means, all new plottables, items etc.
are created on this layer by default. Then comes the "grid" layer which contains the QCPGrid
instances (which belong tightly to QCPAxis, see \ref QCPAxis::grid). The Axis rect background
shall be drawn behind everything else, thus the default QCPAxisRect instance is placed on the
"background" layer. Of course, the layer affiliation of the individual objects can be changed as
required (\ref QCPLayerable::setLayer).
Controlling the ordering of objects is easy: Create a new layer in the position you want it to
be, e.g. above "main", with QCustomPlot::addLayer. Then set the current layer with
QCustomPlot::setCurrentLayer to that new layer and finally create the objects normally. They will
be placed on the new layer automatically, due to the current layer setting. Alternatively you
could have also ignored the current layer setting and just moved the objects with
QCPLayerable::setLayer to the desired layer after creating them.
It is also possible to move whole layers. For example, If you want the grid to be shown in front
of all plottables/items on the "main" layer, just move it above "main" with
QCustomPlot::moveLayer.
The rendering order within one layer is simply by order of creation or insertion. The item
created last (or added last to the layer), is drawn on top of all other objects on that layer.
When a layer is deleted, the objects on it are not deleted with it, but fall on the layer below
the deleted layer, see QCustomPlot::removeLayer.
*/
/* start documentation of inline functions */
/*! \fn QList<QCPLayerable*> QCPLayer::children() const
Returns a list of all layerables on this layer. The order corresponds to the rendering order:
layerables with higher indices are drawn above layerables with lower indices.
*/
/*! \fn int QCPLayer::index() const
Returns the index this layer has in the QCustomPlot. The index is the integer number by which this layer can be
accessed via \ref QCustomPlot::layer.
Layers with higher indices will be drawn above layers with lower indices.
*/
/* end documentation of inline functions */
/*!
Creates a new QCPLayer instance.
Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead.
\warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot.
This check is only performed by \ref QCustomPlot::addLayer.
*/
QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) :
QObject(parentPlot),
mParentPlot(parentPlot),
mName(layerName),
mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function
mVisible(true)
{
// Note: no need to make sure layerName is unique, because layer
// management is done with QCustomPlot functions.
}
QCPLayer::~QCPLayer()
{
// If child layerables are still on this layer, detach them, so they don't try to reach back to this
// then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted
// directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to
// call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.)
while (!mChildren.isEmpty())
mChildren.last()->setLayer(0); // removes itself from mChildren via removeChild()
if (mParentPlot->currentLayer() == this)
qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or 0 beforehand.";
}
/*!
Sets whether this layer is visible or not. If \a visible is set to false, all layerables on this
layer will be invisible.
This function doesn't change the visibility property of the layerables (\ref
QCPLayerable::setVisible), but the \ref QCPLayerable::realVisibility of each layerable takes the
visibility of the parent layer into account.
*/
void QCPLayer::setVisible(bool visible)
{
mVisible = visible;
}
/*! \internal
Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will
be prepended to the list, i.e. be drawn beneath the other layerables already in the list.
This function does not change the \a mLayer member of \a layerable to this layer. (Use
QCPLayerable::setLayer to change the layer of an object, not this function.)
\see removeChild
*/
void QCPLayer::addChild(QCPLayerable *layerable, bool prepend)
{
if (!mChildren.contains(layerable))
{
if (prepend)
mChildren.prepend(layerable);
else
mChildren.append(layerable);
} else
qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast<quintptr>(layerable);
}
/*! \internal
Removes the \a layerable from the list of this layer.
This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer
to change the layer of an object, not this function.)
\see addChild
*/
void QCPLayer::removeChild(QCPLayerable *layerable)
{
if (!mChildren.removeOne(layerable))
qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast<quintptr>(layerable);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLayerable
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLayerable
\brief Base class for all drawable objects
This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid
etc.
Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking
the layers accordingly.
For details about the layering mechanism, see the QCPLayer documentation.
*/
/* start documentation of inline functions */
/*! \fn QCPLayerable *QCPLayerable::parentLayerable() const
Returns the parent layerable of this layerable. The parent layerable is used to provide
visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables
only get drawn if their parent layerables are visible, too.
Note that a parent layerable is not necessarily also the QObject parent for memory management.
Further, a layerable doesn't always have a parent layerable, so this function may return 0.
A parent layerable is set implicitly with when placed inside layout elements and doesn't need to be
set manually by the user.
*/
/* end documentation of inline functions */
/* start documentation of pure virtual functions */
/*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0
\internal
This function applies the default antialiasing setting to the specified \a painter, using the
function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when
\ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing
setting may be specified individually, this function should set the antialiasing state of the
most prominent entity. In this case however, the \ref draw function usually calls the specialized
versions of this function before drawing each entity, effectively overriding the setting of the
default antialiasing hint.
<b>First example:</b> QCPGraph has multiple entities that have an antialiasing setting: The graph
line, fills, scatters and error bars. Those can be configured via QCPGraph::setAntialiased,
QCPGraph::setAntialiasedFill, QCPGraph::setAntialiasedScatters etc. Consequently, there isn't
only the QCPGraph::applyDefaultAntialiasingHint function (which corresponds to the graph line's
antialiasing), but specialized ones like QCPGraph::applyFillAntialiasingHint and
QCPGraph::applyScattersAntialiasingHint. So before drawing one of those entities, QCPGraph::draw
calls the respective specialized applyAntialiasingHint function.
<b>Second example:</b> QCPItemLine consists only of a line so there is only one antialiasing
setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by
all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the
respective layerable subclass.) Consequently it only has the normal
QCPItemLine::applyDefaultAntialiasingHint. The \ref QCPItemLine::draw function doesn't need to
care about setting any antialiasing states, because the default antialiasing hint is already set
on the painter when the \ref draw function is called, and that's the state it wants to draw the
line with.
*/
/*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0
\internal
This function draws the layerable with the specified \a painter. It is only called by
QCustomPlot, if the layerable is visible (\ref setVisible).
Before this function is called, the painter's antialiasing state is set via \ref
applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was
set to \ref clipRect.
*/
/* end documentation of pure virtual functions */
/* start documentation of signals */
/*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer);
This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to
a different layer.
\see setLayer
*/
/* end documentation of signals */
/*!
Creates a new QCPLayerable instance.
Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the
derived classes.
If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a
targetLayer is an empty string, it places itself on the current layer of the plot (see \ref
QCustomPlot::setCurrentLayer).
It is possible to provide 0 as \a plot. In that case, you should assign a parent plot at a later
time with \ref initializeParentPlot.
The layerable's parent layerable is set to \a parentLayerable, if provided. Direct layerable
parents are mainly used to control visibility in a hierarchy of layerables. This means a
layerable is only drawn, if all its ancestor layerables are also visible. Note that \a
parentLayerable does not become the QObject-parent (for memory management) of this layerable, \a
plot does. It is not uncommon to set the QObject-parent to something else in the constructors of
QCPLayerable subclasses, to guarantee a working destruction hierarchy.
*/
QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) :
QObject(plot),
mVisible(true),
mParentPlot(plot),
mParentLayerable(parentLayerable),
mLayer(0),
mAntialiased(true)
{
if (mParentPlot)
{
if (targetLayer.isEmpty())
setLayer(mParentPlot->currentLayer());
else if (!setLayer(targetLayer))
qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed.";
}
}
QCPLayerable::~QCPLayerable()
{
if (mLayer)
{
mLayer->removeChild(this);
mLayer = 0;
}
}
/*!
Sets the visibility of this layerable object. If an object is not visible, it will not be drawn
on the QCustomPlot surface, and user interaction with it (e.g. click and selection) is not
possible.
*/
void QCPLayerable::setVisible(bool on)
{
mVisible = on;
}
/*!
Sets the \a layer of this layerable object. The object will be placed on top of the other objects
already on \a layer.
If \a layer is 0, this layerable will not be on any layer and thus not appear in the plot (or
interact/receive events).
Returns true if the layer of this layerable was successfully changed to \a layer.
*/
bool QCPLayerable::setLayer(QCPLayer *layer)
{
return moveToLayer(layer, false);
}
/*! \overload
Sets the layer of this layerable object by name
Returns true on success, i.e. if \a layerName is a valid layer name.
*/
bool QCPLayerable::setLayer(const QString &layerName)
{
if (!mParentPlot)
{
qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
return false;
}
if (QCPLayer *layer = mParentPlot->layer(layerName))
{
return setLayer(layer);
} else
{
qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName;
return false;
}
}
/*!
Sets whether this object will be drawn antialiased or not.
Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and
QCustomPlot::setNotAntialiasedElements.
*/
void QCPLayerable::setAntialiased(bool enabled)
{
mAntialiased = enabled;
}
/*!
Returns whether this layerable is visible, taking the visibility of the layerable parent and the
visibility of the layer this layerable is on into account. This is the method that is consulted
to decide whether a layerable shall be drawn or not.
If this layerable has a direct layerable parent (usually set via hierarchies implemented in
subclasses, like in the case of QCPLayoutElement), this function returns true only if this
layerable has its visibility set to true and the parent layerable's \ref realVisibility returns
true.
If this layerable doesn't have a direct layerable parent, returns the state of this layerable's
visibility.
*/
bool QCPLayerable::realVisibility() const
{
return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility());
}
/*!
This function is used to decide whether a click hits a layerable object or not.
\a pos is a point in pixel coordinates on the QCustomPlot surface. This function returns the
shortest pixel distance of this point to the object. If the object is either invisible or the
distance couldn't be determined, -1.0 is returned. Further, if \a onlySelectable is true and the
object is not selectable, -1.0 is returned, too.
If the object is represented not by single lines but by an area like a \ref QCPItemText or the
bars of a \ref QCPBars plottable, a click inside the area should also be considered a hit. In
these cases this function thus returns a constant value greater zero but still below the parent
plot's selection tolerance. (typically the selectionTolerance multiplied by 0.99).
Providing a constant value for area objects allows selecting line objects even when they are
obscured by such area objects, by clicking close to the lines (i.e. closer than
0.99*selectionTolerance).
The actual setting of the selection state is not done by this function. This is handled by the
parent QCustomPlot when the mouseReleaseEvent occurs, and the finally selected object is notified
via the selectEvent/deselectEvent methods.
\a details is an optional output parameter. Every layerable subclass may place any information
in \a details. This information will be passed to \ref selectEvent when the parent QCustomPlot
decides on the basis of this selectTest call, that the object was successfully selected. The
subsequent call to \ref selectEvent will carry the \a details. This is useful for multi-part
objects (like QCPAxis). This way, a possibly complex calculation to decide which part was clicked
is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be
placed in \a details. So in the subsequent \ref selectEvent, the decision which part was
selected doesn't have to be done a second time for a single selection operation.
You may pass 0 as \a details to indicate that you are not interested in those selection details.
\see selectEvent, deselectEvent, QCustomPlot::setInteractions
*/
double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(pos)
Q_UNUSED(onlySelectable)
Q_UNUSED(details)
return -1.0;
}
/*! \internal
Sets the parent plot of this layerable. Use this function once to set the parent plot if you have
passed 0 in the constructor. It can not be used to move a layerable from one QCustomPlot to
another one.
Note that, unlike when passing a non-null parent plot in the constructor, this function does not
make \a parentPlot the QObject-parent of this layerable. If you want this, call
QObject::setParent(\a parentPlot) in addition to this function.
Further, you will probably want to set a layer (\ref setLayer) after calling this function, to
make the layerable appear on the QCustomPlot.
The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized
so they can react accordingly (e.g. also initialize the parent plot of child layerables, like
QCPLayout does).
*/
void QCPLayerable::initializeParentPlot(QCustomPlot *parentPlot)
{
if (mParentPlot)
{
qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized";
return;
}
if (!parentPlot)
qDebug() << Q_FUNC_INFO << "called with parentPlot zero";
mParentPlot = parentPlot;
parentPlotInitialized(mParentPlot);
}
/*! \internal
Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not
become the QObject-parent (for memory management) of this layerable.
The parent layerable has influence on the return value of the \ref realVisibility method. Only
layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be
drawn.
\see realVisibility
*/
void QCPLayerable::setParentLayerable(QCPLayerable *parentLayerable)
{
mParentLayerable = parentLayerable;
}
/*! \internal
Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to
the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is
false, the object will be appended.
Returns true on success, i.e. if \a layer is a valid layer.
*/
bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend)
{
if (layer && !mParentPlot)
{
qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
return false;
}
if (layer && layer->parentPlot() != mParentPlot)
{
qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable";
return false;
}
QCPLayer *oldLayer = mLayer;
if (mLayer)
mLayer->removeChild(this);
mLayer = layer;
if (mLayer)
mLayer->addChild(this, prepend);
if (mLayer != oldLayer)
emit layerChanged(mLayer);
return true;
}
/*! \internal
Sets the QCPainter::setAntialiasing state on the provided \a painter, depending on the \a
localAntialiased value as well as the overrides \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements. Which override enum this function takes into account is
controlled via \a overrideElement.
*/
void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const
{
if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement))
painter->setAntialiasing(false);
else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement))
painter->setAntialiasing(true);
else
painter->setAntialiasing(localAntialiased);
}
/*! \internal
This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting
of a parent plot. This is the case when 0 was passed as parent plot in the constructor, and the
parent plot is set at a later time.
For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any
QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level
element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To
propagate the parent plot to all the children of the hierarchy, the top level element then uses
this function to pass the parent plot on to its child elements.
The default implementation does nothing.
\see initializeParentPlot
*/
void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot)
{
Q_UNUSED(parentPlot)
}
/*! \internal
Returns the selection category this layerable shall belong to. The selection category is used in
conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and
which aren't.
Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref
QCP::iSelectOther. This is what the default implementation returns.
\see QCustomPlot::setInteractions
*/
QCP::Interaction QCPLayerable::selectionCategory() const
{
return QCP::iSelectOther;
}
/*! \internal
Returns the clipping rectangle of this layerable object. By default, this is the viewport of the
parent QCustomPlot. Specific subclasses may reimplement this function to provide different
clipping rects.
The returned clipping rect is set on the painter before the draw function of the respective
object is called.
*/
QRect QCPLayerable::clipRect() const
{
if (mParentPlot)
return mParentPlot->viewport();
else
return QRect();
}
/*! \internal
This event is called when the layerable shall be selected, as a consequence of a click by the
user. Subclasses should react to it by setting their selection state appropriately. The default
implementation does nothing.
\a event is the mouse event that caused the selection. \a additive indicates, whether the user
was holding the multi-select-modifier while performing the selection (see \ref
QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled
(i.e. become selected when unselected and unselected when selected).
Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e.
returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot).
The \a details data you output from \ref selectTest is fed back via \a details here. You may
use it to transport any kind of information from the selectTest to the possibly subsequent
selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable
that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need
to do the calculation again to find out which part was actually clicked.
\a selectionStateChanged is an output parameter. If the pointer is non-null, this function must
set the value either to true or false, depending on whether the selection state of this layerable
was actually changed. For layerables that only are selectable as a whole and not in parts, this
is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the
selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the
layerable was previously unselected and now is switched to the selected state.
\see selectTest, deselectEvent
*/
void QCPLayerable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
Q_UNUSED(additive)
Q_UNUSED(details)
Q_UNUSED(selectionStateChanged)
}
/*! \internal
This event is called when the layerable shall be deselected, either as consequence of a user
interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by
unsetting their selection appropriately.
just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must
return true or false when the selection state of this layerable has changed or not changed,
respectively.
\see selectTest, selectEvent
*/
void QCPLayerable::deselectEvent(bool *selectionStateChanged)
{
Q_UNUSED(selectionStateChanged)
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPRange
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPRange
\brief Represents the range an axis is encompassing.
contains a \a lower and \a upper double value and provides convenience input, output and
modification functions.
\see QCPAxis::setRange
*/
/*!
Minimum range size (\a upper - \a lower) the range changing functions will accept. Smaller
intervals would cause errors due to the 11-bit exponent of double precision numbers,
corresponding to a minimum magnitude of roughly 1e-308.
\see validRange, maxRange
*/
const double QCPRange::minRange = 1e-280;
/*!
Maximum values (negative and positive) the range will accept in range-changing functions.
Larger absolute values would cause errors due to the 11-bit exponent of double precision numbers,
corresponding to a maximum magnitude of roughly 1e308.
Since the number of planck-volumes in the entire visible universe is only ~1e183, this should
be enough.
\see validRange, minRange
*/
const double QCPRange::maxRange = 1e250;
/*!
Constructs a range with \a lower and \a upper set to zero.
*/
QCPRange::QCPRange() :
lower(0),
upper(0)
{
}
/*! \overload
Constructs a range with the specified \a lower and \a upper values.
*/
QCPRange::QCPRange(double lower, double upper) :
lower(lower),
upper(upper)
{
normalize();
}
/*!
Returns the size of the range, i.e. \a upper-\a lower
*/
double QCPRange::size() const
{
return upper-lower;
}
/*!
Returns the center of the range, i.e. (\a upper+\a lower)*0.5
*/
double QCPRange::center() const
{
return (upper+lower)*0.5;
}
/*!
Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values
are swapped.
*/
void QCPRange::normalize()
{
if (lower > upper)
qSwap(lower, upper);
}
/*!
Expands this range such that \a otherRange is contained in the new range. It is assumed that both
this range and \a otherRange are normalized (see \ref normalize).
If \a otherRange is already inside the current range, this function does nothing.
\see expanded
*/
void QCPRange::expand(const QCPRange &otherRange)
{
if (lower > otherRange.lower)
lower = otherRange.lower;
if (upper < otherRange.upper)
upper = otherRange.upper;
}
/*!
Returns an expanded range that contains this and \a otherRange. It is assumed that both this
range and \a otherRange are normalized (see \ref normalize).
\see expand
*/
QCPRange QCPRange::expanded(const QCPRange &otherRange) const
{
QCPRange result = *this;
result.expand(otherRange);
return result;
}
/*!
Returns a sanitized version of the range. Sanitized means for logarithmic scales, that
the range won't span the positive and negative sign domain, i.e. contain zero. Further
\a lower will always be numerically smaller (or equal) to \a upper.
If the original range does span positive and negative sign domains or contains zero,
the returned range will try to approximate the original range as good as possible.
If the positive interval of the original range is wider than the negative interval, the
returned range will only contain the positive interval, with lower bound set to \a rangeFac or
\a rangeFac *\a upper, whichever is closer to zero. Same procedure is used if the negative interval
is wider than the positive interval, this time by changing the \a upper bound.
*/
QCPRange QCPRange::sanitizedForLogScale() const
{
double rangeFac = 1e-3;
QCPRange sanitizedRange(lower, upper);
sanitizedRange.normalize();
// can't have range spanning negative and positive values in log plot, so change range to fix it
//if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1))
if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0)
{
// case lower is 0
if (rangeFac < sanitizedRange.upper*rangeFac)
sanitizedRange.lower = rangeFac;
else
sanitizedRange.lower = sanitizedRange.upper*rangeFac;
} //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1))
else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0)
{
// case upper is 0
if (-rangeFac > sanitizedRange.lower*rangeFac)
sanitizedRange.upper = -rangeFac;
else
sanitizedRange.upper = sanitizedRange.lower*rangeFac;
} else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0)
{
// find out whether negative or positive interval is wider to decide which sign domain will be chosen
if (-sanitizedRange.lower > sanitizedRange.upper)
{
// negative is wider, do same as in case upper is 0
if (-rangeFac > sanitizedRange.lower*rangeFac)
sanitizedRange.upper = -rangeFac;
else
sanitizedRange.upper = sanitizedRange.lower*rangeFac;
} else
{
// positive is wider, do same as in case lower is 0
if (rangeFac < sanitizedRange.upper*rangeFac)
sanitizedRange.lower = rangeFac;
else
sanitizedRange.lower = sanitizedRange.upper*rangeFac;
}
}
// due to normalization, case lower>0 && upper<0 should never occur, because that implies upper<lower
return sanitizedRange;
}
/*!
Returns a sanitized version of the range. Sanitized means for linear scales, that
\a lower will always be numerically smaller (or equal) to \a upper.
*/
QCPRange QCPRange::sanitizedForLinScale() const
{
QCPRange sanitizedRange(lower, upper);
sanitizedRange.normalize();
return sanitizedRange;
}
/*!
Returns true when \a value lies within or exactly on the borders of the range.
*/
bool QCPRange::contains(double value) const
{
return value >= lower && value <= upper;
}
/*!
Checks, whether the specified range is within valid bounds, which are defined
as QCPRange::maxRange and QCPRange::minRange.
A valid range means:
\li range bounds within -maxRange and maxRange
\li range size above minRange
\li range size below maxRange
*/
bool QCPRange::validRange(double lower, double upper)
{
return (lower > -maxRange &&
upper < maxRange &&
qAbs(lower-upper) > minRange &&
qAbs(lower-upper) < maxRange &&
!(lower > 0 && qIsInf(upper/lower)) &&
!(upper < 0 && qIsInf(lower/upper)));
}
/*!
\overload
Checks, whether the specified range is within valid bounds, which are defined
as QCPRange::maxRange and QCPRange::minRange.
A valid range means:
\li range bounds within -maxRange and maxRange
\li range size above minRange
\li range size below maxRange
*/
bool QCPRange::validRange(const QCPRange &range)
{
return (range.lower > -maxRange &&
range.upper < maxRange &&
qAbs(range.lower-range.upper) > minRange &&
qAbs(range.lower-range.upper) < maxRange &&
!(range.lower > 0 && qIsInf(range.upper/range.lower)) &&
!(range.upper < 0 && qIsInf(range.lower/range.upper)));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPMarginGroup
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPMarginGroup
\brief A margin group allows synchronization of margin sides if working with multiple layout elements.
QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that
they will all have the same size, based on the largest required margin in the group.
\n
\image html QCPMarginGroup.png "Demonstration of QCPMarginGroup"
\n
In certain situations it is desirable that margins at specific sides are synchronized across
layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will
provide a cleaner look to the user if the left and right margins of the two axis rects are of the
same size. The left axis of the top axis rect will then be at the same horizontal position as the
left axis of the lower axis rect, making them appear aligned. The same applies for the right
axes. This is what QCPMarginGroup makes possible.
To add/remove a specific side of a layout element to/from a margin group, use the \ref
QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call
\ref clear, or just delete the margin group.
\section QCPMarginGroup-example Example
First create a margin group:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-1
Then set this group on the layout element sides:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-2
Here, we've used the first two axis rects of the plot and synchronized their left margins with
each other and their right margins with each other.
*/
/* start documentation of inline functions */
/*! \fn QList<QCPLayoutElement*> QCPMarginGroup::elements(QCP::MarginSide side) const
Returns a list of all layout elements that have their margin \a side associated with this margin
group.
*/
/* end documentation of inline functions */
/*!
Creates a new QCPMarginGroup instance in \a parentPlot.
*/
QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) :
QObject(parentPlot),
mParentPlot(parentPlot)
{
mChildren.insert(QCP::msLeft, QList<QCPLayoutElement*>());
mChildren.insert(QCP::msRight, QList<QCPLayoutElement*>());
mChildren.insert(QCP::msTop, QList<QCPLayoutElement*>());
mChildren.insert(QCP::msBottom, QList<QCPLayoutElement*>());
}
QCPMarginGroup::~QCPMarginGroup()
{
clear();
}
/*!
Returns whether this margin group is empty. If this function returns true, no layout elements use
this margin group to synchronize margin sides.
*/
bool QCPMarginGroup::isEmpty() const
{
QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
while (it.hasNext())
{
it.next();
if (!it.value().isEmpty())
return false;
}
return true;
}
/*!
Clears this margin group. The synchronization of the margin sides that use this margin group is
lifted and they will use their individual margin sizes again.
*/
void QCPMarginGroup::clear()
{
// make all children remove themselves from this margin group:
QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
while (it.hasNext())
{
it.next();
const QList<QCPLayoutElement*> elements = it.value();
for (int i=elements.size()-1; i>=0; --i)
elements.at(i)->setMarginGroup(it.key(), 0); // removes itself from mChildren via removeChild
}
}
/*! \internal
Returns the synchronized common margin for \a side. This is the margin value that will be used by
the layout element on the respective side, if it is part of this margin group.
The common margin is calculated by requesting the automatic margin (\ref
QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin
group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into
account, too.)
*/
int QCPMarginGroup::commonMargin(QCP::MarginSide side) const
{
// query all automatic margins of the layout elements in this margin group side and find maximum:
int result = 0;
const QList<QCPLayoutElement*> elements = mChildren.value(side);
for (int i=0; i<elements.size(); ++i)
{
if (!elements.at(i)->autoMargins().testFlag(side))
continue;
int m = qMax(elements.at(i)->calculateAutoMargin(side), QCP::getMarginValue(elements.at(i)->minimumMargins(), side));
if (m > result)
result = m;
}
return result;
}
/*! \internal
Adds \a element to the internal list of child elements, for the margin \a side.
This function does not modify the margin group property of \a element.
*/
void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element)
{
if (!mChildren[side].contains(element))
mChildren[side].append(element);
else
qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast<quintptr>(element);
}
/*! \internal
Removes \a element from the internal list of child elements, for the margin \a side.
This function does not modify the margin group property of \a element.
*/
void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element)
{
if (!mChildren[side].removeOne(element))
qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast<quintptr>(element);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLayoutElement
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLayoutElement
\brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system".
This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses.
A Layout element is a rectangular object which can be placed in layouts. It has an outer rect
(QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference
between outer and inner rect is called its margin. The margin can either be set to automatic or
manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be
set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic,
the layout element subclass will control the value itself (via \ref calculateAutoMargin).
Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level
layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref
QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested.
Thus in QCustomPlot one can divide layout elements into two categories: The ones that are
invisible by themselves, because they don't draw anything. Their only purpose is to manage the
position and size of other layout elements. This category of layout elements usually use
QCPLayout as base class. Then there is the category of layout elements which actually draw
something. For example, QCPAxisRect, QCPLegend and QCPPlotTitle are of this category. This does
not necessarily mean that the latter category can't have child layout elements. QCPLegend for
instance, actually derives from QCPLayoutGrid and the individual legend items are child layout
elements in the grid layout.
*/
/* start documentation of inline functions */
/*! \fn QCPLayout *QCPLayoutElement::layout() const
Returns the parent layout of this layout element.
*/
/*! \fn QRect QCPLayoutElement::rect() const
Returns the inner rect of this layout element. The inner rect is the outer rect (\ref
setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins).
In some cases, the area between outer and inner rect is left blank. In other cases the margin
area is used to display peripheral graphics while the main content is in the inner rect. This is
where automatic margin calculation becomes interesting because it allows the layout element to
adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect
draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if
\ref setAutoMargins is enabled) according to the space required by the labels of the axes.
*/
/*! \fn virtual void QCPLayoutElement::mousePressEvent(QMouseEvent *event)
This event is called, if the mouse was pressed while being inside the outer rect of this layout
element.
*/
/*! \fn virtual void QCPLayoutElement::mouseMoveEvent(QMouseEvent *event)
This event is called, if the mouse is moved inside the outer rect of this layout element.
*/
/*! \fn virtual void QCPLayoutElement::mouseReleaseEvent(QMouseEvent *event)
This event is called, if the mouse was previously pressed inside the outer rect of this layout
element and is now released.
*/
/*! \fn virtual void QCPLayoutElement::mouseDoubleClickEvent(QMouseEvent *event)
This event is called, if the mouse is double-clicked inside the outer rect of this layout
element.
*/
/*! \fn virtual void QCPLayoutElement::wheelEvent(QWheelEvent *event)
This event is called, if the mouse wheel is scrolled while the cursor is inside the rect of this
layout element.
*/
/* end documentation of inline functions */
/*!
Creates an instance of QCPLayoutElement and sets default values.
*/
QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) :
QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout)
mParentLayout(0),
mMinimumSize(),
mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX),
mRect(0, 0, 0, 0),
mOuterRect(0, 0, 0, 0),
mMargins(0, 0, 0, 0),
mMinimumMargins(0, 0, 0, 0),
mAutoMargins(QCP::msAll)
{
}
QCPLayoutElement::~QCPLayoutElement()
{
setMarginGroup(QCP::msAll, 0); // unregister at margin groups, if there are any
// unregister at layout:
if (qobject_cast<QCPLayout*>(mParentLayout)) // the qobject_cast is just a safeguard in case the layout forgets to call clear() in its dtor and this dtor is called by QObject dtor
mParentLayout->take(this);
}
/*!
Sets the outer rect of this layout element. If the layout element is inside a layout, the layout
sets the position and size of this layout element using this function.
Calling this function externally has no effect, since the layout will overwrite any changes to
the outer rect upon the next replot.
The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect.
\see rect
*/
void QCPLayoutElement::setOuterRect(const QRect &rect)
{
if (mOuterRect != rect)
{
mOuterRect = rect;
mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
}
}
/*!
Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all
sides, this function is used to manually set the margin on those sides. Sides that are still set
to be handled automatically are ignored and may have any value in \a margins.
The margin is the distance between the outer rect (controlled by the parent layout via \ref
setOuterRect) and the inner \ref rect (which usually contains the main content of this layout
element).
\see setAutoMargins
*/
void QCPLayoutElement::setMargins(const QMargins &margins)
{
if (mMargins != margins)
{
mMargins = margins;
mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
}
}
/*!
If \ref setAutoMargins is enabled on some or all margins, this function is used to provide
minimum values for those margins.
The minimum values are not enforced on margin sides that were set to be under manual control via
\ref setAutoMargins.
\see setAutoMargins
*/
void QCPLayoutElement::setMinimumMargins(const QMargins &margins)
{
if (mMinimumMargins != margins)
{
mMinimumMargins = margins;
}
}
/*!
Sets on which sides the margin shall be calculated automatically. If a side is calculated
automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is
set to be controlled manually, the value may be specified with \ref setMargins.
Margin sides that are under automatic control may participate in a \ref QCPMarginGroup (see \ref
setMarginGroup), to synchronize (align) it with other layout elements in the plot.
\see setMinimumMargins, setMargins
*/
void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides)
{
mAutoMargins = sides;
}
/*!
Sets the minimum size for the inner \ref rect of this layout element. A parent layout tries to
respect the \a size here by changing row/column sizes in the layout accordingly.
If the parent layout size is not sufficient to satisfy all minimum size constraints of its child
layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot
propagates the layout's size constraints to the outside by setting its own minimum QWidget size
accordingly, so violations of \a size should be exceptions.
*/
void QCPLayoutElement::setMinimumSize(const QSize &size)
{
if (mMinimumSize != size)
{
mMinimumSize = size;
if (mParentLayout)
mParentLayout->sizeConstraintsChanged();
}
}
/*! \overload
Sets the minimum size for the inner \ref rect of this layout element.
*/
void QCPLayoutElement::setMinimumSize(int width, int height)
{
setMinimumSize(QSize(width, height));
}
/*!
Sets the maximum size for the inner \ref rect of this layout element. A parent layout tries to
respect the \a size here by changing row/column sizes in the layout accordingly.
*/
void QCPLayoutElement::setMaximumSize(const QSize &size)
{
if (mMaximumSize != size)
{
mMaximumSize = size;
if (mParentLayout)
mParentLayout->sizeConstraintsChanged();
}
}
/*! \overload
Sets the maximum size for the inner \ref rect of this layout element.
*/
void QCPLayoutElement::setMaximumSize(int width, int height)
{
setMaximumSize(QSize(width, height));
}
/*!
Sets the margin \a group of the specified margin \a sides.
Margin groups allow synchronizing specified margins across layout elements, see the documentation
of \ref QCPMarginGroup.
To unset the margin group of \a sides, set \a group to 0.
Note that margin groups only work for margin sides that are set to automatic (\ref
setAutoMargins).
*/
void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group)
{
QVector<QCP::MarginSide> sideVector;
if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft);
if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight);
if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop);
if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom);
for (int i=0; i<sideVector.size(); ++i)
{
QCP::MarginSide side = sideVector.at(i);
if (marginGroup(side) != group)
{
QCPMarginGroup *oldGroup = marginGroup(side);
if (oldGroup) // unregister at old group
oldGroup->removeChild(side, this);
if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there
{
mMarginGroups.remove(side);
} else // setting to a new group
{
mMarginGroups[side] = group;
group->addChild(side, this);
}
}
}
}
/*!
Updates the layout element and sub-elements. This function is automatically called before every
replot by the parent layout element. It is called multiple times, once for every \ref
UpdatePhase. The phases are run through in the order of the enum values. For details about what
happens at the different phases, see the documentation of \ref UpdatePhase.
Layout elements that have child elements should call the \ref update method of their child
elements, and pass the current \a phase unchanged.
The default implementation executes the automatic margin mechanism in the \ref upMargins phase.
Subclasses should make sure to call the base class implementation.
*/
void QCPLayoutElement::update(UpdatePhase phase)
{
if (phase == upMargins)
{
if (mAutoMargins != QCP::msNone)
{
// set the margins of this layout element according to automatic margin calculation, either directly or via a margin group:
QMargins newMargins = mMargins;
QList<QCP::MarginSide> allMarginSides = QList<QCP::MarginSide>() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom;
foreach (QCP::MarginSide side, allMarginSides)
{
if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically
{
if (mMarginGroups.contains(side))
QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group
else
QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly
// apply minimum margin restrictions:
if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side))
QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side));
}
}
setMargins(newMargins);
}
}
}
/*!
Returns the minimum size this layout element (the inner \ref rect) may be compressed to.
if a minimum size (\ref setMinimumSize) was not set manually, parent layouts consult this
function to determine the minimum allowed size of this layout element. (A manual minimum size is
considered set if it is non-zero.)
*/
QSize QCPLayoutElement::minimumSizeHint() const
{
return mMinimumSize;
}
/*!
Returns the maximum size this layout element (the inner \ref rect) may be expanded to.
if a maximum size (\ref setMaximumSize) was not set manually, parent layouts consult this
function to determine the maximum allowed size of this layout element. (A manual maximum size is
considered set if it is smaller than Qt's QWIDGETSIZE_MAX.)
*/
QSize QCPLayoutElement::maximumSizeHint() const
{
return mMaximumSize;
}
/*!
Returns a list of all child elements in this layout element. If \a recursive is true, all
sub-child elements are included in the list, too.
\warning There may be entries with value 0 in the returned list. (For example, QCPLayoutGrid may have
empty cells which yield 0 at the respective index.)
*/
QList<QCPLayoutElement*> QCPLayoutElement::elements(bool recursive) const
{
Q_UNUSED(recursive)
return QList<QCPLayoutElement*>();
}
/*!
Layout elements are sensitive to events inside their outer rect. If \a pos is within the outer
rect, this method returns a value corresponding to 0.99 times the parent plot's selection
tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is
true, -1.0 is returned.
See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
QCPLayoutElement subclasses may reimplement this method to provide more specific selection test
behaviour.
*/
double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable)
return -1;
if (QRectF(mOuterRect).contains(pos))
{
if (mParentPlot)
return mParentPlot->selectionTolerance()*0.99;
else
{
qDebug() << Q_FUNC_INFO << "parent plot not defined";
return -1;
}
} else
return -1;
}
/*! \internal
propagates the parent plot initialization to all child elements, by calling \ref
QCPLayerable::initializeParentPlot on them.
*/
void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot)
{
foreach (QCPLayoutElement* el, elements(false))
{
if (!el->parentPlot())
el->initializeParentPlot(parentPlot);
}
}
/*! \internal
Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a
side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the
returned value will not be smaller than the specified minimum margin.
The default implementation just returns the respective manual margin (\ref setMargins) or the
minimum margin, whichever is larger.
*/
int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side)
{
return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLayout
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLayout
\brief The abstract base class for layouts
This is an abstract base class for layout elements whose main purpose is to define the position
and size of other child layout elements. In most cases, layouts don't draw anything themselves
(but there are exceptions to this, e.g. QCPLegend).
QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts.
QCPLayout introduces a common interface for accessing and manipulating the child elements. Those
functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref
simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions
to this interface which are more specialized to the form of the layout. For example, \ref
QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid
more conveniently.
Since this is an abstract base class, you can't instantiate it directly. Rather use one of its
subclasses like QCPLayoutGrid or QCPLayoutInset.
For a general introduction to the layout system, see the dedicated documentation page \ref
thelayoutsystem "The Layout System".
*/
/* start documentation of pure virtual functions */
/*! \fn virtual int QCPLayout::elementCount() const = 0
Returns the number of elements/cells in the layout.
\see elements, elementAt
*/
/*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0
Returns the element in the cell with the given \a index. If \a index is invalid, returns 0.
Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g.
QCPLayoutGrid), so this function may return 0 in those cases. You may use this function to check
whether a cell is empty or not.
\see elements, elementCount, takeAt
*/
/*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0
Removes the element with the given \a index from the layout and returns it.
If the \a index is invalid or the cell with that index is empty, returns 0.
Note that some layouts don't remove the respective cell right away but leave an empty cell after
successful removal of the layout element. To collapse empty cells, use \ref simplify.
\see elementAt, take
*/
/*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0
Removes the specified \a element from the layout and returns true on success.
If the \a element isn't in this layout, returns false.
Note that some layouts don't remove the respective cell right away but leave an empty cell after
successful removal of the layout element. To collapse empty cells, use \ref simplify.
\see takeAt
*/
/* end documentation of pure virtual functions */
/*!
Creates an instance of QCPLayout and sets default values. Note that since QCPLayout
is an abstract base class, it can't be instantiated directly.
*/
QCPLayout::QCPLayout()
{
}
/*!
First calls the QCPLayoutElement::update base class implementation to update the margins on this
layout.
Then calls \ref updateLayout which subclasses reimplement to reposition and resize their cells.
Finally, \ref update is called on all child elements.
*/
void QCPLayout::update(UpdatePhase phase)
{
QCPLayoutElement::update(phase);
// set child element rects according to layout:
if (phase == upLayout)
updateLayout();
// propagate update call to child elements:
const int elCount = elementCount();
for (int i=0; i<elCount; ++i)
{
if (QCPLayoutElement *el = elementAt(i))
el->update(phase);
}
}
/* inherits documentation from base class */
QList<QCPLayoutElement*> QCPLayout::elements(bool recursive) const
{
const int c = elementCount();
QList<QCPLayoutElement*> result;
#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
result.reserve(c);
#endif
for (int i=0; i<c; ++i)
result.append(elementAt(i));
if (recursive)
{
for (int i=0; i<c; ++i)
{
if (result.at(i))
result << result.at(i)->elements(recursive);
}
}
return result;
}
/*!
Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the
default implementation does nothing.
Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit
simplification while QCPLayoutGrid does.
*/
void QCPLayout::simplify()
{
}
/*!
Removes and deletes the element at the provided \a index. Returns true on success. If \a index is
invalid or points to an empty cell, returns false.
This function internally uses \ref takeAt to remove the element from the layout and then deletes
the returned element. Note that some layouts don't remove the respective cell right away but leave an
empty cell after successful removal of the layout element. To collapse empty cells, use \ref
simplify.
\see remove, takeAt
*/
bool QCPLayout::removeAt(int index)
{
if (QCPLayoutElement *el = takeAt(index))
{
delete el;
return true;
} else
return false;
}
/*!
Removes and deletes the provided \a element. Returns true on success. If \a element is not in the
layout, returns false.
This function internally uses \ref takeAt to remove the element from the layout and then deletes
the element. Note that some layouts don't remove the respective cell right away but leave an
empty cell after successful removal of the layout element. To collapse empty cells, use \ref
simplify.
\see removeAt, take
*/
bool QCPLayout::remove(QCPLayoutElement *element)
{
if (take(element))
{
delete element;
return true;
} else
return false;
}
/*!
Removes and deletes all layout elements in this layout. Finally calls \ref simplify to make sure
all empty cells are collapsed.
\see remove, removeAt
*/
void QCPLayout::clear()
{
for (int i=elementCount()-1; i>=0; --i)
{
if (elementAt(i))
removeAt(i);
}
simplify();
}
/*!
Subclasses call this method to report changed (minimum/maximum) size constraints.
If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref
sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of
QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout,
it may update itself and resize cells accordingly.
*/
void QCPLayout::sizeConstraintsChanged() const
{
if (QWidget *w = qobject_cast<QWidget*>(parent()))
w->updateGeometry();
else if (QCPLayout *l = qobject_cast<QCPLayout*>(parent()))
l->sizeConstraintsChanged();
}
/*! \internal
Subclasses reimplement this method to update the position and sizes of the child elements/cells
via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing.
The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay
within that rect.
\ref getSectionSizes may help with the reimplementation of this function.
\see update
*/
void QCPLayout::updateLayout()
{
}
/*! \internal
Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the
\ref QCPLayerable::parentLayerable and the QObject parent to this layout.
Further, if \a el didn't previously have a parent plot, calls \ref
QCPLayerable::initializeParentPlot on \a el to set the paret plot.
This method is used by subclass specific methods that add elements to the layout. Note that this
method only changes properties in \a el. The removal from the old layout and the insertion into
the new layout must be done additionally.
*/
void QCPLayout::adoptElement(QCPLayoutElement *el)
{
if (el)
{
el->mParentLayout = this;
el->setParentLayerable(this);
el->setParent(this);
if (!el->parentPlot())
el->initializeParentPlot(mParentPlot);
} else
qDebug() << Q_FUNC_INFO << "Null element passed";
}
/*! \internal
Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout
and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent
QCustomPlot.
This method is used by subclass specific methods that remove elements from the layout (e.g. \ref
take or \ref takeAt). Note that this method only changes properties in \a el. The removal from
the old layout must be done additionally.
*/
void QCPLayout::releaseElement(QCPLayoutElement *el)
{
if (el)
{
el->mParentLayout = 0;
el->setParentLayerable(0);
el->setParent(mParentPlot);
// Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot
} else
qDebug() << Q_FUNC_INFO << "Null element passed";
}
/*! \internal
This is a helper function for the implementation of \ref updateLayout in subclasses.
It calculates the sizes of one-dimensional sections with provided constraints on maximum section
sizes, minimum section sizes, relative stretch factors and the final total size of all sections.
The QVector entries refer to the sections. Thus all QVectors must have the same size.
\a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size
imposed, set all vector values to Qt's QWIDGETSIZE_MAX.
\a minSizes gives the minimum allowed size of each section. If there shall be no minimum size
imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than
\a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words,
not exceeding the allowed total size is taken to be more important than not going below minimum
section sizes.)
\a stretchFactors give the relative proportions of the sections to each other. If all sections
shall be scaled equally, set all values equal. If the first section shall be double the size of
each individual other section, set the first number of \a stretchFactors to double the value of
the other individual values (e.g. {2, 1, 1, 1}).
\a totalSize is the value that the final section sizes will add up to. Due to rounding, the
actual sum may differ slightly. If you want the section sizes to sum up to exactly that value,
you could distribute the remaining difference on the sections.
The return value is a QVector containing the section sizes.
*/
QVector<int> QCPLayout::getSectionSizes(QVector<int> maxSizes, QVector<int> minSizes, QVector<double> stretchFactors, int totalSize) const
{
if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size())
{
qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors;
return QVector<int>();
}
if (stretchFactors.isEmpty())
return QVector<int>();
int sectionCount = stretchFactors.size();
QVector<double> sectionSizes(sectionCount);
// if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections):
int minSizeSum = 0;
for (int i=0; i<sectionCount; ++i)
minSizeSum += minSizes.at(i);
if (totalSize < minSizeSum)
{
// new stretch factors are minimum sizes and minimum sizes are set to zero:
for (int i=0; i<sectionCount; ++i)
{
stretchFactors[i] = minSizes.at(i);
minSizes[i] = 0;
}
}
QList<int> minimumLockedSections;
QList<int> unfinishedSections;
for (int i=0; i<sectionCount; ++i)
unfinishedSections.append(i);
double freeSize = totalSize;
int outerIterations = 0;
while (!unfinishedSections.isEmpty() && outerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
{
++outerIterations;
int innerIterations = 0;
while (!unfinishedSections.isEmpty() && innerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
{
++innerIterations;
// find section that hits its maximum next:
int nextId = -1;
double nextMax = 1e12;
for (int i=0; i<unfinishedSections.size(); ++i)
{
int secId = unfinishedSections.at(i);
double hitsMaxAt = (maxSizes.at(secId)-sectionSizes.at(secId))/stretchFactors.at(secId);
if (hitsMaxAt < nextMax)
{
nextMax = hitsMaxAt;
nextId = secId;
}
}
// check if that maximum is actually within the bounds of the total size (i.e. can we stretch all remaining sections so far that the found section
// actually hits its maximum, without exceeding the total size when we add up all sections)
double stretchFactorSum = 0;
for (int i=0; i<unfinishedSections.size(); ++i)
stretchFactorSum += stretchFactors.at(unfinishedSections.at(i));
double nextMaxLimit = freeSize/stretchFactorSum;
if (nextMax < nextMaxLimit) // next maximum is actually hit, move forward to that point and fix the size of that section
{
for (int i=0; i<unfinishedSections.size(); ++i)
{
sectionSizes[unfinishedSections.at(i)] += nextMax*stretchFactors.at(unfinishedSections.at(i)); // increment all sections
freeSize -= nextMax*stretchFactors.at(unfinishedSections.at(i));
}
unfinishedSections.removeOne(nextId); // exclude the section that is now at maximum from further changes
} else // next maximum isn't hit, just distribute rest of free space on remaining sections
{
for (int i=0; i<unfinishedSections.size(); ++i)
sectionSizes[unfinishedSections.at(i)] += nextMaxLimit*stretchFactors.at(unfinishedSections.at(i)); // increment all sections
unfinishedSections.clear();
}
}
if (innerIterations == sectionCount*2)
qDebug() << Q_FUNC_INFO << "Exceeded maximum expected inner iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
// now check whether the resulting section sizes violate minimum restrictions:
bool foundMinimumViolation = false;
for (int i=0; i<sectionSizes.size(); ++i)
{
if (minimumLockedSections.contains(i))
continue;
if (sectionSizes.at(i) < minSizes.at(i)) // section violates minimum
{
sectionSizes[i] = minSizes.at(i); // set it to minimum
foundMinimumViolation = true; // make sure we repeat the whole optimization process
minimumLockedSections.append(i);
}
}
if (foundMinimumViolation)
{
freeSize = totalSize;
for (int i=0; i<sectionCount; ++i)
{
if (!minimumLockedSections.contains(i)) // only put sections that haven't hit their minimum back into the pool
unfinishedSections.append(i);
else
freeSize -= sectionSizes.at(i); // remove size of minimum locked sections from available space in next round
}
// reset all section sizes to zero that are in unfinished sections (all others have been set to their minimum):
for (int i=0; i<unfinishedSections.size(); ++i)
sectionSizes[unfinishedSections.at(i)] = 0;
}
}
if (outerIterations == sectionCount*2)
qDebug() << Q_FUNC_INFO << "Exceeded maximum expected outer iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
QVector<int> result(sectionCount);
for (int i=0; i<sectionCount; ++i)
result[i] = qRound(sectionSizes.at(i));
return result;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLayoutGrid
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLayoutGrid
\brief A layout that arranges child elements in a grid
Elements are laid out in a grid with configurable stretch factors (\ref setColumnStretchFactor,
\ref setRowStretchFactor) and spacing (\ref setColumnSpacing, \ref setRowSpacing).
Elements can be added to cells via \ref addElement. The grid is expanded if the specified row or
column doesn't exist yet. Whether a cell contains a valid layout element can be checked with \ref
hasElement, that element can be retrieved with \ref element. If rows and columns that only have
empty cells shall be removed, call \ref simplify. Removal of elements is either done by just
adding the element to a different layout or by using the QCPLayout interface \ref take or \ref
remove.
Row and column insertion can be performed with \ref insertRow and \ref insertColumn.
*/
/*!
Creates an instance of QCPLayoutGrid and sets default values.
*/
QCPLayoutGrid::QCPLayoutGrid() :
mColumnSpacing(5),
mRowSpacing(5)
{
}
QCPLayoutGrid::~QCPLayoutGrid()
{
// clear all child layout elements. This is important because only the specific layouts know how
// to handle removing elements (clear calls virtual removeAt method to do that).
clear();
}
/*!
Returns the element in the cell in \a row and \a column.
Returns 0 if either the row/column is invalid or if the cell is empty. In those cases, a qDebug
message is printed. To check whether a cell exists and isn't empty, use \ref hasElement.
\see addElement, hasElement
*/
QCPLayoutElement *QCPLayoutGrid::element(int row, int column) const
{
if (row >= 0 && row < mElements.size())
{
if (column >= 0 && column < mElements.first().size())
{
if (QCPLayoutElement *result = mElements.at(row).at(column))
return result;
else
qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column;
} else
qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column;
} else
qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column;
return 0;
}
/*!
Returns the number of rows in the layout.
\see columnCount
*/
int QCPLayoutGrid::rowCount() const
{
return mElements.size();
}
/*!
Returns the number of columns in the layout.
\see rowCount
*/
int QCPLayoutGrid::columnCount() const
{
if (mElements.size() > 0)
return mElements.first().size();
else
return 0;
}
/*!
Adds the \a element to cell with \a row and \a column. If \a element is already in a layout, it
is first removed from there. If \a row or \a column don't exist yet, the layout is expanded
accordingly.
Returns true if the element was added successfully, i.e. if the cell at \a row and \a column
didn't already have an element.
\see element, hasElement, take, remove
*/
bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element)
{
if (element)
{
if (!hasElement(row, column))
{
if (element->layout()) // remove from old layout first
element->layout()->take(element);
expandTo(row+1, column+1);
mElements[row][column] = element;
adoptElement(element);
return true;
} else
qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column;
} else
qDebug() << Q_FUNC_INFO << "Can't add null element to row/column:" << row << column;
return false;
}
/*!
Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't
empty.
\see element
*/
bool QCPLayoutGrid::hasElement(int row, int column)
{
if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount())
return mElements.at(row).at(column);
else
return false;
}
/*!
Sets the stretch \a factor of \a column.
Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
The default stretch factor of newly created rows/columns is 1.
\see setColumnStretchFactors, setRowStretchFactor
*/
void QCPLayoutGrid::setColumnStretchFactor(int column, double factor)
{
if (column >= 0 && column < columnCount())
{
if (factor > 0)
mColumnStretchFactors[column] = factor;
else
qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
} else
qDebug() << Q_FUNC_INFO << "Invalid column:" << column;
}
/*!
Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount.
Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
The default stretch factor of newly created rows/columns is 1.
\see setColumnStretchFactor, setRowStretchFactors
*/
void QCPLayoutGrid::setColumnStretchFactors(const QList<double> &factors)
{
if (factors.size() == mColumnStretchFactors.size())
{
mColumnStretchFactors = factors;
for (int i=0; i<mColumnStretchFactors.size(); ++i)
{
if (mColumnStretchFactors.at(i) <= 0)
{
qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mColumnStretchFactors.at(i);
mColumnStretchFactors[i] = 1;
}
}
} else
qDebug() << Q_FUNC_INFO << "Column count not equal to passed stretch factor count:" << factors;
}
/*!
Sets the stretch \a factor of \a row.
Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
The default stretch factor of newly created rows/columns is 1.
\see setColumnStretchFactors, setRowStretchFactor
*/
void QCPLayoutGrid::setRowStretchFactor(int row, double factor)
{
if (row >= 0 && row < rowCount())
{
if (factor > 0)
mRowStretchFactors[row] = factor;
else
qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
} else
qDebug() << Q_FUNC_INFO << "Invalid row:" << row;
}
/*!
Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount.
Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
The default stretch factor of newly created rows/columns is 1.
\see setRowStretchFactor, setColumnStretchFactors
*/
void QCPLayoutGrid::setRowStretchFactors(const QList<double> &factors)
{
if (factors.size() == mRowStretchFactors.size())
{
mRowStretchFactors = factors;
for (int i=0; i<mRowStretchFactors.size(); ++i)
{
if (mRowStretchFactors.at(i) <= 0)
{
qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mRowStretchFactors.at(i);
mRowStretchFactors[i] = 1;
}
}
} else
qDebug() << Q_FUNC_INFO << "Row count not equal to passed stretch factor count:" << factors;
}
/*!
Sets the gap that is left blank between columns to \a pixels.
\see setRowSpacing
*/
void QCPLayoutGrid::setColumnSpacing(int pixels)
{
mColumnSpacing = pixels;
}
/*!
Sets the gap that is left blank between rows to \a pixels.
\see setColumnSpacing
*/
void QCPLayoutGrid::setRowSpacing(int pixels)
{
mRowSpacing = pixels;
}
/*!
Expands the layout to have \a newRowCount rows and \a newColumnCount columns. So the last valid
row index will be \a newRowCount-1, the last valid column index will be \a newColumnCount-1.
If the current column/row count is already larger or equal to \a newColumnCount/\a newRowCount,
this function does nothing in that dimension.
Newly created cells are empty, new rows and columns have the stretch factor 1.
Note that upon a call to \ref addElement, the layout is expanded automatically to contain the
specified row and column, using this function.
\see simplify
*/
void QCPLayoutGrid::expandTo(int newRowCount, int newColumnCount)
{
// add rows as necessary:
while (rowCount() < newRowCount)
{
mElements.append(QList<QCPLayoutElement*>());
mRowStretchFactors.append(1);
}
// go through rows and expand columns as necessary:
int newColCount = qMax(columnCount(), newColumnCount);
for (int i=0; i<rowCount(); ++i)
{
while (mElements.at(i).size() < newColCount)
mElements[i].append(0);
}
while (mColumnStretchFactors.size() < newColCount)
mColumnStretchFactors.append(1);
}
/*!
Inserts a new row with empty cells at the row index \a newIndex. Valid values for \a newIndex
range from 0 (inserts a row at the top) to \a rowCount (appends a row at the bottom).
\see insertColumn
*/
void QCPLayoutGrid::insertRow(int newIndex)
{
if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
{
expandTo(1, 1);
return;
}
if (newIndex < 0)
newIndex = 0;
if (newIndex > rowCount())
newIndex = rowCount();
mRowStretchFactors.insert(newIndex, 1);
QList<QCPLayoutElement*> newRow;
for (int col=0; col<columnCount(); ++col)
newRow.append((QCPLayoutElement*)0);
mElements.insert(newIndex, newRow);
}
/*!
Inserts a new column with empty cells at the column index \a newIndex. Valid values for \a
newIndex range from 0 (inserts a row at the left) to \a rowCount (appends a row at the right).
\see insertRow
*/
void QCPLayoutGrid::insertColumn(int newIndex)
{
if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
{
expandTo(1, 1);
return;
}
if (newIndex < 0)
newIndex = 0;
if (newIndex > columnCount())
newIndex = columnCount();
mColumnStretchFactors.insert(newIndex, 1);
for (int row=0; row<rowCount(); ++row)
mElements[row].insert(newIndex, (QCPLayoutElement*)0);
}
/* inherits documentation from base class */
void QCPLayoutGrid::updateLayout()
{
QVector<int> minColWidths, minRowHeights, maxColWidths, maxRowHeights;
getMinimumRowColSizes(&minColWidths, &minRowHeights);
getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
int totalRowSpacing = (rowCount()-1) * mRowSpacing;
int totalColSpacing = (columnCount()-1) * mColumnSpacing;
QVector<int> colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing);
QVector<int> rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing);
// go through cells and set rects accordingly:
int yOffset = mRect.top();
for (int row=0; row<rowCount(); ++row)
{
if (row > 0)
yOffset += rowHeights.at(row-1)+mRowSpacing;
int xOffset = mRect.left();
for (int col=0; col<columnCount(); ++col)
{
if (col > 0)
xOffset += colWidths.at(col-1)+mColumnSpacing;
if (mElements.at(row).at(col))
mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row)));
}
}
}
/* inherits documentation from base class */
int QCPLayoutGrid::elementCount() const
{
return rowCount()*columnCount();
}
/* inherits documentation from base class */
QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const
{
if (index >= 0 && index < elementCount())
return mElements.at(index / columnCount()).at(index % columnCount());
else
return 0;
}
/* inherits documentation from base class */
QCPLayoutElement *QCPLayoutGrid::takeAt(int index)
{
if (QCPLayoutElement *el = elementAt(index))
{
releaseElement(el);
mElements[index / columnCount()][index % columnCount()] = 0;
return el;
} else
{
qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
return 0;
}
}
/* inherits documentation from base class */
bool QCPLayoutGrid::take(QCPLayoutElement *element)
{
if (element)
{
for (int i=0; i<elementCount(); ++i)
{
if (elementAt(i) == element)
{
takeAt(i);
return true;
}
}
qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
} else
qDebug() << Q_FUNC_INFO << "Can't take null element";
return false;
}
/* inherits documentation from base class */
QList<QCPLayoutElement*> QCPLayoutGrid::elements(bool recursive) const
{
QList<QCPLayoutElement*> result;
int colC = columnCount();
int rowC = rowCount();
#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
result.reserve(colC*rowC);
#endif
for (int row=0; row<rowC; ++row)
{
for (int col=0; col<colC; ++col)
{
result.append(mElements.at(row).at(col));
}
}
if (recursive)
{
int c = result.size();
for (int i=0; i<c; ++i)
{
if (result.at(i))
result << result.at(i)->elements(recursive);
}
}
return result;
}
/*!
Simplifies the layout by collapsing rows and columns which only contain empty cells.
*/
void QCPLayoutGrid::simplify()
{
// remove rows with only empty cells:
for (int row=rowCount()-1; row>=0; --row)
{
bool hasElements = false;
for (int col=0; col<columnCount(); ++col)
{
if (mElements.at(row).at(col))
{
hasElements = true;
break;
}
}
if (!hasElements)
{
mRowStretchFactors.removeAt(row);
mElements.removeAt(row);
if (mElements.isEmpty()) // removed last element, also remove stretch factor (wouldn't happen below because also columnCount changed to 0 now)
mColumnStretchFactors.clear();
}
}
// remove columns with only empty cells:
for (int col=columnCount()-1; col>=0; --col)
{
bool hasElements = false;
for (int row=0; row<rowCount(); ++row)
{
if (mElements.at(row).at(col))
{
hasElements = true;
break;
}
}
if (!hasElements)
{
mColumnStretchFactors.removeAt(col);
for (int row=0; row<rowCount(); ++row)
mElements[row].removeAt(col);
}
}
}
/* inherits documentation from base class */
QSize QCPLayoutGrid::minimumSizeHint() const
{
QVector<int> minColWidths, minRowHeights;
getMinimumRowColSizes(&minColWidths, &minRowHeights);
QSize result(0, 0);
for (int i=0; i<minColWidths.size(); ++i)
result.rwidth() += minColWidths.at(i);
for (int i=0; i<minRowHeights.size(); ++i)
result.rheight() += minRowHeights.at(i);
result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing + mMargins.left() + mMargins.right();
result.rheight() += qMax(0, rowCount()-1) * mRowSpacing + mMargins.top() + mMargins.bottom();
return result;
}
/* inherits documentation from base class */
QSize QCPLayoutGrid::maximumSizeHint() const
{
QVector<int> maxColWidths, maxRowHeights;
getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
QSize result(0, 0);
for (int i=0; i<maxColWidths.size(); ++i)
result.setWidth(qMin(result.width()+maxColWidths.at(i), QWIDGETSIZE_MAX));
for (int i=0; i<maxRowHeights.size(); ++i)
result.setHeight(qMin(result.height()+maxRowHeights.at(i), QWIDGETSIZE_MAX));
result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing + mMargins.left() + mMargins.right();
result.rheight() += qMax(0, rowCount()-1) * mRowSpacing + mMargins.top() + mMargins.bottom();
return result;
}
/*! \internal
Places the minimum column widths and row heights into \a minColWidths and \a minRowHeights
respectively.
The minimum height of a row is the largest minimum height of any element in that row. The minimum
width of a column is the largest minimum width of any element in that column.
This is a helper function for \ref updateLayout.
\see getMaximumRowColSizes
*/
void QCPLayoutGrid::getMinimumRowColSizes(QVector<int> *minColWidths, QVector<int> *minRowHeights) const
{
*minColWidths = QVector<int>(columnCount(), 0);
*minRowHeights = QVector<int>(rowCount(), 0);
for (int row=0; row<rowCount(); ++row)
{
for (int col=0; col<columnCount(); ++col)
{
if (mElements.at(row).at(col))
{
QSize minHint = mElements.at(row).at(col)->minimumSizeHint();
QSize min = mElements.at(row).at(col)->minimumSize();
QSize final(min.width() > 0 ? min.width() : minHint.width(), min.height() > 0 ? min.height() : minHint.height());
if (minColWidths->at(col) < final.width())
(*minColWidths)[col] = final.width();
if (minRowHeights->at(row) < final.height())
(*minRowHeights)[row] = final.height();
}
}
}
}
/*! \internal
Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights
respectively.
The maximum height of a row is the smallest maximum height of any element in that row. The
maximum width of a column is the smallest maximum width of any element in that column.
This is a helper function for \ref updateLayout.
\see getMinimumRowColSizes
*/
void QCPLayoutGrid::getMaximumRowColSizes(QVector<int> *maxColWidths, QVector<int> *maxRowHeights) const
{
*maxColWidths = QVector<int>(columnCount(), QWIDGETSIZE_MAX);
*maxRowHeights = QVector<int>(rowCount(), QWIDGETSIZE_MAX);
for (int row=0; row<rowCount(); ++row)
{
for (int col=0; col<columnCount(); ++col)
{
if (mElements.at(row).at(col))
{
QSize maxHint = mElements.at(row).at(col)->maximumSizeHint();
QSize max = mElements.at(row).at(col)->maximumSize();
QSize final(max.width() < QWIDGETSIZE_MAX ? max.width() : maxHint.width(), max.height() < QWIDGETSIZE_MAX ? max.height() : maxHint.height());
if (maxColWidths->at(col) > final.width())
(*maxColWidths)[col] = final.width();
if (maxRowHeights->at(row) > final.height())
(*maxRowHeights)[row] = final.height();
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLayoutInset
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLayoutInset
\brief A layout that places child elements aligned to the border or arbitrarily positioned
Elements are placed either aligned to the border or at arbitrary position in the area of the
layout. Which placement applies is controlled with the \ref InsetPlacement (\ref
setInsetPlacement).
Elements are added via \ref addElement(QCPLayoutElement *element, Qt::Alignment alignment) or
addElement(QCPLayoutElement *element, const QRectF &rect). If the first method is used, the inset
placement will default to \ref ipBorderAligned and the element will be aligned according to the
\a alignment parameter. The second method defaults to \ref ipFree and allows placing elements at
arbitrary position and size, defined by \a rect.
The alignment or rect can be set via \ref setInsetAlignment or \ref setInsetRect, respectively.
This is the layout that every QCPAxisRect has as \ref QCPAxisRect::insetLayout.
*/
/* start documentation of inline functions */
/*! \fn virtual void QCPLayoutInset::simplify()
The QCPInsetLayout does not need simplification since it can never have empty cells due to its
linear index structure. This method does nothing.
*/
/* end documentation of inline functions */
/*!
Creates an instance of QCPLayoutInset and sets default values.
*/
QCPLayoutInset::QCPLayoutInset()
{
}
QCPLayoutInset::~QCPLayoutInset()
{
// clear all child layout elements. This is important because only the specific layouts know how
// to handle removing elements (clear calls virtual removeAt method to do that).
clear();
}
/*!
Returns the placement type of the element with the specified \a index.
*/
QCPLayoutInset::InsetPlacement QCPLayoutInset::insetPlacement(int index) const
{
if (elementAt(index))
return mInsetPlacement.at(index);
else
{
qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
return ipFree;
}
}
/*!
Returns the alignment of the element with the specified \a index. The alignment only has a
meaning, if the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned.
*/
Qt::Alignment QCPLayoutInset::insetAlignment(int index) const
{
if (elementAt(index))
return mInsetAlignment.at(index);
else
{
qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
return 0;
}
}
/*!
Returns the rect of the element with the specified \a index. The rect only has a
meaning, if the inset placement (\ref setInsetPlacement) is \ref ipFree.
*/
QRectF QCPLayoutInset::insetRect(int index) const
{
if (elementAt(index))
return mInsetRect.at(index);
else
{
qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
return QRectF();
}
}
/*!
Sets the inset placement type of the element with the specified \a index to \a placement.
\see InsetPlacement
*/
void QCPLayoutInset::setInsetPlacement(int index, QCPLayoutInset::InsetPlacement placement)
{
if (elementAt(index))
mInsetPlacement[index] = placement;
else
qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
}
/*!
If the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned, this function
is used to set the alignment of the element with the specified \a index to \a alignment.
\a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
alignment flags will be ignored.
*/
void QCPLayoutInset::setInsetAlignment(int index, Qt::Alignment alignment)
{
if (elementAt(index))
mInsetAlignment[index] = alignment;
else
qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
}
/*!
If the inset placement (\ref setInsetPlacement) is \ref ipFree, this function is used to set the
position and size of the element with the specified \a index to \a rect.
\a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
corner of the layout, with 35% width and height of the parent layout.
Note that the minimum and maximum sizes of the embedded element (\ref
QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize) are enforced.
*/
void QCPLayoutInset::setInsetRect(int index, const QRectF &rect)
{
if (elementAt(index))
mInsetRect[index] = rect;
else
qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
}
/* inherits documentation from base class */
void QCPLayoutInset::updateLayout()
{
for (int i=0; i<mElements.size(); ++i)
{
QRect insetRect;
QSize finalMinSize, finalMaxSize;
QSize minSizeHint = mElements.at(i)->minimumSizeHint();
QSize maxSizeHint = mElements.at(i)->maximumSizeHint();
finalMinSize.setWidth(mElements.at(i)->minimumSize().width() > 0 ? mElements.at(i)->minimumSize().width() : minSizeHint.width());
finalMinSize.setHeight(mElements.at(i)->minimumSize().height() > 0 ? mElements.at(i)->minimumSize().height() : minSizeHint.height());
finalMaxSize.setWidth(mElements.at(i)->maximumSize().width() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().width() : maxSizeHint.width());
finalMaxSize.setHeight(mElements.at(i)->maximumSize().height() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().height() : maxSizeHint.height());
if (mInsetPlacement.at(i) == ipFree)
{
insetRect = QRect(rect().x()+rect().width()*mInsetRect.at(i).x(),
rect().y()+rect().height()*mInsetRect.at(i).y(),
rect().width()*mInsetRect.at(i).width(),
rect().height()*mInsetRect.at(i).height());
if (insetRect.size().width() < finalMinSize.width())
insetRect.setWidth(finalMinSize.width());
if (insetRect.size().height() < finalMinSize.height())
insetRect.setHeight(finalMinSize.height());
if (insetRect.size().width() > finalMaxSize.width())
insetRect.setWidth(finalMaxSize.width());
if (insetRect.size().height() > finalMaxSize.height())
insetRect.setHeight(finalMaxSize.height());
} else if (mInsetPlacement.at(i) == ipBorderAligned)
{
insetRect.setSize(finalMinSize);
Qt::Alignment al = mInsetAlignment.at(i);
if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x());
else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width());
else insetRect.moveLeft(rect().x()+rect().width()*0.5-finalMinSize.width()*0.5); // default to Qt::AlignHCenter
if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y());
else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height());
else insetRect.moveTop(rect().y()+rect().height()*0.5-finalMinSize.height()*0.5); // default to Qt::AlignVCenter
}
mElements.at(i)->setOuterRect(insetRect);
}
}
/* inherits documentation from base class */
int QCPLayoutInset::elementCount() const
{
return mElements.size();
}
/* inherits documentation from base class */
QCPLayoutElement *QCPLayoutInset::elementAt(int index) const
{
if (index >= 0 && index < mElements.size())
return mElements.at(index);
else
return 0;
}
/* inherits documentation from base class */
QCPLayoutElement *QCPLayoutInset::takeAt(int index)
{
if (QCPLayoutElement *el = elementAt(index))
{
releaseElement(el);
mElements.removeAt(index);
mInsetPlacement.removeAt(index);
mInsetAlignment.removeAt(index);
mInsetRect.removeAt(index);
return el;
} else
{
qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
return 0;
}
}
/* inherits documentation from base class */
bool QCPLayoutInset::take(QCPLayoutElement *element)
{
if (element)
{
for (int i=0; i<elementCount(); ++i)
{
if (elementAt(i) == element)
{
takeAt(i);
return true;
}
}
qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
} else
qDebug() << Q_FUNC_INFO << "Can't take null element";
return false;
}
/*!
The inset layout is sensitive to events only at areas where its (visible) child elements are
sensitive. If the selectTest method of any of the child elements returns a positive number for \a
pos, this method returns a value corresponding to 0.99 times the parent plot's selection
tolerance. The inset layout is not selectable itself by default. So if \a onlySelectable is true,
-1.0 is returned.
See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
*/
double QCPLayoutInset::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable)
return -1;
for (int i=0; i<mElements.size(); ++i)
{
// inset layout shall only return positive selectTest, if actually an inset object is at pos
// else it would block the entire underlying QCPAxisRect with its surface.
if (mElements.at(i)->realVisibility() && mElements.at(i)->selectTest(pos, onlySelectable) >= 0)
return mParentPlot->selectionTolerance()*0.99;
}
return -1;
}
/*!
Adds the specified \a element to the layout as an inset aligned at the border (\ref
setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a
alignment.
\a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
alignment flags will be ignored.
\see addElement(QCPLayoutElement *element, const QRectF &rect)
*/
void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment)
{
if (element)
{
if (element->layout()) // remove from old layout first
element->layout()->take(element);
mElements.append(element);
mInsetPlacement.append(ipBorderAligned);
mInsetAlignment.append(alignment);
mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4));
adoptElement(element);
} else
qDebug() << Q_FUNC_INFO << "Can't add null element";
}
/*!
Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref
setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a
rect.
\a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
corner of the layout, with 35% width and height of the parent layout.
\see addElement(QCPLayoutElement *element, Qt::Alignment alignment)
*/
void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect)
{
if (element)
{
if (element->layout()) // remove from old layout first
element->layout()->take(element);
mElements.append(element);
mInsetPlacement.append(ipFree);
mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop);
mInsetRect.append(rect);
adoptElement(element);
} else
qDebug() << Q_FUNC_INFO << "Can't add null element";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLineEnding
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLineEnding
\brief Handles the different ending decorations for line-like items
\image html QCPLineEnding.png "The various ending styles currently supported"
For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine
has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail.
The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can
be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of
the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item.
For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite
directions, e.g. "outward". This can be changed by \ref setInverted, which would make the
respective arrow point inward.
Note that due to the overloaded QCPLineEnding constructor, you may directly specify a
QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g.
\snippet documentation/doc-code-snippets/mainwindow.cpp qcplineending-sethead
*/
/*!
Creates a QCPLineEnding instance with default values (style \ref esNone).
*/
QCPLineEnding::QCPLineEnding() :
mStyle(esNone),
mWidth(8),
mLength(10),
mInverted(false)
{
}
/*!
Creates a QCPLineEnding instance with the specified values.
*/
QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) :
mStyle(style),
mWidth(width),
mLength(length),
mInverted(inverted)
{
}
/*!
Sets the style of the ending decoration.
*/
void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style)
{
mStyle = style;
}
/*!
Sets the width of the ending decoration, if the style supports it. On arrows, for example, the
width defines the size perpendicular to the arrow's pointing direction.
\see setLength
*/
void QCPLineEnding::setWidth(double width)
{
mWidth = width;
}
/*!
Sets the length of the ending decoration, if the style supports it. On arrows, for example, the
length defines the size in pointing direction.
\see setWidth
*/
void QCPLineEnding::setLength(double length)
{
mLength = length;
}
/*!
Sets whether the ending decoration shall be inverted. For example, an arrow decoration will point
inward when \a inverted is set to true.
Note that also the \a width direction is inverted. For symmetrical ending styles like arrows or
discs, this doesn't make a difference. However, asymmetric styles like \ref esHalfBar are
affected by it, which can be used to control to which side the half bar points to.
*/
void QCPLineEnding::setInverted(bool inverted)
{
mInverted = inverted;
}
/*! \internal
Returns the maximum pixel radius the ending decoration might cover, starting from the position
the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item).
This is relevant for clipping. Only omit painting of the decoration when the position where the
decoration is supposed to be drawn is farther away from the clipping rect than the returned
distance.
*/
double QCPLineEnding::boundingDistance() const
{
switch (mStyle)
{
case esNone:
return 0;
case esFlatArrow:
case esSpikeArrow:
case esLineArrow:
case esSkewedBar:
return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length
case esDisc:
case esSquare:
case esDiamond:
case esBar:
case esHalfBar:
return mWidth*1.42; // items that only have a width -> width*sqrt(2)
}
return 0;
}
/*!
Starting from the origin of this line ending (which is style specific), returns the length
covered by the line ending symbol, in backward direction.
For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if
both have the same \ref setLength value, because the spike arrow has an inward curved back, which
reduces the length along its center axis (the drawing origin for arrows is at the tip).
This function is used for precise, style specific placement of line endings, for example in
QCPAxes.
*/
double QCPLineEnding::realLength() const
{
switch (mStyle)
{
case esNone:
case esLineArrow:
case esSkewedBar:
case esBar:
case esHalfBar:
return 0;
case esFlatArrow:
return mLength;
case esDisc:
case esSquare:
case esDiamond:
return mWidth*0.5;
case esSpikeArrow:
return mLength*0.8;
}
return 0;
}
/*! \internal
Draws the line ending with the specified \a painter at the position \a pos. The direction of the
line ending is controlled with \a dir.
*/
void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, const QVector2D &dir) const
{
if (mStyle == esNone)
return;
QVector2D lengthVec(dir.normalized());
if (lengthVec.isNull())
lengthVec = QVector2D(1, 0);
QVector2D widthVec(-lengthVec.y(), lengthVec.x());
lengthVec *= (float)(mLength*(mInverted ? -1 : 1));
widthVec *= (float)(mWidth*0.5*(mInverted ? -1 : 1));
QPen penBackup = painter->pen();
QBrush brushBackup = painter->brush();
QPen miterPen = penBackup;
miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey
QBrush brush(painter->pen().color(), Qt::SolidPattern);
switch (mStyle)
{
case esNone: break;
case esFlatArrow:
{
QPointF points[3] = {pos.toPointF(),
(pos-lengthVec+widthVec).toPointF(),
(pos-lengthVec-widthVec).toPointF()
};
painter->setPen(miterPen);
painter->setBrush(brush);
painter->drawConvexPolygon(points, 3);
painter->setBrush(brushBackup);
painter->setPen(penBackup);
break;
}
case esSpikeArrow:
{
QPointF points[4] = {pos.toPointF(),
(pos-lengthVec+widthVec).toPointF(),
(pos-lengthVec*0.8f).toPointF(),
(pos-lengthVec-widthVec).toPointF()
};
painter->setPen(miterPen);
painter->setBrush(brush);
painter->drawConvexPolygon(points, 4);
painter->setBrush(brushBackup);
painter->setPen(penBackup);
break;
}
case esLineArrow:
{
QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(),
pos.toPointF(),
(pos-lengthVec-widthVec).toPointF()
};
painter->setPen(miterPen);
painter->drawPolyline(points, 3);
painter->setPen(penBackup);
break;
}
case esDisc:
{
painter->setBrush(brush);
painter->drawEllipse(pos.toPointF(), mWidth*0.5, mWidth*0.5);
painter->setBrush(brushBackup);
break;
}
case esSquare:
{
QVector2D widthVecPerp(-widthVec.y(), widthVec.x());
QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(),
(pos-widthVecPerp-widthVec).toPointF(),
(pos+widthVecPerp-widthVec).toPointF(),
(pos+widthVecPerp+widthVec).toPointF()
};
painter->setPen(miterPen);
painter->setBrush(brush);
painter->drawConvexPolygon(points, 4);
painter->setBrush(brushBackup);
painter->setPen(penBackup);
break;
}
case esDiamond:
{
QVector2D widthVecPerp(-widthVec.y(), widthVec.x());
QPointF points[4] = {(pos-widthVecPerp).toPointF(),
(pos-widthVec).toPointF(),
(pos+widthVecPerp).toPointF(),
(pos+widthVec).toPointF()
};
painter->setPen(miterPen);
painter->setBrush(brush);
painter->drawConvexPolygon(points, 4);
painter->setBrush(brushBackup);
painter->setPen(penBackup);
break;
}
case esBar:
{
painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF());
break;
}
case esHalfBar:
{
painter->drawLine((pos+widthVec).toPointF(), pos.toPointF());
break;
}
case esSkewedBar:
{
if (qFuzzyIsNull(painter->pen().widthF()) && !painter->modes().testFlag(QCPPainter::pmNonCosmetic))
{
// if drawing with cosmetic pen (perfectly thin stroke, happens only in vector exports), draw bar exactly on tip of line
painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)).toPointF(),
(pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)).toPointF());
} else
{
// if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to prevent line from sticking through bar slightly
painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF(),
(pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF());
}
break;
}
}
}
/*! \internal
\overload
Draws the line ending. The direction is controlled with the \a angle parameter in radians.
*/
void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, double angle) const
{
draw(painter, pos, QVector2D(qCos(angle), qSin(angle)));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPGrid
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPGrid
\brief Responsible for drawing the grid of a QCPAxis.
This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the
grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref
QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself.
The axis and grid drawing was split into two classes to allow them to be placed on different
layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid
in the background and the axes in the foreground, and any plottables/items in between. This
described situation is the default setup, see the QCPLayer documentation.
*/
/*!
Creates a QCPGrid instance and sets default values.
You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid.
*/
QCPGrid::QCPGrid(QCPAxis *parentAxis) :
QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis),
mParentAxis(parentAxis)
{
// warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called
setParent(parentAxis);
setPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine));
setSubGridVisible(false);
setAntialiased(false);
setAntialiasedSubGrid(false);
setAntialiasedZeroLine(false);
}
/*!
Sets whether grid lines at sub tick marks are drawn.
\see setSubGridPen
*/
void QCPGrid::setSubGridVisible(bool visible)
{
mSubGridVisible = visible;
}
/*!
Sets whether sub grid lines are drawn antialiased.
*/
void QCPGrid::setAntialiasedSubGrid(bool enabled)
{
mAntialiasedSubGrid = enabled;
}
/*!
Sets whether zero lines are drawn antialiased.
*/
void QCPGrid::setAntialiasedZeroLine(bool enabled)
{
mAntialiasedZeroLine = enabled;
}
/*!
Sets the pen with which (major) grid lines are drawn.
*/
void QCPGrid::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen with which sub grid lines are drawn.
*/
void QCPGrid::setSubGridPen(const QPen &pen)
{
mSubGridPen = pen;
}
/*!
Sets the pen with which zero lines are drawn.
Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid
lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen.
*/
void QCPGrid::setZeroLinePen(const QPen &pen)
{
mZeroLinePen = pen;
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing the major grid lines.
This is the antialiasing state the painter passed to the \ref draw method is in by default.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased
*/
void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid);
}
/*! \internal
Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning
over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen).
*/
void QCPGrid::draw(QCPPainter *painter)
{
if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
if (mSubGridVisible)
drawSubGridLines(painter);
drawGridLines(painter);
}
/*! \internal
Draws the main grid lines and possibly a zero line with the specified painter.
This is a helper function called by \ref draw.
*/
void QCPGrid::drawGridLines(QCPPainter *painter) const
{
if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
int lowTick = mParentAxis->mLowestVisibleTick;
int highTick = mParentAxis->mHighestVisibleTick;
double t; // helper variable, result of coordinate-to-pixel transforms
if (mParentAxis->orientation() == Qt::Horizontal)
{
// draw zeroline:
int zeroLineIndex = -1;
if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
{
applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
painter->setPen(mZeroLinePen);
double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero
for (int i=lowTick; i <= highTick; ++i)
{
if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
{
zeroLineIndex = i;
t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
break;
}
}
}
// draw grid lines:
applyDefaultAntialiasingHint(painter);
painter->setPen(mPen);
for (int i=lowTick; i <= highTick; ++i)
{
if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
}
} else
{
// draw zeroline:
int zeroLineIndex = -1;
if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
{
applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
painter->setPen(mZeroLinePen);
double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero
for (int i=lowTick; i <= highTick; ++i)
{
if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
{
zeroLineIndex = i;
t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
break;
}
}
}
// draw grid lines:
applyDefaultAntialiasingHint(painter);
painter->setPen(mPen);
for (int i=lowTick; i <= highTick; ++i)
{
if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
}
}
}
/*! \internal
Draws the sub grid lines with the specified painter.
This is a helper function called by \ref draw.
*/
void QCPGrid::drawSubGridLines(QCPPainter *painter) const
{
if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid);
double t; // helper variable, result of coordinate-to-pixel transforms
painter->setPen(mSubGridPen);
if (mParentAxis->orientation() == Qt::Horizontal)
{
for (int i=0; i<mParentAxis->mSubTickVector.size(); ++i)
{
t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // x
painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
}
} else
{
for (int i=0; i<mParentAxis->mSubTickVector.size(); ++i)
{
t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // y
painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAxis
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAxis
\brief Manages a single axis inside a QCustomPlot.
Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via
QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and
QCustomPlot::yAxis2 (right).
Axes are always part of an axis rect, see QCPAxisRect.
\image html AxisNamesOverview.png
<center>Naming convention of axis parts</center>
\n
\image html AxisRectSpacingOverview.png
<center>Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line
on the left represents the QCustomPlot widget border.</center>
*/
/* start of documentation of inline functions */
/*! \fn Qt::Orientation QCPAxis::orientation() const
Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced
from the axis type (left, top, right or bottom).
\see orientation(AxisType type)
*/
/*! \fn QCPGrid *QCPAxis::grid() const
Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the
grid is displayed.
*/
/*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type)
Returns the orientation of the specified axis type
\see orientation()
*/
/* end of documentation of inline functions */
/* start of documentation of signals */
/*! \fn void QCPAxis::ticksRequest()
This signal is emitted when \ref setAutoTicks is false and the axis is about to generate tick
labels for a replot.
Modifying the tick positions can be done with \ref setTickVector. If you also want to control the
tick labels, set \ref setAutoTickLabels to false and also provide the labels with \ref
setTickVectorLabels.
If you only want static ticks you probably don't need this signal, since you can just set the
tick vector (and possibly tick label vector) once. However, if you want to provide ticks (and
maybe labels) dynamically, e.g. depending on the current axis range, connect a slot to this
signal and set the vector/vectors there.
*/
/*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange)
This signal is emitted when the range of this axis has changed. You can connect it to the \ref
setRange slot of another axis to communicate the new range to the other axis, in order for it to
be synchronized.
You may also manipulate/correct the range with \ref setRange in a slot connected to this signal.
This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper
range shouldn't go beyond certain values. For example, the following slot would limit the x axis
to only positive ranges:
\code
if (newRange.lower < 0)
plot->xAxis->setRange(0, newRange.size());
\endcode
*/
/*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange)
\overload
Additionally to the new range, this signal also provides the previous range held by the axis as
\a oldRange.
*/
/*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType);
This signal is emitted when the scale type changes, by calls to \ref setScaleType
*/
/*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection)
This signal is emitted when the selection state of this axis has changed, either by user interaction
or by a direct call to \ref setSelectedParts.
*/
/*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts);
This signal is emitted when the selectability changes, by calls to \ref setSelectableParts
*/
/* end of documentation of signals */
/*!
Constructs an Axis instance of Type \a type for the axis rect \a parent.
Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create
them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however,
create them manually and then inject them also via \ref QCPAxisRect::addAxis.
*/
QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) :
QCPLayerable(parent->parentPlot(), QString(), parent),
// axis base:
mAxisType(type),
mAxisRect(parent),
mPadding(5),
mOrientation(orientation(type)),
mSelectableParts(spAxis | spTickLabels | spAxisLabel),
mSelectedParts(spNone),
mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
mSelectedBasePen(QPen(Qt::blue, 2)),
// axis label:
mLabel(),
mLabelFont(mParentPlot->font()),
mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
mLabelColor(Qt::black),
mSelectedLabelColor(Qt::blue),
// tick labels:
mTickLabels(true),
mAutoTickLabels(true),
mTickLabelType(ltNumber),
mTickLabelFont(mParentPlot->font()),
mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
mTickLabelColor(Qt::black),
mSelectedTickLabelColor(Qt::blue),
mDateTimeFormat(QLatin1String("hh:mm:ss\ndd.MM.yy")),
mDateTimeSpec(Qt::LocalTime),
mNumberPrecision(6),
mNumberFormatChar('g'),
mNumberBeautifulPowers(true),
// ticks and subticks:
mTicks(true),
mTickStep(1),
mSubTickCount(4),
mAutoTickCount(6),
mAutoTicks(true),
mAutoTickStep(true),
mAutoSubTicks(true),
mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
mSelectedTickPen(QPen(Qt::blue, 2)),
mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
mSelectedSubTickPen(QPen(Qt::blue, 2)),
// scale and range:
mRange(0, 5),
mRangeReversed(false),
mScaleType(stLinear),
mScaleLogBase(10),
mScaleLogBaseLogInv(1.0/qLn(mScaleLogBase)),
// internal members:
mGrid(new QCPGrid(this)),
mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())),
mLowestVisibleTick(0),
mHighestVisibleTick(-1),
mCachedMarginValid(false),
mCachedMargin(0)
{
setParent(parent);
mGrid->setVisible(false);
setAntialiased(false);
setLayer(mParentPlot->currentLayer()); // it's actually on that layer already, but we want it in front of the grid, so we place it on there again
if (type == atTop)
{
setTickLabelPadding(3);
setLabelPadding(6);
} else if (type == atRight)
{
setTickLabelPadding(7);
setLabelPadding(12);
} else if (type == atBottom)
{
setTickLabelPadding(3);
setLabelPadding(3);
} else if (type == atLeft)
{
setTickLabelPadding(5);
setLabelPadding(10);
}
}
QCPAxis::~QCPAxis()
{
delete mAxisPainter;
delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order
}
/* No documentation as it is a property getter */
int QCPAxis::tickLabelPadding() const
{
return mAxisPainter->tickLabelPadding;
}
/* No documentation as it is a property getter */
double QCPAxis::tickLabelRotation() const
{
return mAxisPainter->tickLabelRotation;
}
/* No documentation as it is a property getter */
QCPAxis::LabelSide QCPAxis::tickLabelSide() const
{
return mAxisPainter->tickLabelSide;
}
/* No documentation as it is a property getter */
QString QCPAxis::numberFormat() const
{
QString result;
result.append(mNumberFormatChar);
if (mNumberBeautifulPowers)
{
result.append(QLatin1Char('b'));
if (mAxisPainter->numberMultiplyCross)
result.append(QLatin1Char('c'));
}
return result;
}
/* No documentation as it is a property getter */
int QCPAxis::tickLengthIn() const
{
return mAxisPainter->tickLengthIn;
}
/* No documentation as it is a property getter */
int QCPAxis::tickLengthOut() const
{
return mAxisPainter->tickLengthOut;
}
/* No documentation as it is a property getter */
int QCPAxis::subTickLengthIn() const
{
return mAxisPainter->subTickLengthIn;
}
/* No documentation as it is a property getter */
int QCPAxis::subTickLengthOut() const
{
return mAxisPainter->subTickLengthOut;
}
/* No documentation as it is a property getter */
int QCPAxis::labelPadding() const
{
return mAxisPainter->labelPadding;
}
/* No documentation as it is a property getter */
int QCPAxis::offset() const
{
return mAxisPainter->offset;
}
/* No documentation as it is a property getter */
QCPLineEnding QCPAxis::lowerEnding() const
{
return mAxisPainter->lowerEnding;
}
/* No documentation as it is a property getter */
QCPLineEnding QCPAxis::upperEnding() const
{
return mAxisPainter->upperEnding;
}
/*!
Sets whether the axis uses a linear scale or a logarithmic scale. If \a type is set to \ref
stLogarithmic, the logarithm base can be set with \ref setScaleLogBase. In logarithmic axis
scaling, major tick marks appear at all powers of the logarithm base. Properties like tick step
(\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but less major
ticks, consider choosing a logarithm base of 100, 1000 or even higher.
If \a type is \ref stLogarithmic and the number format (\ref setNumberFormat) uses the 'b' option
(beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10
[superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]"
part). To only display the decimal power, set the number precision to zero with
\ref setNumberPrecision.
*/
void QCPAxis::setScaleType(QCPAxis::ScaleType type)
{
if (mScaleType != type)
{
mScaleType = type;
if (mScaleType == stLogarithmic)
setRange(mRange.sanitizedForLogScale());
mCachedMarginValid = false;
emit scaleTypeChanged(mScaleType);
}
}
/*!
If \ref setScaleType is set to \ref stLogarithmic, \a base will be the logarithm base of the
scaling. In logarithmic axis scaling, major tick marks appear at all powers of \a base.
Properties like tick step (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but
less major ticks, consider choosing \a base 100, 1000 or even higher.
*/
void QCPAxis::setScaleLogBase(double base)
{
if (base > 1)
{
mScaleLogBase = base;
mScaleLogBaseLogInv = 1.0/qLn(mScaleLogBase); // buffer for faster baseLog() calculation
mCachedMarginValid = false;
} else
qDebug() << Q_FUNC_INFO << "Invalid logarithmic scale base (must be greater 1):" << base;
}
/*!
Sets the range of the axis.
This slot may be connected with the \ref rangeChanged signal of another axis so this axis
is always synchronized with the other axis range, when it changes.
To invert the direction of an axis, use \ref setRangeReversed.
*/
void QCPAxis::setRange(const QCPRange &range)
{
if (range.lower == mRange.lower && range.upper == mRange.upper)
return;
if (!QCPRange::validRange(range)) return;
QCPRange oldRange = mRange;
if (mScaleType == stLogarithmic)
{
mRange = range.sanitizedForLogScale();
} else
{
mRange = range.sanitizedForLinScale();
}
mCachedMarginValid = false;
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
(When \ref QCustomPlot::setInteractions contains iSelectAxes.)
However, even when \a selectable is set to a value not allowing the selection of a specific part,
it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
directly.
\see SelectablePart, setSelectedParts
*/
void QCPAxis::setSelectableParts(const SelectableParts &selectable)
{
if (mSelectableParts != selectable)
{
mSelectableParts = selectable;
emit selectableChanged(mSelectableParts);
}
}
/*!
Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
is selected, it uses a different pen/font.
The entire selection mechanism for axes is handled automatically when \ref
QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
wish to change the selection state manually.
This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
\see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
*/
void QCPAxis::setSelectedParts(const SelectableParts &selected)
{
if (mSelectedParts != selected)
{
mSelectedParts = selected;
emit selectionChanged(mSelectedParts);
}
}
/*!
\overload
Sets the lower and upper bound of the axis range.
To invert the direction of an axis, use \ref setRangeReversed.
There is also a slot to set a range, see \ref setRange(const QCPRange &range).
*/
void QCPAxis::setRange(double lower, double upper)
{
if (lower == mRange.lower && upper == mRange.upper)
return;
if (!QCPRange::validRange(lower, upper)) return;
QCPRange oldRange = mRange;
mRange.lower = lower;
mRange.upper = upper;
if (mScaleType == stLogarithmic)
{
mRange = mRange.sanitizedForLogScale();
} else
{
mRange = mRange.sanitizedForLinScale();
}
mCachedMarginValid = false;
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
\overload
Sets the range of the axis.
The \a position coordinate indicates together with the \a alignment parameter, where the new
range will be positioned. \a size defines the size of the new axis range. \a alignment may be
Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
or center of the range to be aligned with \a position. Any other values of \a alignment will
default to Qt::AlignCenter.
*/
void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment)
{
if (alignment == Qt::AlignLeft)
setRange(position, position+size);
else if (alignment == Qt::AlignRight)
setRange(position-size, position);
else // alignment == Qt::AlignCenter
setRange(position-size/2.0, position+size/2.0);
}
/*!
Sets the lower bound of the axis range. The upper bound is not changed.
\see setRange
*/
void QCPAxis::setRangeLower(double lower)
{
if (mRange.lower == lower)
return;
QCPRange oldRange = mRange;
mRange.lower = lower;
if (mScaleType == stLogarithmic)
{
mRange = mRange.sanitizedForLogScale();
} else
{
mRange = mRange.sanitizedForLinScale();
}
mCachedMarginValid = false;
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Sets the upper bound of the axis range. The lower bound is not changed.
\see setRange
*/
void QCPAxis::setRangeUpper(double upper)
{
if (mRange.upper == upper)
return;
QCPRange oldRange = mRange;
mRange.upper = upper;
if (mScaleType == stLogarithmic)
{
mRange = mRange.sanitizedForLogScale();
} else
{
mRange = mRange.sanitizedForLinScale();
}
mCachedMarginValid = false;
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
direction of increasing values is inverted.
Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
of the \ref setRange interface will still reference the mathematically smaller number than the \a
upper part.
*/
void QCPAxis::setRangeReversed(bool reversed)
{
if (mRangeReversed != reversed)
{
mRangeReversed = reversed;
mCachedMarginValid = false;
}
}
/*!
Sets whether the tick positions should be calculated automatically (either from an automatically
generated tick step or a tick step provided manually via \ref setTickStep, see \ref setAutoTickStep).
If \a on is set to false, you must provide the tick positions manually via \ref setTickVector.
For these manual ticks you may let QCPAxis generate the appropriate labels automatically by
leaving \ref setAutoTickLabels set to true. If you also wish to control the displayed labels
manually, set \ref setAutoTickLabels to false and provide the label strings with \ref
setTickVectorLabels.
If you need dynamically calculated tick vectors (and possibly tick label vectors), set the
vectors in a slot connected to the \ref ticksRequest signal.
\see setAutoTickLabels, setAutoSubTicks, setAutoTickCount, setAutoTickStep
*/
void QCPAxis::setAutoTicks(bool on)
{
if (mAutoTicks != on)
{
mAutoTicks = on;
mCachedMarginValid = false;
}
}
/*!
When \ref setAutoTickStep is true, \a approximateCount determines how many ticks should be
generated in the visible range, approximately.
It's not guaranteed that this number of ticks is met exactly, but approximately within a
tolerance of about two.
Only values greater than zero are accepted as \a approximateCount.
\see setAutoTickStep, setAutoTicks, setAutoSubTicks
*/
void QCPAxis::setAutoTickCount(int approximateCount)
{
if (mAutoTickCount != approximateCount)
{
if (approximateCount > 0)
{
mAutoTickCount = approximateCount;
mCachedMarginValid = false;
} else
qDebug() << Q_FUNC_INFO << "approximateCount must be greater than zero:" << approximateCount;
}
}
/*!
Sets whether the tick labels are generated automatically. Depending on the tick label type (\ref
ltNumber or \ref ltDateTime), the labels will either show the coordinate as floating point
number (\ref setNumberFormat), or a date/time formatted according to \ref setDateTimeFormat.
If \a on is set to false, you should provide the tick labels via \ref setTickVectorLabels. This
is usually used in a combination with \ref setAutoTicks set to false for complete control over
tick positions and labels, e.g. when the ticks should be at multiples of pi and show "2pi", "3pi"
etc. as tick labels.
If you need dynamically calculated tick vectors (and possibly tick label vectors), set the
vectors in a slot connected to the \ref ticksRequest signal.
\see setAutoTicks
*/
void QCPAxis::setAutoTickLabels(bool on)
{
if (mAutoTickLabels != on)
{
mAutoTickLabels = on;
mCachedMarginValid = false;
}
}
/*!
Sets whether the tick step, i.e. the interval between two (major) ticks, is calculated
automatically. If \a on is set to true, the axis finds a tick step that is reasonable for human
readable plots.
The number of ticks the algorithm aims for within the visible range can be specified with \ref
setAutoTickCount.
If \a on is set to false, you may set the tick step manually with \ref setTickStep.
\see setAutoTicks, setAutoSubTicks, setAutoTickCount
*/
void QCPAxis::setAutoTickStep(bool on)
{
if (mAutoTickStep != on)
{
mAutoTickStep = on;
mCachedMarginValid = false;
}
}
/*!
Sets whether the number of sub ticks in one tick interval is determined automatically. This
works, as long as the tick step mantissa is a multiple of 0.5. When \ref setAutoTickStep is
enabled, this is always the case.
When \a on is set to false, you may set the sub tick count with \ref setSubTickCount manually.
\see setAutoTickCount, setAutoTicks, setAutoTickStep
*/
void QCPAxis::setAutoSubTicks(bool on)
{
if (mAutoSubTicks != on)
{
mAutoSubTicks = on;
mCachedMarginValid = false;
}
}
/*!
Sets whether tick marks are displayed.
Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
that, see \ref setTickLabels.
*/
void QCPAxis::setTicks(bool show)
{
if (mTicks != show)
{
mTicks = show;
mCachedMarginValid = false;
}
}
/*!
Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
*/
void QCPAxis::setTickLabels(bool show)
{
if (mTickLabels != show)
{
mTickLabels = show;
mCachedMarginValid = false;
}
}
/*!
Sets the distance between the axis base line (including any outward ticks) and the tick labels.
\see setLabelPadding, setPadding
*/
void QCPAxis::setTickLabelPadding(int padding)
{
if (mAxisPainter->tickLabelPadding != padding)
{
mAxisPainter->tickLabelPadding = padding;
mCachedMarginValid = false;
}
}
/*!
Sets whether the tick labels display numbers or dates/times.
If \a type is set to \ref ltNumber, the format specifications of \ref setNumberFormat apply.
If \a type is set to \ref ltDateTime, the format specifications of \ref setDateTimeFormat apply.
In QCustomPlot, date/time coordinates are <tt>double</tt> numbers representing the seconds since
1970-01-01T00:00:00 UTC. This format can be retrieved from QDateTime objects with the
QDateTime::toTime_t() function. Since this only gives a resolution of one second, there is also
the QDateTime::toMSecsSinceEpoch() function which returns the timespan described above in
milliseconds. Divide its return value by 1000.0 to get a value with the format needed for
date/time plotting, with a resolution of one millisecond.
Using the toMSecsSinceEpoch function allows dates that go back to 2nd January 4713 B.C.
(represented by a negative number), unlike the toTime_t function, which works with unsigned
integers and thus only goes back to 1st January 1970. So both for range and accuracy, use of
toMSecsSinceEpoch()/1000.0 should be preferred as key coordinate for date/time axes.
\see setTickLabels
*/
void QCPAxis::setTickLabelType(LabelType type)
{
if (mTickLabelType != type)
{
mTickLabelType = type;
mCachedMarginValid = false;
}
}
/*!
Sets the font of the tick labels.
\see setTickLabels, setTickLabelColor
*/
void QCPAxis::setTickLabelFont(const QFont &font)
{
if (font != mTickLabelFont)
{
mTickLabelFont = font;
mCachedMarginValid = false;
}
}
/*!
Sets the color of the tick labels.
\see setTickLabels, setTickLabelFont
*/
void QCPAxis::setTickLabelColor(const QColor &color)
{
if (color != mTickLabelColor)
{
mTickLabelColor = color;
mCachedMarginValid = false;
}
}
/*!
Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
from -90 to 90 degrees.
If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
other angles, the label is drawn with an offset such that it seems to point toward or away from
the tick mark.
*/
void QCPAxis::setTickLabelRotation(double degrees)
{
if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation))
{
mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0);
mCachedMarginValid = false;
}
}
/*!
Sets whether the tick labels (numbers) shall appear inside or outside the axis rect.
The usual and default setting is \ref lsOutside. Very compact plots sometimes require tick labels
to be inside the axis rect, to save space. If \a side is set to \ref lsInside, the tick labels
appear on the inside are additionally clipped to the axis rect.
*/
void QCPAxis::setTickLabelSide(LabelSide side)
{
mAxisPainter->tickLabelSide = side;
mCachedMarginValid = false;
}
/*!
Sets the format in which dates and times are displayed as tick labels, if \ref setTickLabelType is \ref ltDateTime.
for details about the \a format string, see the documentation of QDateTime::toString().
Newlines can be inserted with "\n".
\see setDateTimeSpec
*/
void QCPAxis::setDateTimeFormat(const QString &format)
{
if (mDateTimeFormat != format)
{
mDateTimeFormat = format;
mCachedMarginValid = false;
}
}
/*!
Sets the time spec that is used for the date time values when \ref setTickLabelType is \ref
ltDateTime.
The default value of QDateTime objects (and also QCustomPlot) is <tt>Qt::LocalTime</tt>. However,
if the date time values passed to QCustomPlot are given in the UTC spec, set \a
timeSpec to <tt>Qt::UTC</tt> to get the correct axis labels.
\see setDateTimeFormat
*/
void QCPAxis::setDateTimeSpec(const Qt::TimeSpec &timeSpec)
{
mDateTimeSpec = timeSpec;
}
/*!
Sets the number format for the numbers drawn as tick labels (if tick label type is \ref
ltNumber). This \a formatCode is an extended version of the format code used e.g. by
QString::number() and QLocale::toString(). For reference about that, see the "Argument Formats"
section in the detailed description of the QString class. \a formatCode is a string of one, two
or three characters. The first character is identical to the normal format code used by Qt. In
short, this means: 'e'/'E' scientific format, 'f' fixed format, 'g'/'G' scientific or fixed,
whichever is shorter.
The second and third characters are optional and specific to QCustomPlot:\n
If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g.
"5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for
"beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
[multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
cross and 183 (0xB7) for the dot.
If the scale type (\ref setScaleType) is \ref stLogarithmic and the \a formatCode uses the 'b'
option (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10
[superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]"
part). To only display the decimal power, set the number precision to zero with \ref
setNumberPrecision.
Examples for \a formatCode:
\li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
normal scientific format is used
\li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
beautifully typeset decimal powers and a dot as multiplication sign
\li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
multiplication sign
\li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
powers. Format code will be reduced to 'f'.
\li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
code will not be changed.
*/
void QCPAxis::setNumberFormat(const QString &formatCode)
{
if (formatCode.isEmpty())
{
qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
return;
}
mCachedMarginValid = false;
// interpret first char as number format char:
QString allowedFormatChars(QLatin1String("eEfgG"));
if (allowedFormatChars.contains(formatCode.at(0)))
{
mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
} else
{
qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
return;
}
if (formatCode.length() < 2)
{
mNumberBeautifulPowers = false;
mAxisPainter->numberMultiplyCross = false;
return;
}
// interpret second char as indicator for beautiful decimal powers:
if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
{
mNumberBeautifulPowers = true;
} else
{
qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
return;
}
if (formatCode.length() < 3)
{
mAxisPainter->numberMultiplyCross = false;
return;
}
// interpret third char as indicator for dot or cross multiplication symbol:
if (formatCode.at(2) == QLatin1Char('c'))
{
mAxisPainter->numberMultiplyCross = true;
} else if (formatCode.at(2) == QLatin1Char('d'))
{
mAxisPainter->numberMultiplyCross = false;
} else
{
qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
return;
}
}
/*!
Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
for details. The effect of precisions are most notably for number Formats starting with 'e', see
\ref setNumberFormat
If the scale type (\ref setScaleType) is \ref stLogarithmic and the number format (\ref
setNumberFormat) uses the 'b' format code (beautifully typeset decimal powers), the display
usually is "1 [multiplication sign] 10 [superscript] n", which looks unnatural for logarithmic
scaling (the redundant "1 [multiplication sign]" part). To only display the decimal power "10
[superscript] n", set \a precision to zero.
*/
void QCPAxis::setNumberPrecision(int precision)
{
if (mNumberPrecision != precision)
{
mNumberPrecision = precision;
mCachedMarginValid = false;
}
}
/*!
If \ref setAutoTickStep is set to false, use this function to set the tick step manually.
The tick step is the interval between (major) ticks, in plot coordinates.
\see setSubTickCount
*/
void QCPAxis::setTickStep(double step)
{
if (mTickStep != step)
{
mTickStep = step;
mCachedMarginValid = false;
}
}
/*!
If you want full control over what ticks (and possibly labels) the axes show, this function is
used to set the coordinates at which ticks will appear.\ref setAutoTicks must be disabled, else
the provided tick vector will be overwritten with automatically generated tick coordinates upon
replot. The labels of the ticks can be generated automatically when \ref setAutoTickLabels is
left enabled. If it is disabled, you can set the labels manually with \ref setTickVectorLabels.
\a vec is a vector containing the positions of the ticks, in plot coordinates.
\warning \a vec must be sorted in ascending order, no additional checks are made to ensure this.
\see setTickVectorLabels
*/
void QCPAxis::setTickVector(const QVector<double> &vec)
{
// don't check whether mTickVector != vec here, because it takes longer than we would save
mTickVector = vec;
mCachedMarginValid = false;
}
/*!
If you want full control over what ticks and labels the axes show, this function is used to set a
number of QStrings that will be displayed at the tick positions which you need to provide with
\ref setTickVector. These two vectors should have the same size. (Note that you need to disable
\ref setAutoTicks and \ref setAutoTickLabels first.)
\a vec is a vector containing the labels of the ticks. The entries correspond to the respective
indices in the tick vector, passed via \ref setTickVector.
\see setTickVector
*/
void QCPAxis::setTickVectorLabels(const QVector<QString> &vec)
{
// don't check whether mTickVectorLabels != vec here, because it takes longer than we would save
mTickVectorLabels = vec;
mCachedMarginValid = false;
}
/*!
Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
zero, the tick labels and axis label will increase their distance to the axis accordingly, so
they won't collide with the ticks.
\see setSubTickLength, setTickLengthIn, setTickLengthOut
*/
void QCPAxis::setTickLength(int inside, int outside)
{
setTickLengthIn(inside);
setTickLengthOut(outside);
}
/*!
Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
inside the plot.
\see setTickLengthOut, setTickLength, setSubTickLength
*/
void QCPAxis::setTickLengthIn(int inside)
{
if (mAxisPainter->tickLengthIn != inside)
{
mAxisPainter->tickLengthIn = inside;
}
}
/*!
Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
outside the plot. If \a outside is greater than zero, the tick labels and axis label will
increase their distance to the axis accordingly, so they won't collide with the ticks.
\see setTickLengthIn, setTickLength, setSubTickLength
*/
void QCPAxis::setTickLengthOut(int outside)
{
if (mAxisPainter->tickLengthOut != outside)
{
mAxisPainter->tickLengthOut = outside;
mCachedMarginValid = false; // only outside tick length can change margin
}
}
/*!
Sets the number of sub ticks in one (major) tick step. A sub tick count of three for example,
divides the tick intervals in four sub intervals.
By default, the number of sub ticks is chosen automatically in a reasonable manner as long as the
mantissa of the tick step is a multiple of 0.5. When \ref setAutoTickStep is enabled, this is
always the case.
If you want to disable automatic sub tick count and use this function to set the count manually,
see \ref setAutoSubTicks.
*/
void QCPAxis::setSubTickCount(int count)
{
mSubTickCount = count;
}
/*!
Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
than zero, the tick labels and axis label will increase their distance to the axis accordingly,
so they won't collide with the ticks.
\see setTickLength, setSubTickLengthIn, setSubTickLengthOut
*/
void QCPAxis::setSubTickLength(int inside, int outside)
{
setSubTickLengthIn(inside);
setSubTickLengthOut(outside);
}
/*!
Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
the plot.
\see setSubTickLengthOut, setSubTickLength, setTickLength
*/
void QCPAxis::setSubTickLengthIn(int inside)
{
if (mAxisPainter->subTickLengthIn != inside)
{
mAxisPainter->subTickLengthIn = inside;
}
}
/*!
Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
outside the plot. If \a outside is greater than zero, the tick labels will increase their
distance to the axis accordingly, so they won't collide with the ticks.
\see setSubTickLengthIn, setSubTickLength, setTickLength
*/
void QCPAxis::setSubTickLengthOut(int outside)
{
if (mAxisPainter->subTickLengthOut != outside)
{
mAxisPainter->subTickLengthOut = outside;
mCachedMarginValid = false; // only outside tick length can change margin
}
}
/*!
Sets the pen, the axis base line is drawn with.
\see setTickPen, setSubTickPen
*/
void QCPAxis::setBasePen(const QPen &pen)
{
mBasePen = pen;
}
/*!
Sets the pen, tick marks will be drawn with.
\see setTickLength, setBasePen
*/
void QCPAxis::setTickPen(const QPen &pen)
{
mTickPen = pen;
}
/*!
Sets the pen, subtick marks will be drawn with.
\see setSubTickCount, setSubTickLength, setBasePen
*/
void QCPAxis::setSubTickPen(const QPen &pen)
{
mSubTickPen = pen;
}
/*!
Sets the font of the axis label.
\see setLabelColor
*/
void QCPAxis::setLabelFont(const QFont &font)
{
if (mLabelFont != font)
{
mLabelFont = font;
mCachedMarginValid = false;
}
}
/*!
Sets the color of the axis label.
\see setLabelFont
*/
void QCPAxis::setLabelColor(const QColor &color)
{
mLabelColor = color;
}
/*!
Sets the text of the axis label that will be shown below/above or next to the axis, depending on
its orientation. To disable axis labels, pass an empty string as \a str.
*/
void QCPAxis::setLabel(const QString &str)
{
if (mLabel != str)
{
mLabel = str;
mCachedMarginValid = false;
}
}
/*!
Sets the distance between the tick labels and the axis label.
\see setTickLabelPadding, setPadding
*/
void QCPAxis::setLabelPadding(int padding)
{
if (mAxisPainter->labelPadding != padding)
{
mAxisPainter->labelPadding = padding;
mCachedMarginValid = false;
}
}
/*!
Sets the padding of the axis.
When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space,
that is left blank.
The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled.
\see setLabelPadding, setTickLabelPadding
*/
void QCPAxis::setPadding(int padding)
{
if (mPadding != padding)
{
mPadding = padding;
mCachedMarginValid = false;
}
}
/*!
Sets the offset the axis has to its axis rect side.
If an axis rect side has multiple axes and automatic margin calculation is enabled for that side,
only the offset of the inner most axis has meaning (even if it is set to be invisible). The
offset of the other, outer axes is controlled automatically, to place them at appropriate
positions.
*/
void QCPAxis::setOffset(int offset)
{
mAxisPainter->offset = offset;
}
/*!
Sets the font that is used for tick labels when they are selected.
\see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedTickLabelFont(const QFont &font)
{
if (font != mSelectedTickLabelFont)
{
mSelectedTickLabelFont = font;
// don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
}
}
/*!
Sets the font that is used for the axis label when it is selected.
\see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedLabelFont(const QFont &font)
{
mSelectedLabelFont = font;
// don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
}
/*!
Sets the color that is used for tick labels when they are selected.
\see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedTickLabelColor(const QColor &color)
{
if (color != mSelectedTickLabelColor)
{
mSelectedTickLabelColor = color;
}
}
/*!
Sets the color that is used for the axis label when it is selected.
\see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedLabelColor(const QColor &color)
{
mSelectedLabelColor = color;
}
/*!
Sets the pen that is used to draw the axis base line when selected.
\see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedBasePen(const QPen &pen)
{
mSelectedBasePen = pen;
}
/*!
Sets the pen that is used to draw the (major) ticks when selected.
\see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedTickPen(const QPen &pen)
{
mSelectedTickPen = pen;
}
/*!
Sets the pen that is used to draw the subticks when selected.
\see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedSubTickPen(const QPen &pen)
{
mSelectedSubTickPen = pen;
}
/*!
Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available
styles.
For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending.
Note that this meaning does not change when the axis range is reversed with \ref
setRangeReversed.
\see setUpperEnding
*/
void QCPAxis::setLowerEnding(const QCPLineEnding &ending)
{
mAxisPainter->lowerEnding = ending;
}
/*!
Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available
styles.
For horizontal axes, this method refers to the right ending, for vertical axes the top ending.
Note that this meaning does not change when the axis range is reversed with \ref
setRangeReversed.
\see setLowerEnding
*/
void QCPAxis::setUpperEnding(const QCPLineEnding &ending)
{
mAxisPainter->upperEnding = ending;
}
/*!
If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
bounds of the range. The range is simply moved by \a diff.
If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
*/
void QCPAxis::moveRange(double diff)
{
QCPRange oldRange = mRange;
if (mScaleType == stLinear)
{
mRange.lower += diff;
mRange.upper += diff;
} else // mScaleType == stLogarithmic
{
mRange.lower *= diff;
mRange.upper *= diff;
}
mCachedMarginValid = false;
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
around 1.0 will have moved symmetrically closer to 1.0).
*/
void QCPAxis::scaleRange(double factor, double center)
{
QCPRange oldRange = mRange;
if (mScaleType == stLinear)
{
QCPRange newRange;
newRange.lower = (mRange.lower-center)*factor + center;
newRange.upper = (mRange.upper-center)*factor + center;
if (QCPRange::validRange(newRange))
mRange = newRange.sanitizedForLinScale();
} else // mScaleType == stLogarithmic
{
if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range
{
QCPRange newRange;
newRange.lower = qPow(mRange.lower/center, factor)*center;
newRange.upper = qPow(mRange.upper/center, factor)*center;
if (QCPRange::validRange(newRange))
mRange = newRange.sanitizedForLogScale();
} else
qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center;
}
mCachedMarginValid = false;
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will
be done around the center of the current axis range.
For example, if \a ratio is 1, this axis is the \a yAxis and \a otherAxis is \a xAxis, graphs
plotted with those axes will appear in a 1:1 aspect ratio, independent of the aspect ratio the
axis rect has.
This is an operation that changes the range of this axis once, it doesn't fix the scale ratio
indefinitely. Note that calling this function in the constructor of the QCustomPlot's parent
won't have the desired effect, since the widget dimensions aren't defined yet, and a resizeEvent
will follow.
*/
void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio)
{
int otherPixelSize, ownPixelSize;
if (otherAxis->orientation() == Qt::Horizontal)
otherPixelSize = otherAxis->axisRect()->width();
else
otherPixelSize = otherAxis->axisRect()->height();
if (orientation() == Qt::Horizontal)
ownPixelSize = axisRect()->width();
else
ownPixelSize = axisRect()->height();
double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/(double)otherPixelSize;
setRange(range().center(), newRangeSize, Qt::AlignCenter);
}
/*!
Changes the axis range such that all plottables associated with this axis are fully visible in
that dimension.
\see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
*/
void QCPAxis::rescale(bool onlyVisiblePlottables)
{
QList<QCPAbstractPlottable*> p = plottables();
QCPRange newRange;
bool haveRange = false;
for (int i=0; i<p.size(); ++i)
{
if (!p.at(i)->realVisibility() && onlyVisiblePlottables)
continue;
QCPRange plottableRange;
bool currentFoundRange;
QCPAbstractPlottable::SignDomain signDomain = QCPAbstractPlottable::sdBoth;
if (mScaleType == stLogarithmic)
signDomain = (mRange.upper < 0 ? QCPAbstractPlottable::sdNegative : QCPAbstractPlottable::sdPositive);
if (p.at(i)->keyAxis() == this)
plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain);
else
plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain);
if (currentFoundRange)
{
if (!haveRange)
newRange = plottableRange;
else
newRange.expand(plottableRange);
haveRange = true;
}
}
if (haveRange)
{
if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
{
double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
if (mScaleType == stLinear)
{
newRange.lower = center-mRange.size()/2.0;
newRange.upper = center+mRange.size()/2.0;
} else // mScaleType == stLogarithmic
{
newRange.lower = center/qSqrt(mRange.upper/mRange.lower);
newRange.upper = center*qSqrt(mRange.upper/mRange.lower);
}
}
setRange(newRange);
}
}
/*!
Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
*/
double QCPAxis::pixelToCoord(double value) const
{
if (orientation() == Qt::Horizontal)
{
if (mScaleType == stLinear)
{
if (!mRangeReversed)
return (value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.lower;
else
return -(value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.upper;
} else // mScaleType == stLogarithmic
{
if (!mRangeReversed)
return qPow(mRange.upper/mRange.lower, (value-mAxisRect->left())/(double)mAxisRect->width())*mRange.lower;
else
return qPow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/(double)mAxisRect->width())*mRange.upper;
}
} else // orientation() == Qt::Vertical
{
if (mScaleType == stLinear)
{
if (!mRangeReversed)
return (mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.lower;
else
return -(mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.upper;
} else // mScaleType == stLogarithmic
{
if (!mRangeReversed)
return qPow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/(double)mAxisRect->height())*mRange.lower;
else
return qPow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/(double)mAxisRect->height())*mRange.upper;
}
}
}
/*!
Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
*/
double QCPAxis::coordToPixel(double value) const
{
if (orientation() == Qt::Horizontal)
{
if (mScaleType == stLinear)
{
if (!mRangeReversed)
return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left();
else
return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left();
} else // mScaleType == stLogarithmic
{
if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range
return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200;
else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range
return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200;
else
{
if (!mRangeReversed)
return baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
else
return baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
}
}
} else // orientation() == Qt::Vertical
{
if (mScaleType == stLinear)
{
if (!mRangeReversed)
return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height();
else
return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height();
} else // mScaleType == stLogarithmic
{
if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range
return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200;
else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range
return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200;
else
{
if (!mRangeReversed)
return mAxisRect->bottom()-baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height();
else
return mAxisRect->bottom()-baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height();
}
}
}
}
/*!
Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
function does not change the current selection state of the axis.
If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
\see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
*/
QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const
{
if (!mVisible)
return spNone;
if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
return spAxis;
else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
return spTickLabels;
else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
return spAxisLabel;
else
return spNone;
}
/* inherits documentation from base class */
double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
if (!mParentPlot) return -1;
SelectablePart part = getPartAt(pos);
if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
return -1;
if (details)
details->setValue(part);
return mParentPlot->selectionTolerance()*0.99;
}
/*!
Returns a list of all the plottables that have this axis as key or value axis.
If you are only interested in plottables of type QCPGraph, see \ref graphs.
\see graphs, items
*/
QList<QCPAbstractPlottable*> QCPAxis::plottables() const
{
QList<QCPAbstractPlottable*> result;
if (!mParentPlot) return result;
for (int i=0; i<mParentPlot->mPlottables.size(); ++i)
{
if (mParentPlot->mPlottables.at(i)->keyAxis() == this ||mParentPlot->mPlottables.at(i)->valueAxis() == this)
result.append(mParentPlot->mPlottables.at(i));
}
return result;
}
/*!
Returns a list of all the graphs that have this axis as key or value axis.
\see plottables, items
*/
QList<QCPGraph*> QCPAxis::graphs() const
{
QList<QCPGraph*> result;
if (!mParentPlot) return result;
for (int i=0; i<mParentPlot->mGraphs.size(); ++i)
{
if (mParentPlot->mGraphs.at(i)->keyAxis() == this || mParentPlot->mGraphs.at(i)->valueAxis() == this)
result.append(mParentPlot->mGraphs.at(i));
}
return result;
}
/*!
Returns a list of all the items that are associated with this axis. An item is considered
associated with an axis if at least one of its positions uses the axis as key or value axis.
\see plottables, graphs
*/
QList<QCPAbstractItem*> QCPAxis::items() const
{
QList<QCPAbstractItem*> result;
if (!mParentPlot) return result;
for (int itemId=0; itemId<mParentPlot->mItems.size(); ++itemId)
{
QList<QCPItemPosition*> positions = mParentPlot->mItems.at(itemId)->positions();
for (int posId=0; posId<positions.size(); ++posId)
{
if (positions.at(posId)->keyAxis() == this || positions.at(posId)->valueAxis() == this)
{
result.append(mParentPlot->mItems.at(itemId));
break;
}
}
}
return result;
}
/*!
Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to
QCPAxis::atLeft, QCP::msRight to QCPAxis::atRight, etc.)
*/
QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side)
{
switch (side)
{
case QCP::msLeft: return atLeft;
case QCP::msRight: return atRight;
case QCP::msTop: return atTop;
case QCP::msBottom: return atBottom;
default: break;
}
qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << (int)side;
return atLeft;
}
/*!
Returns the axis type that describes the opposite axis of an axis with the specified \a type.
*/
QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type)
{
switch (type)
{
case atLeft: return atRight; break;
case atRight: return atLeft; break;
case atBottom: return atTop; break;
case atTop: return atBottom; break;
default: qDebug() << Q_FUNC_INFO << "invalid axis type"; return atLeft; break;
}
}
/*! \internal
This function is called to prepare the tick vector, sub tick vector and tick label vector. If
\ref setAutoTicks is set to true, appropriate tick values are determined automatically via \ref
generateAutoTicks. If it's set to false, the signal ticksRequest is emitted, which can be used to
provide external tick positions. Then the sub tick vectors and tick label vectors are created.
*/
void QCPAxis::setupTickVectors()
{
if (!mParentPlot) return;
if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return;
// fill tick vectors, either by auto generating or by notifying user to fill the vectors himself
if (mAutoTicks)
{
generateAutoTicks();
} else
{
emit ticksRequest();
}
visibleTickBounds(mLowestVisibleTick, mHighestVisibleTick);
if (mTickVector.isEmpty())
{
mSubTickVector.clear();
return;
}
// generate subticks between ticks:
mSubTickVector.resize((mTickVector.size()-1)*mSubTickCount);
if (mSubTickCount > 0)
{
double subTickStep = 0;
double subTickPosition = 0;
int subTickIndex = 0;
bool done = false;
int lowTick = mLowestVisibleTick > 0 ? mLowestVisibleTick-1 : mLowestVisibleTick;
int highTick = mHighestVisibleTick < mTickVector.size()-1 ? mHighestVisibleTick+1 : mHighestVisibleTick;
for (int i=lowTick+1; i<=highTick; ++i)
{
subTickStep = (mTickVector.at(i)-mTickVector.at(i-1))/(double)(mSubTickCount+1);
for (int k=1; k<=mSubTickCount; ++k)
{
subTickPosition = mTickVector.at(i-1) + k*subTickStep;
if (subTickPosition < mRange.lower)
continue;
if (subTickPosition > mRange.upper)
{
done = true;
break;
}
mSubTickVector[subTickIndex] = subTickPosition;
subTickIndex++;
}
if (done) break;
}
mSubTickVector.resize(subTickIndex);
}
// generate tick labels according to tick positions:
if (mAutoTickLabels)
{
int vecsize = mTickVector.size();
mTickVectorLabels.resize(vecsize);
if (mTickLabelType == ltNumber)
{
for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i)
mTickVectorLabels[i] = mParentPlot->locale().toString(mTickVector.at(i), mNumberFormatChar.toLatin1(), mNumberPrecision);
} else if (mTickLabelType == ltDateTime)
{
for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i)
{
#if QT_VERSION < QT_VERSION_CHECK(4, 7, 0) // use fromMSecsSinceEpoch function if available, to gain sub-second accuracy on tick labels (e.g. for format "hh:mm:ss:zzz")
mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromTime_t(mTickVector.at(i)).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
#else
mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromMSecsSinceEpoch(mTickVector.at(i)*1000).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
#endif
}
}
} else // mAutoTickLabels == false
{
if (mAutoTicks) // ticks generated automatically, but not ticklabels, so emit ticksRequest here for labels
{
emit ticksRequest();
}
// make sure provided tick label vector has correct (minimal) length:
if (mTickVectorLabels.size() < mTickVector.size())
mTickVectorLabels.resize(mTickVector.size());
}
}
/*! \internal
If \ref setAutoTicks is set to true, this function is called by \ref setupTickVectors to
generate reasonable tick positions (and subtick count). The algorithm tries to create
approximately <tt>mAutoTickCount</tt> ticks (set via \ref setAutoTickCount).
If the scale is logarithmic, \ref setAutoTickCount is ignored, and one tick is generated at every
power of the current logarithm base, set via \ref setScaleLogBase.
*/
void QCPAxis::generateAutoTicks()
{
if (mScaleType == stLinear)
{
if (mAutoTickStep)
{
// Generate tick positions according to linear scaling:
mTickStep = mRange.size()/(double)(mAutoTickCount+1e-10); // mAutoTickCount ticks on average, the small addition is to prevent jitter on exact integers
double magnitudeFactor = qPow(10.0, qFloor(qLn(mTickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc.
double tickStepMantissa = mTickStep/magnitudeFactor;
if (tickStepMantissa < 5)
{
// round digit after decimal point to 0.5
mTickStep = (int)(tickStepMantissa*2)/2.0*magnitudeFactor;
} else
{
// round to first digit in multiples of 2
mTickStep = (int)(tickStepMantissa/2.0)*2.0*magnitudeFactor;
}
}
if (mAutoSubTicks)
mSubTickCount = calculateAutoSubTickCount(mTickStep);
// Generate tick positions according to mTickStep:
qint64 firstStep = floor(mRange.lower/mTickStep); // do not use qFloor here, or we'll lose 64 bit precision
qint64 lastStep = ceil(mRange.upper/mTickStep); // do not use qCeil here, or we'll lose 64 bit precision
int tickcount = lastStep-firstStep+1;
if (tickcount < 0) tickcount = 0;
mTickVector.resize(tickcount);
for (int i=0; i<tickcount; ++i)
mTickVector[i] = (firstStep+i)*mTickStep;
} else // mScaleType == stLogarithmic
{
// Generate tick positions according to logbase scaling:
if (mRange.lower > 0 && mRange.upper > 0) // positive range
{
double lowerMag = basePow(qFloor(baseLog(mRange.lower)));
double currentMag = lowerMag;
mTickVector.clear();
mTickVector.append(currentMag);
while (currentMag < mRange.upper && currentMag > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
{
currentMag *= mScaleLogBase;
mTickVector.append(currentMag);
}
} else if (mRange.lower < 0 && mRange.upper < 0) // negative range
{
double lowerMag = -basePow(qCeil(baseLog(-mRange.lower)));
double currentMag = lowerMag;
mTickVector.clear();
mTickVector.append(currentMag);
while (currentMag < mRange.upper && currentMag < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
{
currentMag /= mScaleLogBase;
mTickVector.append(currentMag);
}
} else // invalid range for logarithmic scale, because lower and upper have different sign
{
mTickVector.clear();
qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << mRange.lower << "-" << mRange.upper;
}
}
}
/*! \internal
Called by generateAutoTicks when \ref setAutoSubTicks is set to true. Depending on the \a
tickStep between two major ticks on the axis, a different number of sub ticks is appropriate. For
Example taking 4 sub ticks for a \a tickStep of 1 makes more sense than taking 5 sub ticks,
because this corresponds to a sub tick step of 0.2, instead of the less intuitive 0.16667. Note
that a subtick count of 4 means dividing the major tick step into 5 sections.
This is implemented by a hand made lookup for integer tick steps as well as fractional tick steps
with a fractional part of (approximately) 0.5. If a tick step is different (i.e. has no
fractional part close to 0.5), the currently set sub tick count (\ref setSubTickCount) is
returned.
*/
int QCPAxis::calculateAutoSubTickCount(double tickStep) const
{
int result = mSubTickCount; // default to current setting, if no proper value can be found
// get mantissa of tickstep:
double magnitudeFactor = qPow(10.0, qFloor(qLn(tickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc.
double tickStepMantissa = tickStep/magnitudeFactor;
// separate integer and fractional part of mantissa:
double epsilon = 0.01;
double intPartf;
int intPart;
double fracPart = modf(tickStepMantissa, &intPartf);
intPart = intPartf;
// handle cases with (almost) integer mantissa:
if (fracPart < epsilon || 1.0-fracPart < epsilon)
{
if (1.0-fracPart < epsilon)
++intPart;
switch (intPart)
{
case 1: result = 4; break; // 1.0 -> 0.2 substep
case 2: result = 3; break; // 2.0 -> 0.5 substep
case 3: result = 2; break; // 3.0 -> 1.0 substep
case 4: result = 3; break; // 4.0 -> 1.0 substep
case 5: result = 4; break; // 5.0 -> 1.0 substep
case 6: result = 2; break; // 6.0 -> 2.0 substep
case 7: result = 6; break; // 7.0 -> 1.0 substep
case 8: result = 3; break; // 8.0 -> 2.0 substep
case 9: result = 2; break; // 9.0 -> 3.0 substep
}
} else
{
// handle cases with significantly fractional mantissa:
if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa
{
switch (intPart)
{
case 1: result = 2; break; // 1.5 -> 0.5 substep
case 2: result = 4; break; // 2.5 -> 0.5 substep
case 3: result = 4; break; // 3.5 -> 0.7 substep
case 4: result = 2; break; // 4.5 -> 1.5 substep
case 5: result = 4; break; // 5.5 -> 1.1 substep (won't occur with autoTickStep from here on)
case 6: result = 4; break; // 6.5 -> 1.3 substep
case 7: result = 2; break; // 7.5 -> 2.5 substep
case 8: result = 4; break; // 8.5 -> 1.7 substep
case 9: result = 4; break; // 9.5 -> 1.9 substep
}
}
// if mantissa fraction isnt 0.0 or 0.5, don't bother finding good sub tick marks, leave default
}
return result;
}
/* inherits documentation from base class */
void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
SelectablePart part = details.value<SelectablePart>();
if (mSelectableParts.testFlag(part))
{
SelectableParts selBefore = mSelectedParts;
setSelectedParts(additive ? mSelectedParts^part : part);
if (selectionStateChanged)
*selectionStateChanged = mSelectedParts != selBefore;
}
}
/* inherits documentation from base class */
void QCPAxis::deselectEvent(bool *selectionStateChanged)
{
SelectableParts selBefore = mSelectedParts;
setSelectedParts(mSelectedParts & ~mSelectableParts);
if (selectionStateChanged)
*selectionStateChanged = mSelectedParts != selBefore;
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing axis lines.
This is the antialiasing state the painter passed to the \ref draw method is in by default.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased
*/
void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
}
/*! \internal
Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance.
*/
void QCPAxis::draw(QCPPainter *painter)
{
const int lowTick = mLowestVisibleTick;
const int highTick = mHighestVisibleTick;
QVector<double> subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
tickPositions.reserve(highTick-lowTick+1);
tickLabels.reserve(highTick-lowTick+1);
subTickPositions.reserve(mSubTickVector.size());
if (mTicks)
{
for (int i=lowTick; i<=highTick; ++i)
{
tickPositions.append(coordToPixel(mTickVector.at(i)));
if (mTickLabels)
tickLabels.append(mTickVectorLabels.at(i));
}
if (mSubTickCount > 0)
{
const int subTickCount = mSubTickVector.size();
for (int i=0; i<subTickCount; ++i) // no need to check bounds because subticks are always only created inside current mRange
subTickPositions.append(coordToPixel(mSubTickVector.at(i)));
}
}
// transfer all properties of this axis to QCPAxisPainterPrivate which it needs to draw the axis.
// Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
mAxisPainter->type = mAxisType;
mAxisPainter->basePen = getBasePen();
mAxisPainter->labelFont = getLabelFont();
mAxisPainter->labelColor = getLabelColor();
mAxisPainter->label = mLabel;
mAxisPainter->substituteExponent = mAutoTickLabels && mNumberBeautifulPowers && mTickLabelType == ltNumber;
mAxisPainter->tickPen = getTickPen();
mAxisPainter->subTickPen = getSubTickPen();
mAxisPainter->tickLabelFont = getTickLabelFont();
mAxisPainter->tickLabelColor = getTickLabelColor();
mAxisPainter->axisRect = mAxisRect->rect();
mAxisPainter->viewportRect = mParentPlot->viewport();
mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic;
mAxisPainter->reversedEndings = mRangeReversed;
mAxisPainter->tickPositions = tickPositions;
mAxisPainter->tickLabels = tickLabels;
mAxisPainter->subTickPositions = subTickPositions;
mAxisPainter->draw(painter);
}
/*! \internal
Returns via \a lowIndex and \a highIndex, which ticks in the current tick vector are visible in
the current range. The return values are indices of the tick vector, not the positions of the
ticks themselves.
The actual use of this function is when an external tick vector is provided, since it might
exceed far beyond the currently displayed range, and would cause unnecessary calculations e.g. of
subticks.
If all ticks are outside the axis range, an inverted range is returned, i.e. highIndex will be
smaller than lowIndex. There is one case, where this function returns indices that are not really
visible in the current axis range: When the tick spacing is larger than the axis range size and
one tick is below the axis range and the next tick is already above the axis range. Because in
such cases it is usually desirable to know the tick pair, to draw proper subticks.
*/
void QCPAxis::visibleTickBounds(int &lowIndex, int &highIndex) const
{
bool lowFound = false;
bool highFound = false;
lowIndex = 0;
highIndex = -1;
for (int i=0; i < mTickVector.size(); ++i)
{
if (mTickVector.at(i) >= mRange.lower)
{
lowFound = true;
lowIndex = i;
break;
}
}
for (int i=mTickVector.size()-1; i >= 0; --i)
{
if (mTickVector.at(i) <= mRange.upper)
{
highFound = true;
highIndex = i;
break;
}
}
if (!lowFound && highFound)
lowIndex = highIndex+1;
else if (lowFound && !highFound)
highIndex = lowIndex-1;
}
/*! \internal
A log function with the base mScaleLogBase, used mostly for coordinate transforms in logarithmic
scales with arbitrary log base. Uses the buffered mScaleLogBaseLogInv for faster calculation.
This is set to <tt>1.0/qLn(mScaleLogBase)</tt> in \ref setScaleLogBase.
\see basePow, setScaleLogBase, setScaleType
*/
double QCPAxis::baseLog(double value) const
{
return qLn(value)*mScaleLogBaseLogInv;
}
/*! \internal
A power function with the base mScaleLogBase, used mostly for coordinate transforms in
logarithmic scales with arbitrary log base.
\see baseLog, setScaleLogBase, setScaleType
*/
double QCPAxis::basePow(double value) const
{
return qPow(mScaleLogBase, value);
}
/*! \internal
Returns the pen that is used to draw the axis base line. Depending on the selection state, this
is either mSelectedBasePen or mBasePen.
*/
QPen QCPAxis::getBasePen() const
{
return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
}
/*! \internal
Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
is either mSelectedTickPen or mTickPen.
*/
QPen QCPAxis::getTickPen() const
{
return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
}
/*! \internal
Returns the pen that is used to draw the subticks. Depending on the selection state, this
is either mSelectedSubTickPen or mSubTickPen.
*/
QPen QCPAxis::getSubTickPen() const
{
return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
}
/*! \internal
Returns the font that is used to draw the tick labels. Depending on the selection state, this
is either mSelectedTickLabelFont or mTickLabelFont.
*/
QFont QCPAxis::getTickLabelFont() const
{
return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
}
/*! \internal
Returns the font that is used to draw the axis label. Depending on the selection state, this
is either mSelectedLabelFont or mLabelFont.
*/
QFont QCPAxis::getLabelFont() const
{
return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
}
/*! \internal
Returns the color that is used to draw the tick labels. Depending on the selection state, this
is either mSelectedTickLabelColor or mTickLabelColor.
*/
QColor QCPAxis::getTickLabelColor() const
{
return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
}
/*! \internal
Returns the color that is used to draw the axis label. Depending on the selection state, this
is either mSelectedLabelColor or mLabelColor.
*/
QColor QCPAxis::getLabelColor() const
{
return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
}
/*! \internal
Returns the appropriate outward margin for this axis. It is needed if \ref
QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref
atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom
margin and so forth. For the calculation, this function goes through similar steps as \ref draw,
so changing one function likely requires the modification of the other one as well.
The margin consists of the outward tick length, tick label padding, tick label size, label
padding, label size, and padding.
The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc.
unchanged are very fast.
*/
int QCPAxis::calculateMargin()
{
if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis
return 0;
if (mCachedMarginValid)
return mCachedMargin;
// run through similar steps as QCPAxis::draw, and caluclate margin needed to fit axis and its labels
int margin = 0;
int lowTick, highTick;
visibleTickBounds(lowTick, highTick);
QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
tickPositions.reserve(highTick-lowTick+1);
tickLabels.reserve(highTick-lowTick+1);
if (mTicks)
{
for (int i=lowTick; i<=highTick; ++i)
{
tickPositions.append(coordToPixel(mTickVector.at(i)));
if (mTickLabels)
tickLabels.append(mTickVectorLabels.at(i));
}
}
// transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size.
// Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
mAxisPainter->type = mAxisType;
mAxisPainter->labelFont = getLabelFont();
mAxisPainter->label = mLabel;
mAxisPainter->tickLabelFont = mTickLabelFont;
mAxisPainter->axisRect = mAxisRect->rect();
mAxisPainter->viewportRect = mParentPlot->viewport();
mAxisPainter->tickPositions = tickPositions;
mAxisPainter->tickLabels = tickLabels;
margin += mAxisPainter->size();
margin += mPadding;
mCachedMargin = margin;
mCachedMarginValid = true;
return margin;
}
/* inherits documentation from base class */
QCP::Interaction QCPAxis::selectionCategory() const
{
return QCP::iSelectAxes;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAxisPainterPrivate
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAxisPainterPrivate
\internal
\brief (Private)
This is a private class and not part of the public QCustomPlot interface.
It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and
axis label. It also buffers the labels to reduce replot times. The parameters are configured by
directly accessing the public member variables.
*/
/*!
Constructs a QCPAxisPainterPrivate instance. Make sure to not create a new instance on every
redraw, to utilize the caching mechanisms.
*/
QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) :
type(QCPAxis::atLeft),
basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
lowerEnding(QCPLineEnding::esNone),
upperEnding(QCPLineEnding::esNone),
labelPadding(0),
tickLabelPadding(0),
tickLabelRotation(0),
tickLabelSide(QCPAxis::lsOutside),
substituteExponent(true),
numberMultiplyCross(false),
tickLengthIn(5),
tickLengthOut(0),
subTickLengthIn(2),
subTickLengthOut(0),
tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
offset(0),
abbreviateDecimalPowers(false),
reversedEndings(false),
mParentPlot(parentPlot),
mLabelCache(16) // cache at most 16 (tick) labels
{
}
QCPAxisPainterPrivate::~QCPAxisPainterPrivate()
{
}
/*! \internal
Draws the axis with the specified \a painter.
The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set
here, too.
*/
void QCPAxisPainterPrivate::draw(QCPPainter *painter)
{
QByteArray newHash = generateLabelParameterHash();
if (newHash != mLabelParameterHash)
{
mLabelCache.clear();
mLabelParameterHash = newHash;
}
QPoint origin;
switch (type)
{
case QCPAxis::atLeft: origin = axisRect.bottomLeft() +QPoint(-offset, 0); break;
case QCPAxis::atRight: origin = axisRect.bottomRight()+QPoint(+offset, 0); break;
case QCPAxis::atTop: origin = axisRect.topLeft() +QPoint(0, -offset); break;
case QCPAxis::atBottom: origin = axisRect.bottomLeft() +QPoint(0, +offset); break;
}
double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes)
switch (type)
{
case QCPAxis::atTop: yCor = -1; break;
case QCPAxis::atRight: xCor = 1; break;
default: break;
}
int margin = 0;
// draw baseline:
QLineF baseLine;
painter->setPen(basePen);
if (QCPAxis::orientation(type) == Qt::Horizontal)
baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(axisRect.width()+xCor, yCor));
else
baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -axisRect.height()+yCor));
if (reversedEndings)
baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later
painter->drawLine(baseLine);
// draw ticks:
if (!tickPositions.isEmpty())
{
painter->setPen(tickPen);
int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis)
if (QCPAxis::orientation(type) == Qt::Horizontal)
{
for (int i=0; i<tickPositions.size(); ++i)
painter->drawLine(QLineF(tickPositions.at(i)+xCor, origin.y()-tickLengthOut*tickDir+yCor, tickPositions.at(i)+xCor, origin.y()+tickLengthIn*tickDir+yCor));
} else
{
for (int i=0; i<tickPositions.size(); ++i)
painter->drawLine(QLineF(origin.x()-tickLengthOut*tickDir+xCor, tickPositions.at(i)+yCor, origin.x()+tickLengthIn*tickDir+xCor, tickPositions.at(i)+yCor));
}
}
// draw subticks:
if (!subTickPositions.isEmpty())
{
painter->setPen(subTickPen);
// direction of ticks ("inward" is right for left axis and left for right axis)
int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1;
if (QCPAxis::orientation(type) == Qt::Horizontal)
{
for (int i=0; i<subTickPositions.size(); ++i)
painter->drawLine(QLineF(subTickPositions.at(i)+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPositions.at(i)+xCor, origin.y()+subTickLengthIn*tickDir+yCor));
} else
{
for (int i=0; i<subTickPositions.size(); ++i)
painter->drawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPositions.at(i)+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPositions.at(i)+yCor));
}
}
margin += qMax(0, qMax(tickLengthOut, subTickLengthOut));
// draw axis base endings:
bool antialiasingBackup = painter->antialiasing();
painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't
painter->setBrush(QBrush(basePen.color()));
QVector2D baseLineVector(baseLine.dx(), baseLine.dy());
if (lowerEnding.style() != QCPLineEnding::esNone)
lowerEnding.draw(painter, QVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector);
if (upperEnding.style() != QCPLineEnding::esNone)
upperEnding.draw(painter, QVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector);
painter->setAntialiasing(antialiasingBackup);
// tick labels:
QRect oldClipRect;
if (tickLabelSide == QCPAxis::lsInside) // if using inside labels, clip them to the axis rect
{
oldClipRect = painter->clipRegion().boundingRect();
painter->setClipRect(axisRect);
}
QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label
if (!tickLabels.isEmpty())
{
if (tickLabelSide == QCPAxis::lsOutside)
margin += tickLabelPadding;
painter->setFont(tickLabelFont);
painter->setPen(QPen(tickLabelColor));
const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size());
int distanceToAxis = margin;
if (tickLabelSide == QCPAxis::lsInside)
distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding);
for (int i=0; i<maxLabelIndex; ++i)
placeTickLabel(painter, tickPositions.at(i), distanceToAxis, tickLabels.at(i), &tickLabelsSize);
if (tickLabelSide == QCPAxis::lsOutside)
margin += (QCPAxis::orientation(type) == Qt::Horizontal) ? tickLabelsSize.height() : tickLabelsSize.width();
}
if (tickLabelSide == QCPAxis::lsInside)
painter->setClipRect(oldClipRect);
// axis label:
QRect labelBounds;
if (!label.isEmpty())
{
margin += labelPadding;
painter->setFont(labelFont);
painter->setPen(QPen(labelColor));
labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label);
if (type == QCPAxis::atLeft)
{
QTransform oldTransform = painter->transform();
painter->translate((origin.x()-margin-labelBounds.height()), origin.y());
painter->rotate(-90);
painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
painter->setTransform(oldTransform);
}
else if (type == QCPAxis::atRight)
{
QTransform oldTransform = painter->transform();
painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-axisRect.height());
painter->rotate(90);
painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
painter->setTransform(oldTransform);
}
else if (type == QCPAxis::atTop)
painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
else if (type == QCPAxis::atBottom)
painter->drawText(origin.x(), origin.y()+margin, axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
}
// set selection boxes:
int selectionTolerance = 0;
if (mParentPlot)
selectionTolerance = mParentPlot->selectionTolerance();
else
qDebug() << Q_FUNC_INFO << "mParentPlot is null";
int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance);
int selAxisInSize = selectionTolerance;
int selTickLabelSize;
int selTickLabelOffset;
if (tickLabelSide == QCPAxis::lsOutside)
{
selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding;
} else
{
selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding);
}
int selLabelSize = labelBounds.height();
int selLabelOffset = qMax(tickLengthOut, subTickLengthOut)+(!tickLabels.isEmpty() && tickLabelSide == QCPAxis::lsOutside ? tickLabelPadding+selTickLabelSize : 0)+labelPadding;
if (type == QCPAxis::atLeft)
{
mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, axisRect.top(), origin.x()+selAxisInSize, axisRect.bottom());
mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, axisRect.top(), origin.x()-selTickLabelOffset, axisRect.bottom());
mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, axisRect.top(), origin.x()-selLabelOffset, axisRect.bottom());
} else if (type == QCPAxis::atRight)
{
mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, axisRect.top(), origin.x()+selAxisOutSize, axisRect.bottom());
mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, axisRect.top(), origin.x()+selTickLabelOffset, axisRect.bottom());
mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, axisRect.top(), origin.x()+selLabelOffset, axisRect.bottom());
} else if (type == QCPAxis::atTop)
{
mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisOutSize, axisRect.right(), origin.y()+selAxisInSize);
mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, axisRect.right(), origin.y()-selTickLabelOffset);
mLabelSelectionBox.setCoords(axisRect.left(), origin.y()-selLabelOffset-selLabelSize, axisRect.right(), origin.y()-selLabelOffset);
} else if (type == QCPAxis::atBottom)
{
mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisInSize, axisRect.right(), origin.y()+selAxisOutSize);
mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, axisRect.right(), origin.y()+selTickLabelOffset);
mLabelSelectionBox.setCoords(axisRect.left(), origin.y()+selLabelOffset+selLabelSize, axisRect.right(), origin.y()+selLabelOffset);
}
mAxisSelectionBox = mAxisSelectionBox.normalized();
mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized();
mLabelSelectionBox = mLabelSelectionBox.normalized();
// draw hitboxes for debug purposes:
//painter->setBrush(Qt::NoBrush);
//painter->drawRects(QVector<QRect>() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox);
}
/*! \internal
Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone
direction) needed to fit the axis.
*/
int QCPAxisPainterPrivate::size() const
{
int result = 0;
// get length of tick marks pointing outwards:
if (!tickPositions.isEmpty())
result += qMax(0, qMax(tickLengthOut, subTickLengthOut));
// calculate size of tick labels:
if (tickLabelSide == QCPAxis::lsOutside)
{
QSize tickLabelsSize(0, 0);
if (!tickLabels.isEmpty())
{
for (int i=0; i<tickLabels.size(); ++i)
getMaxTickLabelSize(tickLabelFont, tickLabels.at(i), &tickLabelsSize);
result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width();
result += tickLabelPadding;
}
}
// calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees):
if (!label.isEmpty())
{
QFontMetrics fontMetrics(labelFont);
QRect bounds;
bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label);
result += bounds.height() + labelPadding;
}
return result;
}
/*! \internal
Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This
method is called automatically in \ref draw, if any parameters have changed that invalidate the
cached labels, such as font, color, etc.
*/
void QCPAxisPainterPrivate::clearCache()
{
mLabelCache.clear();
}
/*! \internal
Returns a hash that allows uniquely identifying whether the label parameters have changed such
that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the
return value of this method hasn't changed since the last redraw, the respective label parameters
haven't changed and cached labels may be used.
*/
QByteArray QCPAxisPainterPrivate::generateLabelParameterHash() const
{
QByteArray result;
result.append(QByteArray::number(tickLabelRotation));
result.append(QByteArray::number((int)tickLabelSide));
result.append(QByteArray::number((int)substituteExponent));
result.append(QByteArray::number((int)numberMultiplyCross));
result.append(tickLabelColor.name().toLatin1()+QByteArray::number(tickLabelColor.alpha(), 16));
result.append(tickLabelFont.toString().toLatin1());
return result;
}
/*! \internal
Draws a single tick label with the provided \a painter, utilizing the internal label cache to
significantly speed up drawing of labels that were drawn in previous calls. The tick label is
always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in
pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence
for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate),
at which the label should be drawn.
In order to later draw the axis label in a place that doesn't overlap with the tick labels, the
largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref
drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a
tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently
holds.
The label is drawn with the font and pen that are currently set on the \a painter. To draw
superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref
getTickLabelData).
*/
void QCPAxisPainterPrivate::placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize)
{
// warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly!
if (text.isEmpty()) return;
QSize finalSize;
QPointF labelAnchor;
switch (type)
{
case QCPAxis::atLeft: labelAnchor = QPointF(axisRect.left()-distanceToAxis-offset, position); break;
case QCPAxis::atRight: labelAnchor = QPointF(axisRect.right()+distanceToAxis+offset, position); break;
case QCPAxis::atTop: labelAnchor = QPointF(position, axisRect.top()-distanceToAxis-offset); break;
case QCPAxis::atBottom: labelAnchor = QPointF(position, axisRect.bottom()+distanceToAxis+offset); break;
}
if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled
{
CachedLabel *cachedLabel = mLabelCache.take(text); // attempt to get label from cache
if (!cachedLabel) // no cached label existed, create it
{
cachedLabel = new CachedLabel;
TickLabelData labelData = getTickLabelData(painter->font(), text);
cachedLabel->offset = getTickLabelDrawOffset(labelData)+labelData.rotatedTotalBounds.topLeft();
cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
cachedLabel->pixmap.fill(Qt::transparent);
QCPPainter cachePainter(&cachedLabel->pixmap);
cachePainter.setPen(painter->pen());
drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData);
}
// if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
bool labelClippedByBorder = false;
if (tickLabelSide == QCPAxis::lsOutside)
{
if (QCPAxis::orientation(type) == Qt::Horizontal)
labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left();
else
labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top();
}
if (!labelClippedByBorder)
{
painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap);
finalSize = cachedLabel->pixmap.size();
}
mLabelCache.insert(text, cachedLabel); // return label to cache or insert for the first time if newly created
} else // label caching disabled, draw text directly on surface:
{
TickLabelData labelData = getTickLabelData(painter->font(), text);
QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData);
// if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
bool labelClippedByBorder = false;
if (tickLabelSide == QCPAxis::lsOutside)
{
if (QCPAxis::orientation(type) == Qt::Horizontal)
labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left();
else
labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top();
}
if (!labelClippedByBorder)
{
drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData);
finalSize = labelData.rotatedTotalBounds.size();
}
}
// expand passed tickLabelsSize if current tick label is larger:
if (finalSize.width() > tickLabelsSize->width())
tickLabelsSize->setWidth(finalSize.width());
if (finalSize.height() > tickLabelsSize->height())
tickLabelsSize->setHeight(finalSize.height());
}
/*! \internal
This is a \ref placeTickLabel helper function.
Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a
y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to
directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when
QCP::phCacheLabels plotting hint is not set.
*/
void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const
{
// backup painter settings that we're about to change:
QTransform oldTransform = painter->transform();
QFont oldFont = painter->font();
// transform painter to position/rotation:
painter->translate(x, y);
if (!qFuzzyIsNull(tickLabelRotation))
painter->rotate(tickLabelRotation);
// draw text:
if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used
{
painter->setFont(labelData.baseFont);
painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart);
painter->setFont(labelData.expFont);
painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart);
} else
{
painter->setFont(labelData.baseFont);
painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart);
}
// reset painter settings to what it was before:
painter->setTransform(oldTransform);
painter->setFont(oldFont);
}
/*! \internal
This is a \ref placeTickLabel helper function.
Transforms the passed \a text and \a font to a tickLabelData structure that can then be further
processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and
exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes.
*/
QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const
{
TickLabelData result;
// determine whether beautiful decimal powers should be used
bool useBeautifulPowers = false;
int ePos = -1; // first index of exponent part, text before that will be basePart, text until eLast will be expPart
int eLast = -1; // last index of exponent part, rest of text after this will be suffixPart
if (substituteExponent)
{
ePos = text.indexOf(QLatin1Char('e'));
if (ePos > 0 && text.at(ePos-1).isDigit())
{
eLast = ePos;
while (eLast+1 < text.size() && (text.at(eLast+1) == QLatin1Char('+') || text.at(eLast+1) == QLatin1Char('-') || text.at(eLast+1).isDigit()))
++eLast;
if (eLast > ePos) // only if also to right of 'e' is a digit/+/- interpret it as beautifiable power
useBeautifulPowers = true;
}
}
// calculate text bounding rects and do string preparation for beautiful decimal powers:
result.baseFont = font;
if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line
result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding
if (useBeautifulPowers)
{
// split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent:
result.basePart = text.left(ePos);
// in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base:
if (abbreviateDecimalPowers && result.basePart == QLatin1String("1"))
result.basePart = QLatin1String("10");
else
result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + QLatin1String("10");
result.expPart = text.mid(ePos+1);
// clip "+" and leading zeros off expPart:
while (result.expPart.length() > 2 && result.expPart.at(1) == QLatin1Char('0')) // length > 2 so we leave one zero when numberFormatChar is 'e'
result.expPart.remove(1, 1);
if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+'))
result.expPart.remove(0, 1);
// prepare smaller font for exponent:
result.expFont = font;
if (result.expFont.pointSize() > 0)
result.expFont.setPointSize(result.expFont.pointSize()*0.75);
else
result.expFont.setPixelSize(result.expFont.pixelSize()*0.75);
// calculate bounding rects of base part, exponent part and total one:
result.baseBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart);
result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart);
result.totalBounds = result.baseBounds.adjusted(0, 0, result.expBounds.width()+2, 0); // +2 consists of the 1 pixel spacing between base and exponent (see drawTickLabel) and an extra pixel to include AA
} else // useBeautifulPowers == false
{
result.basePart = text;
result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart);
}
result.totalBounds.moveTopLeft(QPoint(0, 0)); // want bounding box aligned top left at origin, independent of how it was created, to make further processing simpler
// calculate possibly different bounding rect after rotation:
result.rotatedTotalBounds = result.totalBounds;
if (!qFuzzyIsNull(tickLabelRotation))
{
QTransform transform;
transform.rotate(tickLabelRotation);
result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds);
}
return result;
}
/*! \internal
This is a \ref placeTickLabel helper function.
Calculates the offset at which the top left corner of the specified tick label shall be drawn.
The offset is relative to a point right next to the tick the label belongs to.
This function is thus responsible for e.g. centering tick labels under ticks and positioning them
appropriately when they are rotated.
*/
QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const
{
/*
calculate label offset from base point at tick (non-trivial, for best visual appearance): short
explanation for bottom axis: The anchor, i.e. the point in the label that is placed
horizontally under the corresponding tick is always on the label side that is closer to the
axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height
is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text
will be centered under the tick (i.e. displaced horizontally by half its height). At the same
time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick
labels.
*/
bool doRotation = !qFuzzyIsNull(tickLabelRotation);
bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes.
double radians = tickLabelRotation/180.0*M_PI;
int x=0, y=0;
if ((type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsInside)) // Anchor at right side of tick label
{
if (doRotation)
{
if (tickLabelRotation > 0)
{
x = -qCos(radians)*labelData.totalBounds.width();
y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0;
} else
{
x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height();
y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0;
}
} else
{
x = -labelData.totalBounds.width();
y = -labelData.totalBounds.height()/2.0;
}
} else if ((type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsInside)) // Anchor at left side of tick label
{
if (doRotation)
{
if (tickLabelRotation > 0)
{
x = +qSin(radians)*labelData.totalBounds.height();
y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0;
} else
{
x = 0;
y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0;
}
} else
{
x = 0;
y = -labelData.totalBounds.height()/2.0;
}
} else if ((type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsInside)) // Anchor at bottom side of tick label
{
if (doRotation)
{
if (tickLabelRotation > 0)
{
x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0;
y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height();
} else
{
x = -qSin(-radians)*labelData.totalBounds.height()/2.0;
y = -qCos(-radians)*labelData.totalBounds.height();
}
} else
{
x = -labelData.totalBounds.width()/2.0;
y = -labelData.totalBounds.height();
}
} else if ((type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsInside)) // Anchor at top side of tick label
{
if (doRotation)
{
if (tickLabelRotation > 0)
{
x = +qSin(radians)*labelData.totalBounds.height()/2.0;
y = 0;
} else
{
x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0;
y = +qSin(-radians)*labelData.totalBounds.width();
}
} else
{
x = -labelData.totalBounds.width()/2.0;
y = 0;
}
}
return QPointF(x, y);
}
/*! \internal
Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label
to be drawn, depending on number format etc. Since only the largest tick label is wanted for the
margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a
smaller width/height.
*/
void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const
{
// note: this function must return the same tick label sizes as the placeTickLabel function.
QSize finalSize;
if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label
{
const CachedLabel *cachedLabel = mLabelCache.object(text);
finalSize = cachedLabel->pixmap.size();
} else // label caching disabled or no label with this text cached:
{
TickLabelData labelData = getTickLabelData(font, text);
finalSize = labelData.rotatedTotalBounds.size();
}
// expand passed tickLabelsSize if current tick label is larger:
if (finalSize.width() > tickLabelsSize->width())
tickLabelsSize->setWidth(finalSize.width());
if (finalSize.height() > tickLabelsSize->height())
tickLabelsSize->setHeight(finalSize.height());
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAbstractPlottable
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAbstractPlottable
\brief The abstract base class for all data representing objects in a plot.
It defines a very basic interface like name, pen, brush, visibility etc. Since this class is
abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to
create new ways of displaying data (see "Creating own plottables" below).
All further specifics are in the subclasses, for example:
\li A normal graph with possibly a line, scatter points and error bars: \ref QCPGraph
(typically created with \ref QCustomPlot::addGraph)
\li A parametric curve: \ref QCPCurve
\li A bar chart: \ref QCPBars
\li A statistical box plot: \ref QCPStatisticalBox
\li A color encoded two-dimensional map: \ref QCPColorMap
\li An OHLC/Candlestick chart: \ref QCPFinancial
\section plottables-subclassing Creating own plottables
To create an own plottable, you implement a subclass of QCPAbstractPlottable. These are the pure
virtual functions, you must implement:
\li \ref clearData
\li \ref selectTest
\li \ref draw
\li \ref drawLegendIcon
\li \ref getKeyRange
\li \ref getValueRange
See the documentation of those functions for what they need to do.
For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot
coordinates to pixel coordinates. This function is quite convenient, because it takes the
orientation of the key and value axes into account for you (x and y are swapped when the key axis
is vertical and the value axis horizontal). If you are worried about performance (i.e. you need
to translate many points in a loop like QCPGraph), you can directly use \ref
QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis
yourself.
Here are some important members you inherit from QCPAbstractPlottable:
<table>
<tr>
<td>QCustomPlot *\b mParentPlot</td>
<td>A pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the constructor.</td>
</tr><tr>
<td>QString \b mName</td>
<td>The name of the plottable.</td>
</tr><tr>
<td>QPen \b mPen</td>
<td>The generic pen of the plottable. You should use this pen for the most prominent data representing lines in the plottable (e.g QCPGraph uses this pen for its graph lines and scatters)</td>
</tr><tr>
<td>QPen \b mSelectedPen</td>
<td>The generic pen that should be used when the plottable is selected (hint: \ref mainPen gives you the right pen, depending on selection state).</td>
</tr><tr>
<td>QBrush \b mBrush</td>
<td>The generic brush of the plottable. You should use this brush for the most prominent fillable structures in the plottable (e.g. QCPGraph uses this brush to control filling under the graph)</td>
</tr><tr>
<td>QBrush \b mSelectedBrush</td>
<td>The generic brush that should be used when the plottable is selected (hint: \ref mainBrush gives you the right brush, depending on selection state).</td>
</tr><tr>
<td>QPointer<QCPAxis>\b mKeyAxis, \b mValueAxis</td>
<td>The key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel functions to translate coordinates to pixels in either the key or value dimension.
Make sure to check whether the pointer is null before using it. If one of the axes is null, don't draw the plottable.</td>
</tr><tr>
<td>bool \b mSelected</td>
<td>indicates whether the plottable is selected or not.</td>
</tr>
</table>
*/
/* start of documentation of pure virtual functions */
/*! \fn void QCPAbstractPlottable::clearData() = 0
Clears all data in the plottable.
*/
/*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0
\internal
called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation
of this plottable inside \a rect, next to the plottable name.
The passed \a painter has its cliprect set to \a rect, so painting outside of \a rect won't
appear outside the legend icon border.
*/
/*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, SignDomain inSignDomain) const = 0
\internal
called by rescaleAxes functions to get the full data key bounds. For logarithmic plots, one can
set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the
returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain
to \ref sdNegative and all positive points will be ignored for range calculation. For no
restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output
parameter that indicates whether a range could be found or not. If this is false, you shouldn't
use the returned range (e.g. no points in data).
Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
this function may have size zero, which wouldn't count as a valid range.
\see rescaleAxes, getValueRange
*/
/*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, SignDomain inSignDomain) const = 0
\internal
called by rescaleAxes functions to get the full data value bounds. For logarithmic plots, one can
set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the
returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain
to \ref sdNegative and all positive points will be ignored for range calculation. For no
restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output
parameter that indicates whether a range could be found or not. If this is false, you shouldn't
use the returned range (e.g. no points in data).
Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
this function may have size zero, which wouldn't count as a valid range.
\see rescaleAxes, getKeyRange
*/
/* end of documentation of pure virtual functions */
/* start of documentation of signals */
/*! \fn void QCPAbstractPlottable::selectionChanged(bool selected)
This signal is emitted when the selection state of this plottable has changed, either by user
interaction or by a direct call to \ref setSelected.
*/
/*! \fn void QCPAbstractPlottable::selectableChanged(bool selectable);
This signal is emitted when the selectability of this plottable has changed.
\see setSelectable
*/
/* end of documentation of signals */
/*!
Constructs an abstract plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as
its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance
and have perpendicular orientations. If either of these restrictions is violated, a corresponding
message is printed to the debug output (qDebug), the construction is not aborted, though.
Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables,
it can't be directly instantiated.
You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead.
*/
QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis->axisRect()),
mName(),
mAntialiasedFill(true),
mAntialiasedScatters(true),
mAntialiasedErrorBars(false),
mPen(Qt::black),
mSelectedPen(Qt::black),
mBrush(Qt::NoBrush),
mSelectedBrush(Qt::NoBrush),
mKeyAxis(keyAxis),
mValueAxis(valueAxis),
mSelectable(true),
mSelected(false)
{
if (keyAxis->parentPlot() != valueAxis->parentPlot())
qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis.";
if (keyAxis->orientation() == valueAxis->orientation())
qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other.";
}
/*!
The name is the textual representation of this plottable as it is displayed in the legend
(\ref QCPLegend). It may contain any UTF-8 characters, including newlines.
*/
void QCPAbstractPlottable::setName(const QString &name)
{
mName = name;
}
/*!
Sets whether fills of this plottable are drawn antialiased or not.
Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
*/
void QCPAbstractPlottable::setAntialiasedFill(bool enabled)
{
mAntialiasedFill = enabled;
}
/*!
Sets whether the scatter symbols of this plottable are drawn antialiased or not.
Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
*/
void QCPAbstractPlottable::setAntialiasedScatters(bool enabled)
{
mAntialiasedScatters = enabled;
}
/*!
Sets whether the error bars of this plottable are drawn antialiased or not.
Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
*/
void QCPAbstractPlottable::setAntialiasedErrorBars(bool enabled)
{
mAntialiasedErrorBars = enabled;
}
/*!
The pen is used to draw basic lines that make up the plottable representation in the
plot.
For example, the \ref QCPGraph subclass draws its graph lines with this pen.
\see setBrush
*/
void QCPAbstractPlottable::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
When the plottable is selected, this pen is used to draw basic lines instead of the normal
pen set via \ref setPen.
\see setSelected, setSelectable, setSelectedBrush, selectTest
*/
void QCPAbstractPlottable::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
The brush is used to draw basic fills of the plottable representation in the
plot. The Fill can be a color, gradient or texture, see the usage of QBrush.
For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when
it's not set to Qt::NoBrush.
\see setPen
*/
void QCPAbstractPlottable::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
When the plottable is selected, this brush is used to draw fills instead of the normal
brush set via \ref setBrush.
\see setSelected, setSelectable, setSelectedPen, selectTest
*/
void QCPAbstractPlottable::setSelectedBrush(const QBrush &brush)
{
mSelectedBrush = brush;
}
/*!
The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal
to the plottable's value axis. This function performs no checks to make sure this is the case.
The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the
y-axis (QCustomPlot::yAxis) as value axis.
Normally, the key and value axes are set in the constructor of the plottable (or \ref
QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
\see setValueAxis
*/
void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis)
{
mKeyAxis = axis;
}
/*!
The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is
orthogonal to the plottable's key axis. This function performs no checks to make sure this is the
case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and
the y-axis (QCustomPlot::yAxis) as value axis.
Normally, the key and value axes are set in the constructor of the plottable (or \ref
QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
\see setKeyAxis
*/
void QCPAbstractPlottable::setValueAxis(QCPAxis *axis)
{
mValueAxis = axis;
}
/*!
Sets whether the user can (de-)select this plottable by clicking on the QCustomPlot surface.
(When \ref QCustomPlot::setInteractions contains iSelectPlottables.)
However, even when \a selectable was set to false, it is possible to set the selection manually,
by calling \ref setSelected directly.
\see setSelected
*/
void QCPAbstractPlottable::setSelectable(bool selectable)
{
if (mSelectable != selectable)
{
mSelectable = selectable;
emit selectableChanged(mSelectable);
}
}
/*!
Sets whether this plottable is selected or not. When selected, it uses a different pen and brush
to draw its lines and fills, see \ref setSelectedPen and \ref setSelectedBrush.
The entire selection mechanism for plottables is handled automatically when \ref
QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
you wish to change the selection state manually.
This function can change the selection state even when \ref setSelectable was set to false.
emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
\see setSelectable, selectTest
*/
void QCPAbstractPlottable::setSelected(bool selected)
{
if (mSelected != selected)
{
mSelected = selected;
emit selectionChanged(mSelected);
}
}
/*!
Rescales the key and value axes associated with this plottable to contain all displayed data, so
the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make
sure not to rescale to an illegal range i.e. a range containing different signs and/or zero.
Instead it will stay in the current sign domain and ignore all parts of the plottable that lie
outside of that domain.
\a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show
multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has
\a onlyEnlarge set to false (the default), and all subsequent set to true.
\see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale
*/
void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const
{
rescaleKeyAxis(onlyEnlarge);
rescaleValueAxis(onlyEnlarge);
}
/*!
Rescales the key axis of the plottable so the whole plottable is visible.
See \ref rescaleAxes for detailed behaviour.
*/
void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const
{
QCPAxis *keyAxis = mKeyAxis.data();
if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
SignDomain signDomain = sdBoth;
if (keyAxis->scaleType() == QCPAxis::stLogarithmic)
signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive);
bool foundRange;
QCPRange newRange = getKeyRange(foundRange, signDomain);
if (foundRange)
{
if (onlyEnlarge)
newRange.expand(keyAxis->range());
if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
{
double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
if (keyAxis->scaleType() == QCPAxis::stLinear)
{
newRange.lower = center-keyAxis->range().size()/2.0;
newRange.upper = center+keyAxis->range().size()/2.0;
} else // scaleType() == stLogarithmic
{
newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower);
newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower);
}
}
keyAxis->setRange(newRange);
}
}
/*!
Rescales the value axis of the plottable so the whole plottable is visible.
Returns true if the axis was actually scaled. This might not be the case if this plottable has an
invalid range, e.g. because it has no data points.
See \ref rescaleAxes for detailed behaviour.
*/
void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge) const
{
QCPAxis *valueAxis = mValueAxis.data();
if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; }
SignDomain signDomain = sdBoth;
if (valueAxis->scaleType() == QCPAxis::stLogarithmic)
signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive);
bool foundRange;
QCPRange newRange = getValueRange(foundRange, signDomain);
if (foundRange)
{
if (onlyEnlarge)
newRange.expand(valueAxis->range());
if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
{
double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
if (valueAxis->scaleType() == QCPAxis::stLinear)
{
newRange.lower = center-valueAxis->range().size()/2.0;
newRange.upper = center+valueAxis->range().size()/2.0;
} else // scaleType() == stLogarithmic
{
newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower);
newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower);
}
}
valueAxis->setRange(newRange);
}
}
/*!
Adds this plottable to the legend of the parent QCustomPlot (QCustomPlot::legend).
Normally, a QCPPlottableLegendItem is created and inserted into the legend. If the plottable
needs a more specialized representation in the legend, this function will take this into account
and instead create the specialized subclass of QCPAbstractLegendItem.
Returns true on success, i.e. when the legend exists and a legend item associated with this plottable isn't already in
the legend.
\see removeFromLegend, QCPLegend::addItem
*/
bool QCPAbstractPlottable::addToLegend()
{
if (!mParentPlot || !mParentPlot->legend)
return false;
if (!mParentPlot->legend->hasItemWithPlottable(this))
{
mParentPlot->legend->addItem(new QCPPlottableLegendItem(mParentPlot->legend, this));
return true;
} else
return false;
}
/*!
Removes the plottable from the legend of the parent QCustomPlot. This means the
QCPAbstractLegendItem (usually a QCPPlottableLegendItem) that is associated with this plottable
is removed.
Returns true on success, i.e. if the legend exists and a legend item associated with this
plottable was found and removed.
\see addToLegend, QCPLegend::removeItem
*/
bool QCPAbstractPlottable::removeFromLegend() const
{
if (!mParentPlot->legend)
return false;
if (QCPPlottableLegendItem *lip = mParentPlot->legend->itemWithPlottable(this))
return mParentPlot->legend->removeItem(lip);
else
return false;
}
/* inherits documentation from base class */
QRect QCPAbstractPlottable::clipRect() const
{
if (mKeyAxis && mValueAxis)
return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect();
else
return QRect();
}
/* inherits documentation from base class */
QCP::Interaction QCPAbstractPlottable::selectionCategory() const
{
return QCP::iSelectPlottables;
}
/*! \internal
Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface,
taking the orientations of the axes associated with this plottable into account (e.g. whether key
represents x or y).
\a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y.
\see pixelsToCoords, QCPAxis::coordToPixel
*/
void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (keyAxis->orientation() == Qt::Horizontal)
{
x = keyAxis->coordToPixel(key);
y = valueAxis->coordToPixel(value);
} else
{
y = keyAxis->coordToPixel(key);
x = valueAxis->coordToPixel(value);
}
}
/*! \internal
\overload
Returns the input as pixel coordinates in a QPointF.
*/
const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
if (keyAxis->orientation() == Qt::Horizontal)
return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value));
else
return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key));
}
/*! \internal
Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates,
taking the orientations of the axes associated with this plottable into account (e.g. whether key
represents x or y).
\a x and \a y are transformed to the plot coodinates and are written to \a key and \a value.
\see coordsToPixels, QCPAxis::coordToPixel
*/
void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (keyAxis->orientation() == Qt::Horizontal)
{
key = keyAxis->pixelToCoord(x);
value = valueAxis->pixelToCoord(y);
} else
{
key = keyAxis->pixelToCoord(y);
value = valueAxis->pixelToCoord(x);
}
}
/*! \internal
\overload
Returns the pixel input \a pixelPos as plot coordinates \a key and \a value.
*/
void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const
{
pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value);
}
/*! \internal
Returns the pen that should be used for drawing lines of the plottable. Returns mPen when the
graph is not selected and mSelectedPen when it is.
*/
QPen QCPAbstractPlottable::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
/*! \internal
Returns the brush that should be used for drawing fills of the plottable. Returns mBrush when the
graph is not selected and mSelectedBrush when it is.
*/
QBrush QCPAbstractPlottable::mainBrush() const
{
return mSelected ? mSelectedBrush : mBrush;
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing plottable lines.
This is the antialiasing state the painter passed to the \ref draw method is in by default.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint
*/
void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables);
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing plottable fills.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint
*/
void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills);
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing plottable scatter points.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint, applyErrorBarsAntialiasingHint
*/
void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters);
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing plottable error bars.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyDefaultAntialiasingHint
*/
void QCPAbstractPlottable::applyErrorBarsAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiasedErrorBars, QCP::aeErrorBars);
}
/*! \internal
Finds the shortest squared distance of \a point to the line segment defined by \a start and \a
end.
This function may be used to help with the implementation of the \ref selectTest function for
specific plottables.
\note This function is identical to QCPAbstractItem::distSqrToLine
*/
double QCPAbstractPlottable::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const
{
QVector2D a(start);
QVector2D b(end);
QVector2D p(point);
QVector2D v(b-a);
double vLengthSqr = v.lengthSquared();
if (!qFuzzyIsNull(vLengthSqr))
{
double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr;
if (mu < 0)
return (a-p).lengthSquared();
else if (mu > 1)
return (b-p).lengthSquared();
else
return ((a + mu*v)-p).lengthSquared();
} else
return (a-p).lengthSquared();
}
/* inherits documentation from base class */
void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
Q_UNUSED(details)
if (mSelectable)
{
bool selBefore = mSelected;
setSelected(additive ? !mSelected : true);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
/* inherits documentation from base class */
void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged)
{
if (mSelectable)
{
bool selBefore = mSelected;
setSelected(false);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemAnchor
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemAnchor
\brief An anchor of an item to which positions can be attached to.
An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't
control anything on its item, but provides a way to tie other items via their positions to the
anchor.
For example, a QCPItemRect is defined by its positions \a topLeft and \a bottomRight.
Additionally it has various anchors like \a top, \a topRight or \a bottomLeft etc. So you can
attach the \a start (which is a QCPItemPosition) of a QCPItemLine to one of the anchors by
calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the
QCPItemRect. This way the start of the line will now always follow the respective anchor location
on the rect item.
Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an
anchor to other positions.
To learn how to provide anchors in your own item subclasses, see the subclassing section of the
QCPAbstractItem documentation.
*/
/* start documentation of inline functions */
/*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition()
Returns 0 if this instance is merely a QCPItemAnchor, and a valid pointer of type QCPItemPosition* if
it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor).
This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids
dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with
gcc compiler).
*/
/* end documentation of inline functions */
/*!
Creates a new QCPItemAnchor. You shouldn't create QCPItemAnchor instances directly, even if
you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as
explained in the subclassing section of the QCPAbstractItem documentation.
*/
QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId) :
mName(name),
mParentPlot(parentPlot),
mParentItem(parentItem),
mAnchorId(anchorId)
{
}
QCPItemAnchor::~QCPItemAnchor()
{
// unregister as parent at children:
foreach (QCPItemPosition *child, mChildrenX.toList())
{
if (child->parentAnchorX() == this)
child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX
}
foreach (QCPItemPosition *child, mChildrenY.toList())
{
if (child->parentAnchorY() == this)
child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY
}
}
/*!
Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface.
The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the
parent item, QCPItemAnchor is just an intermediary.
*/
QPointF QCPItemAnchor::pixelPoint() const
{
if (mParentItem)
{
if (mAnchorId > -1)
{
return mParentItem->anchorPixelPoint(mAnchorId);
} else
{
qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId;
return QPointF();
}
} else
{
qDebug() << Q_FUNC_INFO << "no parent item set";
return QPointF();
}
}
/*! \internal
Adds \a pos to the childX list of this anchor, which keeps track of which children use this
anchor as parent anchor for the respective coordinate. This is necessary to notify the children
prior to destruction of the anchor.
Note that this function does not change the parent setting in \a pos.
*/
void QCPItemAnchor::addChildX(QCPItemPosition *pos)
{
if (!mChildrenX.contains(pos))
mChildrenX.insert(pos);
else
qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
}
/*! \internal
Removes \a pos from the childX list of this anchor.
Note that this function does not change the parent setting in \a pos.
*/
void QCPItemAnchor::removeChildX(QCPItemPosition *pos)
{
if (!mChildrenX.remove(pos))
qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
}
/*! \internal
Adds \a pos to the childY list of this anchor, which keeps track of which children use this
anchor as parent anchor for the respective coordinate. This is necessary to notify the children
prior to destruction of the anchor.
Note that this function does not change the parent setting in \a pos.
*/
void QCPItemAnchor::addChildY(QCPItemPosition *pos)
{
if (!mChildrenY.contains(pos))
mChildrenY.insert(pos);
else
qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
}
/*! \internal
Removes \a pos from the childY list of this anchor.
Note that this function does not change the parent setting in \a pos.
*/
void QCPItemAnchor::removeChildY(QCPItemPosition *pos)
{
if (!mChildrenY.remove(pos))
qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemPosition
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemPosition
\brief Manages the position of an item.
Every item has at least one public QCPItemPosition member pointer which provides ways to position the
item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two:
\a topLeft and \a bottomRight.
QCPItemPosition has a type (\ref PositionType) that can be set with \ref setType. This type
defines how coordinates passed to \ref setCoords are to be interpreted, e.g. as absolute pixel
coordinates, as plot coordinates of certain axes, etc. For more advanced plots it is also
possible to assign different types per X/Y coordinate of the position (see \ref setTypeX, \ref
setTypeY). This way an item could be positioned at a fixed pixel distance from the top in the Y
direction, while following a plot coordinate in the X direction.
A QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. This way you can tie
multiple items together. If the QCPItemPosition has a parent, its coordinates (\ref setCoords)
are considered to be absolute pixels in the reference frame of the parent anchor, where (0, 0)
means directly ontop of the parent anchor. For example, You could attach the \a start position of
a QCPItemLine to the \a bottom anchor of a QCPItemText to make the starting point of the line
always be centered under the text label, no matter where the text is moved to. For more advanced
plots, it is possible to assign different parent anchors per X/Y coordinate of the position, see
\ref setParentAnchorX, \ref setParentAnchorY. This way an item could follow another item in the X
direction but stay at a fixed position in the Y direction. Or even follow item A in X, and item B
in Y.
Note that every QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent
anchor for other positions.
To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPoint. This
works no matter what type this QCPItemPosition is or what parent-child situation it is in, as \ref
setPixelPoint transforms the coordinates appropriately, to make the position appear at the specified
pixel values.
*/
/* start documentation of inline functions */
/*! \fn QCPItemPosition::PositionType *QCPItemPosition::type() const
Returns the current position type.
If different types were set for X and Y (\ref setTypeX, \ref setTypeY), this method returns the
type of the X coordinate. In that case rather use \a typeX() and \a typeY().
\see setType
*/
/*! \fn QCPItemAnchor *QCPItemPosition::parentAnchor() const
Returns the current parent anchor.
If different parent anchors were set for X and Y (\ref setParentAnchorX, \ref setParentAnchorY),
this method returns the parent anchor of the Y coordinate. In that case rather use \a
parentAnchorX() and \a parentAnchorY().
\see setParentAnchor
*/
/* end documentation of inline functions */
/*!
Creates a new QCPItemPosition. You shouldn't create QCPItemPosition instances directly, even if
you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as
explained in the subclassing section of the QCPAbstractItem documentation.
*/
QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name) :
QCPItemAnchor(parentPlot, parentItem, name),
mPositionTypeX(ptAbsolute),
mPositionTypeY(ptAbsolute),
mKey(0),
mValue(0),
mParentAnchorX(0),
mParentAnchorY(0)
{
}
QCPItemPosition::~QCPItemPosition()
{
// unregister as parent at children:
// Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it itself, because only then
// the setParentAnchor(0) call the correct QCPItemPosition::pixelPoint function instead of QCPItemAnchor::pixelPoint
foreach (QCPItemPosition *child, mChildrenX.toList())
{
if (child->parentAnchorX() == this)
child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX
}
foreach (QCPItemPosition *child, mChildrenY.toList())
{
if (child->parentAnchorY() == this)
child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY
}
// unregister as child in parent:
if (mParentAnchorX)
mParentAnchorX->removeChildX(this);
if (mParentAnchorY)
mParentAnchorY->removeChildY(this);
}
/* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
QCPAxisRect *QCPItemPosition::axisRect() const
{
return mAxisRect.data();
}
/*!
Sets the type of the position. The type defines how the coordinates passed to \ref setCoords
should be handled and how the QCPItemPosition should behave in the plot.
The possible values for \a type can be separated in two main categories:
\li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords
and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes.
By default, the QCustomPlot's x- and yAxis are used.
\li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This
corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref
ptAxisRectRatio. They differ only in the way the absolute position is described, see the
documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify
the axis rect with \ref setAxisRect. By default this is set to the main axis rect.
Note that the position type \ref ptPlotCoords is only available (and sensible) when the position
has no parent anchor (\ref setParentAnchor).
If the type is changed, the apparent pixel position on the plot is preserved. This means
the coordinates as retrieved with coords() and set with \ref setCoords may change in the process.
This method sets the type for both X and Y directions. It is also possible to set different types
for X and Y, see \ref setTypeX, \ref setTypeY.
*/
void QCPItemPosition::setType(QCPItemPosition::PositionType type)
{
setTypeX(type);
setTypeY(type);
}
/*!
This method sets the position type of the X coordinate to \a type.
For a detailed description of what a position type is, see the documentation of \ref setType.
\see setType, setTypeY
*/
void QCPItemPosition::setTypeX(QCPItemPosition::PositionType type)
{
if (mPositionTypeX != type)
{
// if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
// were deleted), don't try to recover the pixelPoint() because it would output a qDebug warning.
bool retainPixelPosition = true;
if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
retainPixelPosition = false;
if ((mPositionTypeX == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
retainPixelPosition = false;
QPointF pixel;
if (retainPixelPosition)
pixel = pixelPoint();
mPositionTypeX = type;
if (retainPixelPosition)
setPixelPoint(pixel);
}
}
/*!
This method sets the position type of the Y coordinate to \a type.
For a detailed description of what a position type is, see the documentation of \ref setType.
\see setType, setTypeX
*/
void QCPItemPosition::setTypeY(QCPItemPosition::PositionType type)
{
if (mPositionTypeY != type)
{
// if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
// were deleted), don't try to recover the pixelPoint() because it would output a qDebug warning.
bool retainPixelPosition = true;
if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
retainPixelPosition = false;
if ((mPositionTypeY == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
retainPixelPosition = false;
QPointF pixel;
if (retainPixelPosition)
pixel = pixelPoint();
mPositionTypeY = type;
if (retainPixelPosition)
setPixelPoint(pixel);
}
}
/*!
Sets the parent of this QCPItemPosition to \a parentAnchor. This means the position will now
follow any position changes of the anchor. The local coordinate system of positions with a parent
anchor always is absolute pixels, with (0, 0) being exactly on top of the parent anchor. (Hence
the type shouldn't be set to \ref ptPlotCoords for positions with parent anchors.)
if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved
during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position
will be exactly on top of the parent anchor.
To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to 0.
If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is
set to \ref ptAbsolute, to keep the position in a valid state.
This method sets the parent anchor for both X and Y directions. It is also possible to set
different parents for X and Y, see \ref setParentAnchorX, \ref setParentAnchorY.
*/
bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
{
bool successX = setParentAnchorX(parentAnchor, keepPixelPosition);
bool successY = setParentAnchorY(parentAnchor, keepPixelPosition);
return successX && successY;
}
/*!
This method sets the parent anchor of the X coordinate to \a parentAnchor.
For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor.
\see setParentAnchor, setParentAnchorY
*/
bool QCPItemPosition::setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
{
// make sure self is not assigned as parent:
if (parentAnchor == this)
{
qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
return false;
}
// make sure no recursive parent-child-relationships are created:
QCPItemAnchor *currentParent = parentAnchor;
while (currentParent)
{
if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
{
// is a QCPItemPosition, might have further parent, so keep iterating
if (currentParentPos == this)
{
qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
return false;
}
currentParent = currentParentPos->parentAnchorX();
} else
{
// is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
// same, to prevent a position being child of an anchor which itself depends on the position,
// because they're both on the same item:
if (currentParent->mParentItem == mParentItem)
{
qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
return false;
}
break;
}
}
// if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
if (!mParentAnchorX && mPositionTypeX == ptPlotCoords)
setTypeX(ptAbsolute);
// save pixel position:
QPointF pixelP;
if (keepPixelPosition)
pixelP = pixelPoint();
// unregister at current parent anchor:
if (mParentAnchorX)
mParentAnchorX->removeChildX(this);
// register at new parent anchor:
if (parentAnchor)
parentAnchor->addChildX(this);
mParentAnchorX = parentAnchor;
// restore pixel position under new parent:
if (keepPixelPosition)
setPixelPoint(pixelP);
else
setCoords(0, coords().y());
return true;
}
/*!
This method sets the parent anchor of the Y coordinate to \a parentAnchor.
For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor.
\see setParentAnchor, setParentAnchorX
*/
bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
{
// make sure self is not assigned as parent:
if (parentAnchor == this)
{
qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
return false;
}
// make sure no recursive parent-child-relationships are created:
QCPItemAnchor *currentParent = parentAnchor;
while (currentParent)
{
if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
{
// is a QCPItemPosition, might have further parent, so keep iterating
if (currentParentPos == this)
{
qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
return false;
}
currentParent = currentParentPos->parentAnchorY();
} else
{
// is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
// same, to prevent a position being child of an anchor which itself depends on the position,
// because they're both on the same item:
if (currentParent->mParentItem == mParentItem)
{
qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
return false;
}
break;
}
}
// if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
if (!mParentAnchorY && mPositionTypeY == ptPlotCoords)
setTypeY(ptAbsolute);
// save pixel position:
QPointF pixelP;
if (keepPixelPosition)
pixelP = pixelPoint();
// unregister at current parent anchor:
if (mParentAnchorY)
mParentAnchorY->removeChildY(this);
// register at new parent anchor:
if (parentAnchor)
parentAnchor->addChildY(this);
mParentAnchorY = parentAnchor;
// restore pixel position under new parent:
if (keepPixelPosition)
setPixelPoint(pixelP);
else
setCoords(coords().x(), 0);
return true;
}
/*!
Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type
(\ref setType, \ref setTypeX, \ref setTypeY).
For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position
on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the
QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the
plot coordinate system defined by the axes set by \ref setAxes. By default those are the
QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available
coordinate types and their meaning.
If different types were configured for X and Y (\ref setTypeX, \ref setTypeY), \a key and \a
value must also be provided in the different coordinate systems. Here, the X type refers to \a
key, and the Y type refers to \a value.
\see setPixelPoint
*/
void QCPItemPosition::setCoords(double key, double value)
{
mKey = key;
mValue = value;
}
/*! \overload
Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the
meaning of \a value of the \ref setCoords(double key, double value) method.
*/
void QCPItemPosition::setCoords(const QPointF &pos)
{
setCoords(pos.x(), pos.y());
}
/*!
Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It
includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor).
\see setPixelPoint
*/
QPointF QCPItemPosition::pixelPoint() const
{
QPointF result;
// determine X:
switch (mPositionTypeX)
{
case ptAbsolute:
{
result.rx() = mKey;
if (mParentAnchorX)
result.rx() += mParentAnchorX->pixelPoint().x();
break;
}
case ptViewportRatio:
{
result.rx() = mKey*mParentPlot->viewport().width();
if (mParentAnchorX)
result.rx() += mParentAnchorX->pixelPoint().x();
else
result.rx() += mParentPlot->viewport().left();
break;
}
case ptAxisRectRatio:
{
if (mAxisRect)
{
result.rx() = mKey*mAxisRect.data()->width();
if (mParentAnchorX)
result.rx() += mParentAnchorX->pixelPoint().x();
else
result.rx() += mAxisRect.data()->left();
} else
qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined";
break;
}
case ptPlotCoords:
{
if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal)
result.rx() = mKeyAxis.data()->coordToPixel(mKey);
else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal)
result.rx() = mValueAxis.data()->coordToPixel(mValue);
else
qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined";
break;
}
}
// determine Y:
switch (mPositionTypeY)
{
case ptAbsolute:
{
result.ry() = mValue;
if (mParentAnchorY)
result.ry() += mParentAnchorY->pixelPoint().y();
break;
}
case ptViewportRatio:
{
result.ry() = mValue*mParentPlot->viewport().height();
if (mParentAnchorY)
result.ry() += mParentAnchorY->pixelPoint().y();
else
result.ry() += mParentPlot->viewport().top();
break;
}
case ptAxisRectRatio:
{
if (mAxisRect)
{
result.ry() = mValue*mAxisRect.data()->height();
if (mParentAnchorY)
result.ry() += mParentAnchorY->pixelPoint().y();
else
result.ry() += mAxisRect.data()->top();
} else
qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined";
break;
}
case ptPlotCoords:
{
if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical)
result.ry() = mKeyAxis.data()->coordToPixel(mKey);
else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical)
result.ry() = mValueAxis.data()->coordToPixel(mValue);
else
qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined";
break;
}
}
return result;
}
/*!
When \ref setType is \ref ptPlotCoords, this function may be used to specify the axes the
coordinates set with \ref setCoords relate to. By default they are set to the initial xAxis and
yAxis of the QCustomPlot.
*/
void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis)
{
mKeyAxis = keyAxis;
mValueAxis = valueAxis;
}
/*!
When \ref setType is \ref ptAxisRectRatio, this function may be used to specify the axis rect the
coordinates set with \ref setCoords relate to. By default this is set to the main axis rect of
the QCustomPlot.
*/
void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect)
{
mAxisRect = axisRect;
}
/*!
Sets the apparent pixel position. This works no matter what type (\ref setType) this
QCPItemPosition is or what parent-child situation it is in, as coordinates are transformed
appropriately, to make the position finally appear at the specified pixel values.
Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is
identical to that of \ref setCoords.
\see pixelPoint, setCoords
*/
void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint)
{
double x = pixelPoint.x();
double y = pixelPoint.y();
switch (mPositionTypeX)
{
case ptAbsolute:
{
if (mParentAnchorX)
x -= mParentAnchorX->pixelPoint().x();
break;
}
case ptViewportRatio:
{
if (mParentAnchorX)
x -= mParentAnchorX->pixelPoint().x();
else
x -= mParentPlot->viewport().left();
x /= (double)mParentPlot->viewport().width();
break;
}
case ptAxisRectRatio:
{
if (mAxisRect)
{
if (mParentAnchorX)
x -= mParentAnchorX->pixelPoint().x();
else
x -= mAxisRect.data()->left();
x /= (double)mAxisRect.data()->width();
} else
qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined";
break;
}
case ptPlotCoords:
{
if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal)
x = mKeyAxis.data()->pixelToCoord(x);
else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal)
y = mValueAxis.data()->pixelToCoord(x);
else
qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined";
break;
}
}
switch (mPositionTypeY)
{
case ptAbsolute:
{
if (mParentAnchorY)
y -= mParentAnchorY->pixelPoint().y();
break;
}
case ptViewportRatio:
{
if (mParentAnchorY)
y -= mParentAnchorY->pixelPoint().y();
else
y -= mParentPlot->viewport().top();
y /= (double)mParentPlot->viewport().height();
break;
}
case ptAxisRectRatio:
{
if (mAxisRect)
{
if (mParentAnchorY)
y -= mParentAnchorY->pixelPoint().y();
else
y -= mAxisRect.data()->top();
y /= (double)mAxisRect.data()->height();
} else
qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined";
break;
}
case ptPlotCoords:
{
if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical)
x = mKeyAxis.data()->pixelToCoord(y);
else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical)
y = mValueAxis.data()->pixelToCoord(y);
else
qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined";
break;
}
}
setCoords(x, y);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAbstractItem
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAbstractItem
\brief The abstract base class for all items in a plot.
In QCustomPlot, items are supplemental graphical elements that are neither plottables
(QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus
plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each
specific item has at least one QCPItemPosition member which controls the positioning. Some items
are defined by more than one coordinate and thus have two or more QCPItemPosition members (For
example, QCPItemRect has \a topLeft and \a bottomRight).
This abstract base class defines a very basic interface like visibility and clipping. Since this
class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass
yourself to create new items.
The built-in items are:
<table>
<tr><td>QCPItemLine</td><td>A line defined by a start and an end point. May have different ending styles on each side (e.g. arrows).</td></tr>
<tr><td>QCPItemStraightLine</td><td>A straight line defined by a start and a direction point. Unlike QCPItemLine, the straight line is infinitely long and has no endings.</td></tr>
<tr><td>QCPItemCurve</td><td>A curve defined by start, end and two intermediate control points. May have different ending styles on each side (e.g. arrows).</td></tr>
<tr><td>QCPItemRect</td><td>A rectangle</td></tr>
<tr><td>QCPItemEllipse</td><td>An ellipse</td></tr>
<tr><td>QCPItemPixmap</td><td>An arbitrary pixmap</td></tr>
<tr><td>QCPItemText</td><td>A text label</td></tr>
<tr><td>QCPItemBracket</td><td>A bracket which may be used to reference/highlight certain parts in the plot.</td></tr>
<tr><td>QCPItemTracer</td><td>An item that can be attached to a QCPGraph and sticks to its data points, given a key coordinate.</td></tr>
</table>
\section items-clipping Clipping
Items are by default clipped to the main axis rect (they are only visible inside the axis rect).
To make an item visible outside that axis rect, disable clipping via \ref setClipToAxisRect
"setClipToAxisRect(false)".
On the other hand if you want the item to be clipped to a different axis rect, specify it via
\ref setClipAxisRect. This clipAxisRect property of an item is only used for clipping behaviour, and
in principle is independent of the coordinate axes the item might be tied to via its position
members (\ref QCPItemPosition::setAxes). However, it is common that the axis rect for clipping
also contains the axes used for the item positions.
\section items-using Using items
First you instantiate the item you want to use and add it to the plot:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-1
by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just
set the plot coordinates where the line should start/end:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-2
If we don't want the line to be positioned in plot coordinates but a different coordinate system,
e.g. absolute pixel positions on the QCustomPlot surface, we need to change the position type like this:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-3
Then we can set the coordinates, this time in pixels:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-4
and make the line visible on the entire QCustomPlot, by disabling clipping to the axis rect:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-5
For more advanced plots, it is even possible to set different types and parent anchors per X/Y
coordinate of an item position, using for example \ref QCPItemPosition::setTypeX or \ref
QCPItemPosition::setParentAnchorX. For details, see the documentation of \ref QCPItemPosition.
\section items-subclassing Creating own items
To create an own item, you implement a subclass of QCPAbstractItem. These are the pure
virtual functions, you must implement:
\li \ref selectTest
\li \ref draw
See the documentation of those functions for what they need to do.
\subsection items-positioning Allowing the item to be positioned
As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall
have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add
a public member of type QCPItemPosition like so:
\code QCPItemPosition * const myPosition;\endcode
the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition
instance it points to, can be modified, of course).
The initialization of this pointer is made easy with the \ref createPosition function. Just assign
the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition
takes a string which is the name of the position, typically this is identical to the variable name.
For example, the constructor of QCPItemExample could look like this:
\code
QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
myPosition(createPosition("myPosition"))
{
// other constructor code
}
\endcode
\subsection items-drawing The draw function
To give your item a visual representation, reimplement the \ref draw function and use the passed
QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the
position member(s) via \ref QCPItemPosition::pixelPoint.
To optimize performance you should calculate a bounding rect first (don't forget to take the pen
width into account), check whether it intersects the \ref clipRect, and only draw the item at all
if this is the case.
\subsection items-selection The selectTest function
Your implementation of the \ref selectTest function may use the helpers \ref distSqrToLine and
\ref rectSelectTest. With these, the implementation of the selection test becomes significantly
simpler for most items. See the documentation of \ref selectTest for what the function parameters
mean and what the function should return.
\subsection anchors Providing anchors
Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public
member, e.g.
\code QCPItemAnchor * const bottom;\endcode
and create it in the constructor with the \ref createAnchor function, assigning it a name and an
anchor id (an integer enumerating all anchors on the item, you may create an own enum for this).
Since anchors can be placed anywhere, relative to the item's position(s), your item needs to
provide the position of every anchor with the reimplementation of the \ref anchorPixelPoint(int
anchorId) function.
In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel
position when anything attached to the anchor needs to know the coordinates.
*/
/* start of documentation of inline functions */
/*! \fn QList<QCPItemPosition*> QCPAbstractItem::positions() const
Returns all positions of the item in a list.
\see anchors, position
*/
/*! \fn QList<QCPItemAnchor*> QCPAbstractItem::anchors() const
Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always
also an anchor, the list will also contain the positions of this item.
\see positions, anchor
*/
/* end of documentation of inline functions */
/* start documentation of pure virtual functions */
/*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0
\internal
Draws this item with the provided \a painter.
The cliprect of the provided painter is set to the rect returned by \ref clipRect before this
function is called. The clipRect depends on the clipping settings defined by \ref
setClipToAxisRect and \ref setClipAxisRect.
*/
/* end documentation of pure virtual functions */
/* start documentation of signals */
/*! \fn void QCPAbstractItem::selectionChanged(bool selected)
This signal is emitted when the selection state of this item has changed, either by user interaction
or by a direct call to \ref setSelected.
*/
/* end documentation of signals */
/*!
Base class constructor which initializes base class members.
*/
QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) :
QCPLayerable(parentPlot),
mClipToAxisRect(false),
mSelectable(true),
mSelected(false)
{
QList<QCPAxisRect*> rects = parentPlot->axisRects();
if (rects.size() > 0)
{
setClipToAxisRect(true);
setClipAxisRect(rects.first());
}
}
QCPAbstractItem::~QCPAbstractItem()
{
// don't delete mPositions because every position is also an anchor and thus in mAnchors
qDeleteAll(mAnchors);
}
/* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
QCPAxisRect *QCPAbstractItem::clipAxisRect() const
{
return mClipAxisRect.data();
}
/*!
Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the
entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect.
\see setClipAxisRect
*/
void QCPAbstractItem::setClipToAxisRect(bool clip)
{
mClipToAxisRect = clip;
if (mClipToAxisRect)
setParentLayerable(mClipAxisRect.data());
}
/*!
Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref
setClipToAxisRect is set to true.
\see setClipToAxisRect
*/
void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect)
{
mClipAxisRect = rect;
if (mClipToAxisRect)
setParentLayerable(mClipAxisRect.data());
}
/*!
Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface.
(When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.)
However, even when \a selectable was set to false, it is possible to set the selection manually,
by calling \ref setSelected.
\see QCustomPlot::setInteractions, setSelected
*/
void QCPAbstractItem::setSelectable(bool selectable)
{
if (mSelectable != selectable)
{
mSelectable = selectable;
emit selectableChanged(mSelectable);
}
}
/*!
Sets whether this item is selected or not. When selected, it might use a different visual
appearance (e.g. pen and brush), this depends on the specific item though.
The entire selection mechanism for items is handled automatically when \ref
QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this
function when you wish to change the selection state manually.
This function can change the selection state even when \ref setSelectable was set to false.
emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
\see setSelectable, selectTest
*/
void QCPAbstractItem::setSelected(bool selected)
{
if (mSelected != selected)
{
mSelected = selected;
emit selectionChanged(mSelected);
}
}
/*!
Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by
that name, returns 0.
This function provides an alternative way to access item positions. Normally, you access
positions direcly by their member pointers (which typically have the same variable name as \a
name).
\see positions, anchor
*/
QCPItemPosition *QCPAbstractItem::position(const QString &name) const
{
for (int i=0; i<mPositions.size(); ++i)
{
if (mPositions.at(i)->name() == name)
return mPositions.at(i);
}
qDebug() << Q_FUNC_INFO << "position with name not found:" << name;
return 0;
}
/*!
Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by
that name, returns 0.
This function provides an alternative way to access item anchors. Normally, you access
anchors direcly by their member pointers (which typically have the same variable name as \a
name).
\see anchors, position
*/
QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const
{
for (int i=0; i<mAnchors.size(); ++i)
{
if (mAnchors.at(i)->name() == name)
return mAnchors.at(i);
}
qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name;
return 0;
}
/*!
Returns whether this item has an anchor with the specified \a name.
Note that you can check for positions with this function, too. This is because every position is
also an anchor (QCPItemPosition inherits from QCPItemAnchor).
\see anchor, position
*/
bool QCPAbstractItem::hasAnchor(const QString &name) const
{
for (int i=0; i<mAnchors.size(); ++i)
{
if (mAnchors.at(i)->name() == name)
return true;
}
return false;
}
/*! \internal
Returns the rect the visual representation of this item is clipped to. This depends on the
current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect.
If the item is not clipped to an axis rect, the \ref QCustomPlot::viewport rect is returned.
\see draw
*/
QRect QCPAbstractItem::clipRect() const
{
if (mClipToAxisRect && mClipAxisRect)
return mClipAxisRect.data()->rect();
else
return mParentPlot->viewport();
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing item lines.
This is the antialiasing state the painter passed to the \ref draw method is in by default.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased
*/
void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeItems);
}
/*! \internal
Finds the shortest squared distance of \a point to the line segment defined by \a start and \a
end.
This function may be used to help with the implementation of the \ref selectTest function for
specific items.
\note This function is identical to QCPAbstractPlottable::distSqrToLine
\see rectSelectTest
*/
double QCPAbstractItem::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const
{
QVector2D a(start);
QVector2D b(end);
QVector2D p(point);
QVector2D v(b-a);
double vLengthSqr = v.lengthSquared();
if (!qFuzzyIsNull(vLengthSqr))
{
double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr;
if (mu < 0)
return (a-p).lengthSquared();
else if (mu > 1)
return (b-p).lengthSquared();
else
return ((a + mu*v)-p).lengthSquared();
} else
return (a-p).lengthSquared();
}
/*! \internal
A convenience function which returns the selectTest value for a specified \a rect and a specified
click position \a pos. \a filledRect defines whether a click inside the rect should also be
considered a hit or whether only the rect border is sensitive to hits.
This function may be used to help with the implementation of the \ref selectTest function for
specific items.
For example, if your item consists of four rects, call this function four times, once for each
rect, in your \ref selectTest reimplementation. Finally, return the minimum of all four returned
values.
\see distSqrToLine
*/
double QCPAbstractItem::rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const
{
double result = -1;
// distance to border:
QList<QLineF> lines;
lines << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight())
<< QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight());
double minDistSqr = std::numeric_limits<double>::max();
for (int i=0; i<lines.size(); ++i)
{
double distSqr = distSqrToLine(lines.at(i).p1(), lines.at(i).p2(), pos);
if (distSqr < minDistSqr)
minDistSqr = distSqr;
}
result = qSqrt(minDistSqr);
// filled rect, allow click inside to count as hit:
if (filledRect && result > mParentPlot->selectionTolerance()*0.99)
{
if (rect.contains(pos))
result = mParentPlot->selectionTolerance()*0.99;
}
return result;
}
/*! \internal
Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in
item subclasses if they want to provide anchors (QCPItemAnchor).
For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor
ids and returns the respective pixel points of the specified anchor.
\see createAnchor
*/
QPointF QCPAbstractItem::anchorPixelPoint(int anchorId) const
{
qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId;
return QPointF();
}
/*! \internal
Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified
\a name must be a unique string that is usually identical to the variable name of the position
member (This is needed to provide the name-based \ref position access to positions).
Don't delete positions created by this function manually, as the item will take care of it.
Use this function in the constructor (initialization list) of the specific item subclass to
create each position member. Don't create QCPItemPositions with \b new yourself, because they
won't be registered with the item properly.
\see createAnchor
*/
QCPItemPosition *QCPAbstractItem::createPosition(const QString &name)
{
if (hasAnchor(name))
qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name);
mPositions.append(newPosition);
mAnchors.append(newPosition); // every position is also an anchor
newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis);
newPosition->setType(QCPItemPosition::ptPlotCoords);
if (mParentPlot->axisRect())
newPosition->setAxisRect(mParentPlot->axisRect());
newPosition->setCoords(0, 0);
return newPosition;
}
/*! \internal
Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified
\a name must be a unique string that is usually identical to the variable name of the anchor
member (This is needed to provide the name based \ref anchor access to anchors).
The \a anchorId must be a number identifying the created anchor. It is recommended to create an
enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor
to identify itself when it calls QCPAbstractItem::anchorPixelPoint. That function then returns
the correct pixel coordinates for the passed anchor id.
Don't delete anchors created by this function manually, as the item will take care of it.
Use this function in the constructor (initialization list) of the specific item subclass to
create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they
won't be registered with the item properly.
\see createPosition
*/
QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId)
{
if (hasAnchor(name))
qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId);
mAnchors.append(newAnchor);
return newAnchor;
}
/* inherits documentation from base class */
void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
Q_UNUSED(details)
if (mSelectable)
{
bool selBefore = mSelected;
setSelected(additive ? !mSelected : true);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
/* inherits documentation from base class */
void QCPAbstractItem::deselectEvent(bool *selectionStateChanged)
{
if (mSelectable)
{
bool selBefore = mSelected;
setSelected(false);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
/* inherits documentation from base class */
QCP::Interaction QCPAbstractItem::selectionCategory() const
{
return QCP::iSelectItems;
}
/*! \file */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCustomPlot
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCustomPlot
\brief The central class of the library. This is the QWidget which displays the plot and
interacts with the user.
For tutorials on how to use QCustomPlot, see the website\n
http://www.qcustomplot.com/
*/
/* start of documentation of inline functions */
/*! \fn QRect QCustomPlot::viewport() const
Returns the viewport rect of this QCustomPlot instance. The viewport is the area the plot is
drawn in, all mechanisms, e.g. margin caluclation take the viewport to be the outer border of the
plot. The viewport normally is the rect() of the QCustomPlot widget, i.e. a rect with top left
(0, 0) and size of the QCustomPlot widget.
Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically
an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger
and contains also the axes themselves, their tick numbers, their labels, the plot title etc.
Only when saving to a file (see \ref savePng, \ref savePdf etc.) the viewport is temporarily
modified to allow saving plots with sizes independent of the current widget size.
*/
/*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const
Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just
one cell with the main QCPAxisRect inside.
*/
/* end of documentation of inline functions */
/* start of documentation of signals */
/*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event)
This signal is emitted when the QCustomPlot receives a mouse double click event.
*/
/*! \fn void QCustomPlot::mousePress(QMouseEvent *event)
This signal is emitted when the QCustomPlot receives a mouse press event.
It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
QCPAxisRect::setRangeDragAxes.
*/
/*! \fn void QCustomPlot::mouseMove(QMouseEvent *event)
This signal is emitted when the QCustomPlot receives a mouse move event.
It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
QCPAxisRect::setRangeDragAxes.
\warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here,
because the dragging starting point was saved the moment the mouse was pressed. Thus it only has
a meaning for the range drag axes that were set at that moment. If you want to change the drag
axes, consider doing this in the \ref mousePress signal instead.
*/
/*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event)
This signal is emitted when the QCustomPlot receives a mouse release event.
It is emitted before QCustomPlot handles any other mechanisms like object selection. So a
slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or
\ref QCPAbstractPlottable::setSelectable.
*/
/*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event)
This signal is emitted when the QCustomPlot receives a mouse wheel event.
It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot
connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref
QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor.
*/
/*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event)
This signal is emitted when a plottable is clicked.
\a event is the mouse event that caused the click and \a plottable is the plottable that received
the click.
\see plottableDoubleClick
*/
/*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event)
This signal is emitted when a plottable is double clicked.
\a event is the mouse event that caused the click and \a plottable is the plottable that received
the click.
\see plottableClick
*/
/*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event)
This signal is emitted when an item is clicked.
\a event is the mouse event that caused the click and \a item is the item that received the
click.
\see itemDoubleClick
*/
/*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event)
This signal is emitted when an item is double clicked.
\a event is the mouse event that caused the click and \a item is the item that received the
click.
\see itemClick
*/
/*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
This signal is emitted when an axis is clicked.
\a event is the mouse event that caused the click, \a axis is the axis that received the click and
\a part indicates the part of the axis that was clicked.
\see axisDoubleClick
*/
/*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
This signal is emitted when an axis is double clicked.
\a event is the mouse event that caused the click, \a axis is the axis that received the click and
\a part indicates the part of the axis that was clicked.
\see axisClick
*/
/*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
This signal is emitted when a legend (item) is clicked.
\a event is the mouse event that caused the click, \a legend is the legend that received the
click and \a item is the legend item that received the click. If only the legend and no item is
clicked, \a item is 0. This happens for a click inside the legend padding or the space between
two items.
\see legendDoubleClick
*/
/*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
This signal is emitted when a legend (item) is double clicked.
\a event is the mouse event that caused the click, \a legend is the legend that received the
click and \a item is the legend item that received the click. If only the legend and no item is
clicked, \a item is 0. This happens for a click inside the legend padding or the space between
two items.
\see legendClick
*/
/*! \fn void QCustomPlot:: titleClick(QMouseEvent *event, QCPPlotTitle *title)
This signal is emitted when a plot title is clicked.
\a event is the mouse event that caused the click and \a title is the plot title that received
the click.
\see titleDoubleClick
*/
/*! \fn void QCustomPlot::titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title)
This signal is emitted when a plot title is double clicked.
\a event is the mouse event that caused the click and \a title is the plot title that received
the click.
\see titleClick
*/
/*! \fn void QCustomPlot::selectionChangedByUser()
This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by
clicking. It is not emitted when the selection state of an object has changed programmatically by
a direct call to setSelected() on an object or by calling \ref deselectAll.
In addition to this signal, selectable objects also provide individual signals, for example
QCPAxis::selectionChanged or QCPAbstractPlottable::selectionChanged. Note that those signals are
emitted even if the selection state is changed programmatically.
See the documentation of \ref setInteractions for details about the selection mechanism.
\see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends
*/
/*! \fn void QCustomPlot::beforeReplot()
This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref
replot).
It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
replot synchronously, it won't cause an infinite recursion.
\see replot, afterReplot
*/
/*! \fn void QCustomPlot::afterReplot()
This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref
replot).
It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
replot synchronously, it won't cause an infinite recursion.
\see replot, beforeReplot
*/
/* end of documentation of signals */
/* start of documentation of public members */
/*! \var QCPAxis *QCustomPlot::xAxis
A pointer to the primary x Axis (bottom) of the main axis rect of the plot.
QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
default legend is removed due to manipulation of the layout system (e.g. by removing the main
axis rect), the corresponding pointers become 0.
*/
/*! \var QCPAxis *QCustomPlot::yAxis
A pointer to the primary y Axis (left) of the main axis rect of the plot.
QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
default legend is removed due to manipulation of the layout system (e.g. by removing the main
axis rect), the corresponding pointers become 0.
*/
/*! \var QCPAxis *QCustomPlot::xAxis2
A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are
invisible by default. Use QCPAxis::setVisible to change this (or use \ref
QCPAxisRect::setupFullAxesBox).
QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
default legend is removed due to manipulation of the layout system (e.g. by removing the main
axis rect), the corresponding pointers become 0.
*/
/*! \var QCPAxis *QCustomPlot::yAxis2
A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are
invisible by default. Use QCPAxis::setVisible to change this (or use \ref
QCPAxisRect::setupFullAxesBox).
QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
default legend is removed due to manipulation of the layout system (e.g. by removing the main
axis rect), the corresponding pointers become 0.
*/
/*! \var QCPLegend *QCustomPlot::legend
A pointer to the default legend of the main axis rect. The legend is invisible by default. Use
QCPLegend::setVisible to change this.
QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
layout system\endlink to add multiple legends to the plot, use the layout system interface to
access the new legend. For example, legends can be placed inside an axis rect's \ref
QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If
the default legend is removed due to manipulation of the layout system (e.g. by removing the main
axis rect), the corresponding pointer becomes 0.
*/
/* end of documentation of public members */
/*!
Constructs a QCustomPlot and sets reasonable default values.
*/
QCustomPlot::QCustomPlot(QWidget *parent) :
QWidget(parent),
xAxis(0),
yAxis(0),
xAxis2(0),
yAxis2(0),
legend(0),
mPlotLayout(0),
mAutoAddPlottableToLegend(true),
mAntialiasedElements(QCP::aeNone),
mNotAntialiasedElements(QCP::aeNone),
mInteractions(0),
mSelectionTolerance(8),
mNoAntialiasingOnDrag(false),
mBackgroundBrush(Qt::white, Qt::SolidPattern),
mBackgroundScaled(true),
mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
mCurrentLayer(0),
mPlottingHints(QCP::phCacheLabels|QCP::phForceRepaint),
mMultiSelectModifier(Qt::ControlModifier),
mPaintBuffer(size()),
mMouseEventElement(0),
mReplotting(false)
{
setAttribute(Qt::WA_NoMousePropagation);
setAttribute(Qt::WA_OpaquePaintEvent);
setMouseTracking(true);
QLocale currentLocale = locale();
currentLocale.setNumberOptions(QLocale::OmitGroupSeparator);
setLocale(currentLocale);
// create initial layers:
mLayers.append(new QCPLayer(this, QLatin1String("background")));
mLayers.append(new QCPLayer(this, QLatin1String("grid")));
mLayers.append(new QCPLayer(this, QLatin1String("main")));
mLayers.append(new QCPLayer(this, QLatin1String("axes")));
mLayers.append(new QCPLayer(this, QLatin1String("legend")));
updateLayerIndices();
setCurrentLayer(QLatin1String("main"));
// create initial layout, axis rect and legend:
mPlotLayout = new QCPLayoutGrid;
mPlotLayout->initializeParentPlot(this);
mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry
mPlotLayout->setLayer(QLatin1String("main"));
QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true);
mPlotLayout->addElement(0, 0, defaultAxisRect);
xAxis = defaultAxisRect->axis(QCPAxis::atBottom);
yAxis = defaultAxisRect->axis(QCPAxis::atLeft);
xAxis2 = defaultAxisRect->axis(QCPAxis::atTop);
yAxis2 = defaultAxisRect->axis(QCPAxis::atRight);
legend = new QCPLegend;
legend->setVisible(false);
defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop);
defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12));
defaultAxisRect->setLayer(QLatin1String("background"));
xAxis->setLayer(QLatin1String("axes"));
yAxis->setLayer(QLatin1String("axes"));
xAxis2->setLayer(QLatin1String("axes"));
yAxis2->setLayer(QLatin1String("axes"));
xAxis->grid()->setLayer(QLatin1String("grid"));
yAxis->grid()->setLayer(QLatin1String("grid"));
xAxis2->grid()->setLayer(QLatin1String("grid"));
yAxis2->grid()->setLayer(QLatin1String("grid"));
legend->setLayer(QLatin1String("legend"));
setViewport(rect()); // needs to be called after mPlotLayout has been created
replot();
}
QCustomPlot::~QCustomPlot()
{
clearPlottables();
clearItems();
if (mPlotLayout)
{
delete mPlotLayout;
mPlotLayout = 0;
}
mCurrentLayer = 0;
qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed
mLayers.clear();
}
/*!
Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement.
This overrides the antialiasing settings for whole element groups, normally controlled with the
\a setAntialiasing function on the individual elements. If an element is neither specified in
\ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
each individual element instance is used.
For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be
drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
to.
if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is
removed from there.
\see setNotAntialiasedElements
*/
void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements)
{
mAntialiasedElements = antialiasedElements;
// make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
mNotAntialiasedElements |= ~mAntialiasedElements;
}
/*!
Sets whether the specified \a antialiasedElement is forcibly drawn antialiased.
See \ref setAntialiasedElements for details.
\see setNotAntialiasedElement
*/
void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled)
{
if (!enabled && mAntialiasedElements.testFlag(antialiasedElement))
mAntialiasedElements &= ~antialiasedElement;
else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement))
mAntialiasedElements |= antialiasedElement;
// make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
mNotAntialiasedElements |= ~mAntialiasedElements;
}
/*!
Sets which elements are forcibly drawn not antialiased as an \a or combination of
QCP::AntialiasedElement.
This overrides the antialiasing settings for whole element groups, normally controlled with the
\a setAntialiasing function on the individual elements. If an element is neither specified in
\ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
each individual element instance is used.
For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be
drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
to.
if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is
removed from there.
\see setAntialiasedElements
*/
void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements)
{
mNotAntialiasedElements = notAntialiasedElements;
// make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
mAntialiasedElements |= ~mNotAntialiasedElements;
}
/*!
Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased.
See \ref setNotAntialiasedElements for details.
\see setAntialiasedElement
*/
void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled)
{
if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement))
mNotAntialiasedElements &= ~notAntialiasedElement;
else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement))
mNotAntialiasedElements |= notAntialiasedElement;
// make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
mAntialiasedElements |= ~mNotAntialiasedElements;
}
/*!
If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the
plottable to the legend (QCustomPlot::legend).
\see addPlottable, addGraph, QCPLegend::addItem
*/
void QCustomPlot::setAutoAddPlottableToLegend(bool on)
{
mAutoAddPlottableToLegend = on;
}
/*!
Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction
enums. There are the following types of interactions:
<b>Axis range manipulation</b> is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the
respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel.
For details how to control which axes the user may drag/zoom and in what orientations, see \ref
QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes,
\ref QCPAxisRect::setRangeZoomAxes.
<b>Plottable selection</b> is controlled by \ref QCP::iSelectPlottables. If \ref QCP::iSelectPlottables is
set, the user may select plottables (graphs, curves, bars,...) by clicking on them or in their
vicinity (\ref setSelectionTolerance). Whether the user can actually select a plottable can
further be restricted with the \ref QCPAbstractPlottable::setSelectable function on the specific
plottable. To find out whether a specific plottable is selected, call
QCPAbstractPlottable::selected(). To retrieve a list of all currently selected plottables, call
\ref selectedPlottables. If you're only interested in QCPGraphs, you may use the convenience
function \ref selectedGraphs.
<b>Item selection</b> is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set, the user
may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity. To find
out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of
all currently selected items, call \ref selectedItems.
<b>Axis selection</b> is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user
may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick
labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for
each axis. To retrieve a list of all axes that currently contain selected parts, call \ref
selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts().
<b>Legend selection</b> is controlled with \ref QCP::iSelectLegend. If this is set, the user may
select the legend itself or individual items by clicking on them. What parts exactly are
selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the
legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To
find out which child items are selected, call \ref QCPLegend::selectedItems.
<b>All other selectable elements</b> The selection of all other selectable objects (e.g.
QCPPlotTitle, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the
user may select those objects by clicking on them. To find out which are currently selected, you
need to check their selected state explicitly.
If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is
emitted. Each selectable object additionally emits an individual selectionChanged signal whenever
their selection state has changed, i.e. not only by user interaction.
To allow multiple objects to be selected by holding the selection modifier (\ref
setMultiSelectModifier), set the flag \ref QCP::iMultiSelect.
\note In addition to the selection mechanism presented here, QCustomPlot always emits
corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and
\ref plottableDoubleClick for example.
\see setInteraction, setSelectionTolerance
*/
void QCustomPlot::setInteractions(const QCP::Interactions &interactions)
{
mInteractions = interactions;
}
/*!
Sets the single \a interaction of this QCustomPlot to \a enabled.
For details about the interaction system, see \ref setInteractions.
\see setInteractions
*/
void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled)
{
if (!enabled && mInteractions.testFlag(interaction))
mInteractions &= ~interaction;
else if (enabled && !mInteractions.testFlag(interaction))
mInteractions |= interaction;
}
/*!
Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or
not.
If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a
potential selection when the minimum distance between the click position and the graph line is
smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks
directly inside the area and ignore this selection tolerance. In other words, it only has meaning
for parts of objects that are too thin to exactly hit with a click and thus need such a
tolerance.
\see setInteractions, QCPLayerable::selectTest
*/
void QCustomPlot::setSelectionTolerance(int pixels)
{
mSelectionTolerance = pixels;
}
/*!
Sets whether antialiasing is disabled for this QCustomPlot while the user is dragging axes
ranges. If many objects, especially plottables, are drawn antialiased, this greatly improves
performance during dragging. Thus it creates a more responsive user experience. As soon as the
user stops dragging, the last replot is done with normal antialiasing, to restore high image
quality.
\see setAntialiasedElements, setNotAntialiasedElements
*/
void QCustomPlot::setNoAntialiasingOnDrag(bool enabled)
{
mNoAntialiasingOnDrag = enabled;
}
/*!
Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint.
\see setPlottingHint
*/
void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints)
{
mPlottingHints = hints;
}
/*!
Sets the specified plotting \a hint to \a enabled.
\see setPlottingHints
*/
void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled)
{
QCP::PlottingHints newHints = mPlottingHints;
if (!enabled)
newHints &= ~hint;
else
newHints |= hint;
if (newHints != mPlottingHints)
setPlottingHints(newHints);
}
/*!
Sets the keyboard modifier that will be recognized as multi-select-modifier.
If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple objects
by clicking on them one after the other while holding down \a modifier.
By default the multi-select-modifier is set to Qt::ControlModifier.
\see setInteractions
*/
void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier)
{
mMultiSelectModifier = modifier;
}
/*!
Sets the viewport of this QCustomPlot. The Viewport is the area that the top level layout
(QCustomPlot::plotLayout()) uses as its rect. Normally, the viewport is the entire widget rect.
This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref
savePdf, etc. by temporarily changing the viewport size.
*/
void QCustomPlot::setViewport(const QRect &rect)
{
mViewport = rect;
if (mPlotLayout)
mPlotLayout->setOuterRect(mViewport);
}
/*!
Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn
below all other objects in the plot.
For cases where the provided pixmap doesn't have the same size as the viewport, scaling can be
enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is
preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
consider using the overloaded version of this function.
If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will
first be filled with that brush, before drawing the background pixmap. This can be useful for
background pixmaps with translucent areas.
\see setBackgroundScaled, setBackgroundScaledMode
*/
void QCustomPlot::setBackground(const QPixmap &pm)
{
mBackgroundPixmap = pm;
mScaledBackgroundPixmap = QPixmap();
}
/*!
Sets the background brush of the viewport (see \ref setViewport).
Before drawing everything else, the background is filled with \a brush. If a background pixmap
was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport
before the background pixmap is drawn. This can be useful for background pixmaps with translucent
areas.
Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be
useful for exporting to image formats which support transparency, e.g. \ref savePng.
\see setBackgroundScaled, setBackgroundScaledMode
*/
void QCustomPlot::setBackground(const QBrush &brush)
{
mBackgroundBrush = brush;
}
/*! \overload
Allows setting the background pixmap of the viewport, whether it shall be scaled and how it
shall be scaled in one call.
\see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
*/
void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
{
mBackgroundPixmap = pm;
mScaledBackgroundPixmap = QPixmap();
mBackgroundScaled = scaled;
mBackgroundScaledMode = mode;
}
/*!
Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is
set to true, control whether and how the aspect ratio of the original pixmap is preserved with
\ref setBackgroundScaledMode.
Note that the scaled version of the original pixmap is buffered, so there is no performance
penalty on replots. (Except when the viewport dimensions are changed continuously.)
\see setBackground, setBackgroundScaledMode
*/
void QCustomPlot::setBackgroundScaled(bool scaled)
{
mBackgroundScaled = scaled;
}
/*!
If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this
function to define whether and how the aspect ratio of the original pixmap is preserved.
\see setBackground, setBackgroundScaled
*/
void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode)
{
mBackgroundScaledMode = mode;
}
/*!
Returns the plottable with \a index. If the index is invalid, returns 0.
There is an overloaded version of this function with no parameter which returns the last added
plottable, see QCustomPlot::plottable()
\see plottableCount, addPlottable
*/
QCPAbstractPlottable *QCustomPlot::plottable(int index)
{
if (index >= 0 && index < mPlottables.size())
{
return mPlottables.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return 0;
}
}
/*! \overload
Returns the last plottable that was added with \ref addPlottable. If there are no plottables in
the plot, returns 0.
\see plottableCount, addPlottable
*/
QCPAbstractPlottable *QCustomPlot::plottable()
{
if (!mPlottables.isEmpty())
{
return mPlottables.last();
} else
return 0;
}
/*!
Adds the specified plottable to the plot and, if \ref setAutoAddPlottableToLegend is enabled, to
the legend (QCustomPlot::legend). QCustomPlot takes ownership of the plottable.
Returns true on success, i.e. when \a plottable isn't already in the plot and the parent plot of
\a plottable is this QCustomPlot (the latter is controlled by what axes were passed in the
plottable's constructor).
\see plottable, plottableCount, removePlottable, clearPlottables
*/
bool QCustomPlot::addPlottable(QCPAbstractPlottable *plottable)
{
if (mPlottables.contains(plottable))
{
qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast<quintptr>(plottable);
return false;
}
if (plottable->parentPlot() != this)
{
qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(plottable);
return false;
}
mPlottables.append(plottable);
// possibly add plottable to legend:
if (mAutoAddPlottableToLegend)
plottable->addToLegend();
// special handling for QCPGraphs to maintain the simple graph interface:
if (QCPGraph *graph = qobject_cast<QCPGraph*>(plottable))
mGraphs.append(graph);
if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor)
plottable->setLayer(currentLayer());
return true;
}
/*!
Removes the specified plottable from the plot and, if necessary, from the legend (QCustomPlot::legend).
Returns true on success.
\see addPlottable, clearPlottables
*/
bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable)
{
if (!mPlottables.contains(plottable))
{
qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast<quintptr>(plottable);
return false;
}
// remove plottable from legend:
plottable->removeFromLegend();
// special handling for QCPGraphs to maintain the simple graph interface:
if (QCPGraph *graph = qobject_cast<QCPGraph*>(plottable))
mGraphs.removeOne(graph);
// remove plottable:
delete plottable;
mPlottables.removeOne(plottable);
return true;
}
/*! \overload
Removes the plottable by its \a index.
*/
bool QCustomPlot::removePlottable(int index)
{
if (index >= 0 && index < mPlottables.size())
return removePlottable(mPlottables[index]);
else
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return false;
}
}
/*!
Removes all plottables from the plot (and the QCustomPlot::legend, if necessary).
Returns the number of plottables removed.
\see removePlottable
*/
int QCustomPlot::clearPlottables()
{
int c = mPlottables.size();
for (int i=c-1; i >= 0; --i)
removePlottable(mPlottables[i]);
return c;
}
/*!
Returns the number of currently existing plottables in the plot
\see plottable, addPlottable
*/
int QCustomPlot::plottableCount() const
{
return mPlottables.size();
}
/*!
Returns a list of the selected plottables. If no plottables are currently selected, the list is empty.
There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs.
\see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected
*/
QList<QCPAbstractPlottable*> QCustomPlot::selectedPlottables() const
{
QList<QCPAbstractPlottable*> result;
foreach (QCPAbstractPlottable *plottable, mPlottables)
{
if (plottable->selected())
result.append(plottable);
}
return result;
}
/*!
Returns the plottable at the pixel position \a pos. Plottables that only consist of single lines
(like graphs) have a tolerance band around them, see \ref setSelectionTolerance. If multiple
plottables come into consideration, the one closest to \a pos is returned.
If \a onlySelectable is true, only plottables that are selectable
(QCPAbstractPlottable::setSelectable) are considered.
If there is no plottable at \a pos, the return value is 0.
\see itemAt, layoutElementAt
*/
QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable) const
{
QCPAbstractPlottable *resultPlottable = 0;
double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value
foreach (QCPAbstractPlottable *plottable, mPlottables)
{
if (onlySelectable && !plottable->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPabstractPlottable::selectable
continue;
if ((plottable->keyAxis()->axisRect()->rect() & plottable->valueAxis()->axisRect()->rect()).contains(pos.toPoint())) // only consider clicks inside the rect that is spanned by the plottable's key/value axes
{
double currentDistance = plottable->selectTest(pos, false);
if (currentDistance >= 0 && currentDistance < resultDistance)
{
resultPlottable = plottable;
resultDistance = currentDistance;
}
}
}
return resultPlottable;
}
/*!
Returns whether this QCustomPlot instance contains the \a plottable.
\see addPlottable
*/
bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const
{
return mPlottables.contains(plottable);
}
/*!
Returns the graph with \a index. If the index is invalid, returns 0.
There is an overloaded version of this function with no parameter which returns the last created
graph, see QCustomPlot::graph()
\see graphCount, addGraph
*/
QCPGraph *QCustomPlot::graph(int index) const
{
if (index >= 0 && index < mGraphs.size())
{
return mGraphs.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return 0;
}
}
/*! \overload
Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot,
returns 0.
\see graphCount, addGraph
*/
QCPGraph *QCustomPlot::graph() const
{
if (!mGraphs.isEmpty())
{
return mGraphs.last();
} else
return 0;
}
/*!
Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the
bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a
keyAxis and \a valueAxis must reside in this QCustomPlot.
\a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically
"y") for the graph.
Returns a pointer to the newly created graph, or 0 if adding the graph failed.
\see graph, graphCount, removeGraph, clearGraphs
*/
QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis)
{
if (!keyAxis) keyAxis = xAxis;
if (!valueAxis) valueAxis = yAxis;
if (!keyAxis || !valueAxis)
{
qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)";
return 0;
}
if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this)
{
qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent";
return 0;
}
QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis);
if (addPlottable(newGraph))
{
newGraph->setName(QLatin1String("Graph ")+QString::number(mGraphs.size()));
return newGraph;
} else
{
delete newGraph;
return 0;
}
}
/*!
Removes the specified \a graph from the plot and, if necessary, from the QCustomPlot::legend. If
any other graphs in the plot have a channel fill set towards the removed graph, the channel fill
property of those graphs is reset to zero (no channel fill).
Returns true on success.
\see clearGraphs
*/
bool QCustomPlot::removeGraph(QCPGraph *graph)
{
return removePlottable(graph);
}
/*! \overload
Removes the graph by its \a index.
*/
bool QCustomPlot::removeGraph(int index)
{
if (index >= 0 && index < mGraphs.size())
return removeGraph(mGraphs[index]);
else
return false;
}
/*!
Removes all graphs from the plot (and the QCustomPlot::legend, if necessary).
Returns the number of graphs removed.
\see removeGraph
*/
int QCustomPlot::clearGraphs()
{
int c = mGraphs.size();
for (int i=c-1; i >= 0; --i)
removeGraph(mGraphs[i]);
return c;
}
/*!
Returns the number of currently existing graphs in the plot
\see graph, addGraph
*/
int QCustomPlot::graphCount() const
{
return mGraphs.size();
}
/*!
Returns a list of the selected graphs. If no graphs are currently selected, the list is empty.
If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars,
etc., use \ref selectedPlottables.
\see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected
*/
QList<QCPGraph*> QCustomPlot::selectedGraphs() const
{
QList<QCPGraph*> result;
foreach (QCPGraph *graph, mGraphs)
{
if (graph->selected())
result.append(graph);
}
return result;
}
/*!
Returns the item with \a index. If the index is invalid, returns 0.
There is an overloaded version of this function with no parameter which returns the last added
item, see QCustomPlot::item()
\see itemCount, addItem
*/
QCPAbstractItem *QCustomPlot::item(int index) const
{
if (index >= 0 && index < mItems.size())
{
return mItems.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return 0;
}
}
/*! \overload
Returns the last item, that was added with \ref addItem. If there are no items in the plot,
returns 0.
\see itemCount, addItem
*/
QCPAbstractItem *QCustomPlot::item() const
{
if (!mItems.isEmpty())
{
return mItems.last();
} else
return 0;
}
/*!
Adds the specified item to the plot. QCustomPlot takes ownership of the item.
Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a
item is this QCustomPlot.
\see item, itemCount, removeItem, clearItems
*/
bool QCustomPlot::addItem(QCPAbstractItem *item)
{
if (!mItems.contains(item) && item->parentPlot() == this)
{
mItems.append(item);
return true;
} else
{
qDebug() << Q_FUNC_INFO << "item either already in list or not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(item);
return false;
}
}
/*!
Removes the specified item from the plot.
Returns true on success.
\see addItem, clearItems
*/
bool QCustomPlot::removeItem(QCPAbstractItem *item)
{
if (mItems.contains(item))
{
delete item;
mItems.removeOne(item);
return true;
} else
{
qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast<quintptr>(item);
return false;
}
}
/*! \overload
Removes the item by its \a index.
*/
bool QCustomPlot::removeItem(int index)
{
if (index >= 0 && index < mItems.size())
return removeItem(mItems[index]);
else
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return false;
}
}
/*!
Removes all items from the plot.
Returns the number of items removed.
\see removeItem
*/
int QCustomPlot::clearItems()
{
int c = mItems.size();
for (int i=c-1; i >= 0; --i)
removeItem(mItems[i]);
return c;
}
/*!
Returns the number of currently existing items in the plot
\see item, addItem
*/
int QCustomPlot::itemCount() const
{
return mItems.size();
}
/*!
Returns a list of the selected items. If no items are currently selected, the list is empty.
\see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected
*/
QList<QCPAbstractItem*> QCustomPlot::selectedItems() const
{
QList<QCPAbstractItem*> result;
foreach (QCPAbstractItem *item, mItems)
{
if (item->selected())
result.append(item);
}
return result;
}
/*!
Returns the item at the pixel position \a pos. Items that only consist of single lines (e.g. \ref
QCPItemLine or \ref QCPItemCurve) have a tolerance band around them, see \ref
setSelectionTolerance. If multiple items come into consideration, the one closest to \a pos is
returned.
If \a onlySelectable is true, only items that are selectable (QCPAbstractItem::setSelectable) are
considered.
If there is no item at \a pos, the return value is 0.
\see plottableAt, layoutElementAt
*/
QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const
{
QCPAbstractItem *resultItem = 0;
double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value
foreach (QCPAbstractItem *item, mItems)
{
if (onlySelectable && !item->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractItem::selectable
continue;
if (!item->clipToAxisRect() || item->clipRect().contains(pos.toPoint())) // only consider clicks inside axis cliprect of the item if actually clipped to it
{
double currentDistance = item->selectTest(pos, false);
if (currentDistance >= 0 && currentDistance < resultDistance)
{
resultItem = item;
resultDistance = currentDistance;
}
}
}
return resultItem;
}
/*!
Returns whether this QCustomPlot contains the \a item.
\see addItem
*/
bool QCustomPlot::hasItem(QCPAbstractItem *item) const
{
return mItems.contains(item);
}
/*!
Returns the layer with the specified \a name. If there is no layer with the specified name, 0 is
returned.
Layer names are case-sensitive.
\see addLayer, moveLayer, removeLayer
*/
QCPLayer *QCustomPlot::layer(const QString &name) const
{
foreach (QCPLayer *layer, mLayers)
{
if (layer->name() == name)
return layer;
}
return 0;
}
/*! \overload
Returns the layer by \a index. If the index is invalid, 0 is returned.
\see addLayer, moveLayer, removeLayer
*/
QCPLayer *QCustomPlot::layer(int index) const
{
if (index >= 0 && index < mLayers.size())
{
return mLayers.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return 0;
}
}
/*!
Returns the layer that is set as current layer (see \ref setCurrentLayer).
*/
QCPLayer *QCustomPlot::currentLayer() const
{
return mCurrentLayer;
}
/*!
Sets the layer with the specified \a name to be the current layer. All layerables (\ref
QCPLayerable), e.g. plottables and items, are created on the current layer.
Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot.
Layer names are case-sensitive.
\see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer
*/
bool QCustomPlot::setCurrentLayer(const QString &name)
{
if (QCPLayer *newCurrentLayer = layer(name))
{
return setCurrentLayer(newCurrentLayer);
} else
{
qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name;
return false;
}
}
/*! \overload
Sets the provided \a layer to be the current layer.
Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot.
\see addLayer, moveLayer, removeLayer
*/
bool QCustomPlot::setCurrentLayer(QCPLayer *layer)
{
if (!mLayers.contains(layer))
{
qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
return false;
}
mCurrentLayer = layer;
return true;
}
/*!
Returns the number of currently existing layers in the plot
\see layer, addLayer
*/
int QCustomPlot::layerCount() const
{
return mLayers.size();
}
/*!
Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which
must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer.
Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a
valid layer inside this QCustomPlot.
If \a otherLayer is 0, the highest layer in the QCustomPlot will be used.
For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer.
\see layer, moveLayer, removeLayer
*/
bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
{
if (!otherLayer)
otherLayer = mLayers.last();
if (!mLayers.contains(otherLayer))
{
qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
return false;
}
if (layer(name))
{
qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name;
return false;
}
QCPLayer *newLayer = new QCPLayer(this, name);
mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer);
updateLayerIndices();
return true;
}
/*!
Removes the specified \a layer and returns true on success.
All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below
\a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both
cases, the total rendering order of all layerables in the QCustomPlot is preserved.
If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom
layer) becomes the new current layer.
It is not possible to remove the last layer of the plot.
\see layer, addLayer, moveLayer
*/
bool QCustomPlot::removeLayer(QCPLayer *layer)
{
if (!mLayers.contains(layer))
{
qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
return false;
}
if (mLayers.size() < 2)
{
qDebug() << Q_FUNC_INFO << "can't remove last layer";
return false;
}
// append all children of this layer to layer below (if this is lowest layer, prepend to layer above)
int removedIndex = layer->index();
bool isFirstLayer = removedIndex==0;
QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1);
QList<QCPLayerable*> children = layer->children();
if (isFirstLayer) // prepend in reverse order (so order relative to each other stays the same)
{
for (int i=children.size()-1; i>=0; --i)
children.at(i)->moveToLayer(targetLayer, true);
} else // append normally
{
for (int i=0; i<children.size(); ++i)
children.at(i)->moveToLayer(targetLayer, false);
}
// if removed layer is current layer, change current layer to layer below/above:
if (layer == mCurrentLayer)
setCurrentLayer(targetLayer);
// remove layer:
delete layer;
mLayers.removeOne(layer);
updateLayerIndices();
return true;
}
/*!
Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or
below is controlled with \a insertMode.
Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the
QCustomPlot.
\see layer, addLayer, moveLayer
*/
bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
{
if (!mLayers.contains(layer))
{
qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
return false;
}
if (!mLayers.contains(otherLayer))
{
qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
return false;
}
if (layer->index() > otherLayer->index())
mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0));
else if (layer->index() < otherLayer->index())
mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 0:-1));
updateLayerIndices();
return true;
}
/*!
Returns the number of axis rects in the plot.
All axis rects can be accessed via QCustomPlot::axisRect().
Initially, only one axis rect exists in the plot.
\see axisRect, axisRects
*/
int QCustomPlot::axisRectCount() const
{
return axisRects().size();
}
/*!
Returns the axis rect with \a index.
Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were
added, all of them may be accessed with this function in a linear fashion (even when they are
nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout).
\see axisRectCount, axisRects
*/
QCPAxisRect *QCustomPlot::axisRect(int index) const
{
const QList<QCPAxisRect*> rectList = axisRects();
if (index >= 0 && index < rectList.size())
{
return rectList.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index;
return 0;
}
}
/*!
Returns all axis rects in the plot.
\see axisRectCount, axisRect
*/
QList<QCPAxisRect*> QCustomPlot::axisRects() const
{
QList<QCPAxisRect*> result;
QStack<QCPLayoutElement*> elementStack;
if (mPlotLayout)
elementStack.push(mPlotLayout);
while (!elementStack.isEmpty())
{
foreach (QCPLayoutElement *element, elementStack.pop()->elements(false))
{
if (element)
{
elementStack.push(element);
if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(element))
result.append(ar);
}
}
}
return result;
}
/*!
Returns the layout element at pixel position \a pos. If there is no element at that position,
returns 0.
Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on
any of its parent elements is set to false, it will not be considered.
\see itemAt, plottableAt
*/
QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const
{
QCPLayoutElement *currentElement = mPlotLayout;
bool searchSubElements = true;
while (searchSubElements && currentElement)
{
searchSubElements = false;
foreach (QCPLayoutElement *subElement, currentElement->elements(false))
{
if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0)
{
currentElement = subElement;
searchSubElements = true;
break;
}
}
}
return currentElement;
}
/*!
Returns the axes that currently have selected parts, i.e. whose selection state is not \ref
QCPAxis::spNone.
\see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts,
QCPAxis::setSelectableParts
*/
QList<QCPAxis*> QCustomPlot::selectedAxes() const
{
QList<QCPAxis*> result, allAxes;
foreach (QCPAxisRect *rect, axisRects())
allAxes << rect->axes();
foreach (QCPAxis *axis, allAxes)
{
if (axis->selectedParts() != QCPAxis::spNone)
result.append(axis);
}
return result;
}
/*!
Returns the legends that currently have selected parts, i.e. whose selection state is not \ref
QCPLegend::spNone.
\see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts,
QCPLegend::setSelectableParts, QCPLegend::selectedItems
*/
QList<QCPLegend*> QCustomPlot::selectedLegends() const
{
QList<QCPLegend*> result;
QStack<QCPLayoutElement*> elementStack;
if (mPlotLayout)
elementStack.push(mPlotLayout);
while (!elementStack.isEmpty())
{
foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false))
{
if (subElement)
{
elementStack.push(subElement);
if (QCPLegend *leg = qobject_cast<QCPLegend*>(subElement))
{
if (leg->selectedParts() != QCPLegend::spNone)
result.append(leg);
}
}
}
}
return result;
}
/*!
Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot.
Since calling this function is not a user interaction, this does not emit the \ref
selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the
objects were previously selected.
\see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends
*/
void QCustomPlot::deselectAll()
{
foreach (QCPLayer *layer, mLayers)
{
foreach (QCPLayerable *layerable, layer->children())
layerable->deselectEvent(0);
}
}
/*!
Causes a complete replot into the internal buffer. Finally, update() is called, to redraw the
buffer on the QCustomPlot widget surface. This is the method that must be called to make changes,
for example on the axis ranges or data points of graphs, visible.
Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the
QCustomPlot widget and user interactions (object selection and range dragging/zooming).
Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref
afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two
signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite
recursion.
*/
void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority)
{
if (mReplotting) // incase signals loop back to replot slot
return;
mReplotting = true;
emit beforeReplot();
mPaintBuffer.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent);
QCPPainter painter;
painter.begin(&mPaintBuffer);
if (painter.isActive())
{
painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem
if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush)
painter.fillRect(mViewport, mBackgroundBrush);
draw(&painter);
painter.end();
if ((refreshPriority == rpHint && mPlottingHints.testFlag(QCP::phForceRepaint)) || refreshPriority==rpImmediate)
repaint();
else
update();
} else // might happen if QCustomPlot has width or height zero
qDebug() << Q_FUNC_INFO << "Couldn't activate painter on buffer. This usually happens because QCustomPlot has width or height zero.";
emit afterReplot();
mReplotting = false;
}
/*!
Rescales the axes such that all plottables (like graphs) in the plot are fully visible.
if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true
(QCPLayerable::setVisible), will be used to rescale the axes.
\see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale
*/
void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables)
{
QList<QCPAxis*> allAxes;
foreach (QCPAxisRect *rect, axisRects())
allAxes << rect->axes();
foreach (QCPAxis *axis, allAxes)
axis->rescale(onlyVisiblePlottables);
}
/*!
Saves a PDF with the vectorized plot to the file \a fileName. The axis ratio as well as the scale
of texts and lines will be derived from the specified \a width and \a height. This means, the
output will look like the normal on-screen output of a QCustomPlot widget with the corresponding
pixel width and height. If either \a width or \a height is zero, the exported image will have the
same dimensions as the QCustomPlot widget currently has.
\a noCosmeticPen disables the use of cosmetic pens when drawing to the PDF file. Cosmetic pens
are pens with numerical width 0, which are always drawn as a one pixel wide line, no matter what
zoom factor is set in the PDF-Viewer. For more information about cosmetic pens, see the QPainter
and QPen documentation.
The objects of the plot will appear in the current selection state. If you don't want any
selected objects to be painted in their selected look, deselect everything with \ref deselectAll
before calling this function.
Returns true on success.
\warning
\li If you plan on editing the exported PDF file with a vector graphics editor like
Inkscape, it is advised to set \a noCosmeticPen to true to avoid losing those cosmetic lines
(which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks).
\li If calling this function inside the constructor of the parent of the QCustomPlot widget
(i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
function uses the current width and height of the QCustomPlot widget. However, in Qt, these
aren't defined yet inside the constructor, so you would get an image that has strange
widths/heights.
\a pdfCreator and \a pdfTitle may be used to set the according metadata fields in the resulting
PDF file.
\note On Android systems, this method does nothing and issues an according qDebug warning
message. This is also the case if for other reasons the define flag QT_NO_PRINTER is set.
\see savePng, saveBmp, saveJpg, saveRastered
*/
bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width, int height, const QString &pdfCreator, const QString &pdfTitle)
{
bool success = false;
#ifdef QT_NO_PRINTER
Q_UNUSED(fileName)
Q_UNUSED(noCosmeticPen)
Q_UNUSED(width)
Q_UNUSED(height)
Q_UNUSED(pdfCreator)
Q_UNUSED(pdfTitle)
qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created.";
#else
int newWidth, newHeight;
if (width == 0 || height == 0)
{
newWidth = this->width();
newHeight = this->height();
} else
{
newWidth = width;
newHeight = height;
}
QPrinter printer(QPrinter::ScreenResolution);
printer.setOutputFileName(fileName);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setColorMode(QPrinter::Color);
printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator);
printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle);
QRect oldViewport = viewport();
setViewport(QRect(0, 0, newWidth, newHeight));
#if QT_VERSION < QT_VERSION_CHECK(5, 3, 0)
printer.setFullPage(true);
printer.setPaperSize(viewport().size(), QPrinter::DevicePixel);
#else
QPageLayout pageLayout;
pageLayout.setMode(QPageLayout::FullPageMode);
pageLayout.setOrientation(QPageLayout::Portrait);
pageLayout.setMargins(QMarginsF(0, 0, 0, 0));
pageLayout.setPageSize(QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch));
printer.setPageLayout(pageLayout);
#endif
QCPPainter printpainter;
if (printpainter.begin(&printer))
{
printpainter.setMode(QCPPainter::pmVectorized);
printpainter.setMode(QCPPainter::pmNoCaching);
printpainter.setMode(QCPPainter::pmNonCosmetic, noCosmeticPen);
printpainter.setWindow(mViewport);
if (mBackgroundBrush.style() != Qt::NoBrush &&
mBackgroundBrush.color() != Qt::white &&
mBackgroundBrush.color() != Qt::transparent &&
mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent
printpainter.fillRect(viewport(), mBackgroundBrush);
draw(&printpainter);
printpainter.end();
success = true;
}
setViewport(oldViewport);
#endif // QT_NO_PRINTER
return success;
}
/*!
Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width
and \a height in pixels. If either \a width or \a height is zero, the exported image will have
the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not
scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter.
For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
200*200 pixel resolution.
If you use a high scaling factor, it is recommended to enable antialiasing for all elements via
temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
QCustomPlot to place objects with sub-pixel accuracy.
\warning If calling this function inside the constructor of the parent of the QCustomPlot widget
(i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
function uses the current width and height of the QCustomPlot widget. However, in Qt, these
aren't defined yet inside the constructor, so you would get an image that has strange
widths/heights.
The objects of the plot will appear in the current selection state. If you don't want any selected
objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
this function.
If you want the PNG to have a transparent background, call \ref setBackground(const QBrush
&brush) with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving.
PNG compression can be controlled with the \a quality parameter which must be between 0 and 100 or
-1 to use the default setting.
Returns true on success. If this function fails, most likely the PNG format isn't supported by
the system, see Qt docs about QImageWriter::supportedImageFormats().
\see savePdf, saveBmp, saveJpg, saveRastered
*/
bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality)
{
return saveRastered(fileName, width, height, scale, "PNG", quality);
}
/*!
Saves a JPG image file to \a fileName on disc. The output plot will have the dimensions \a width
and \a height in pixels. If either \a width or \a height is zero, the exported image will have
the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not
scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter.
For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
200*200 pixel resolution.
If you use a high scaling factor, it is recommended to enable antialiasing for all elements via
temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
QCustomPlot to place objects with sub-pixel accuracy.
\warning If calling this function inside the constructor of the parent of the QCustomPlot widget
(i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
function uses the current width and height of the QCustomPlot widget. However, in Qt, these
aren't defined yet inside the constructor, so you would get an image that has strange
widths/heights.
The objects of the plot will appear in the current selection state. If you don't want any selected
objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
this function.
JPG compression can be controlled with the \a quality parameter which must be between 0 and 100 or
-1 to use the default setting.
Returns true on success. If this function fails, most likely the JPG format isn't supported by
the system, see Qt docs about QImageWriter::supportedImageFormats().
\see savePdf, savePng, saveBmp, saveRastered
*/
bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality)
{
return saveRastered(fileName, width, height, scale, "JPG", quality);
}
/*!
Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width
and \a height in pixels. If either \a width or \a height is zero, the exported image will have
the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not
scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter.
For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
200*200 pixel resolution.
If you use a high scaling factor, it is recommended to enable antialiasing for all elements via
temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
QCustomPlot to place objects with sub-pixel accuracy.
\warning If calling this function inside the constructor of the parent of the QCustomPlot widget
(i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
function uses the current width and height of the QCustomPlot widget. However, in Qt, these
aren't defined yet inside the constructor, so you would get an image that has strange
widths/heights.
The objects of the plot will appear in the current selection state. If you don't want any selected
objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
this function.
Returns true on success. If this function fails, most likely the BMP format isn't supported by
the system, see Qt docs about QImageWriter::supportedImageFormats().
\see savePdf, savePng, saveJpg, saveRastered
*/
bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale)
{
return saveRastered(fileName, width, height, scale, "BMP");
}
/*! \internal
Returns a minimum size hint that corresponds to the minimum size of the top level layout
(\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum
size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot.
This is especially important, when placed in a QLayout where other components try to take in as
much space as possible (e.g. QMdiArea).
*/
QSize QCustomPlot::minimumSizeHint() const
{
return mPlotLayout->minimumSizeHint();
}
/*! \internal
Returns a size hint that is the same as \ref minimumSizeHint.
*/
QSize QCustomPlot::sizeHint() const
{
return mPlotLayout->minimumSizeHint();
}
/*! \internal
Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but
draws the internal buffer on the widget surface.
*/
void QCustomPlot::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter painter(this);
painter.drawPixmap(0, 0, mPaintBuffer);
}
/*! \internal
Event handler for a resize of the QCustomPlot widget. Causes the internal buffer to be resized to
the new size. The viewport (which becomes the outer rect of mPlotLayout) is resized
appropriately. Finally a \ref replot is performed.
*/
void QCustomPlot::resizeEvent(QResizeEvent *event)
{
// resize and repaint the buffer:
mPaintBuffer = QPixmap(event->size());
setViewport(rect());
replot(rpQueued); // queued update is important here, to prevent painting issues in some contexts
}
/*! \internal
Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then emits
the specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref
axisDoubleClick, etc.). Finally determines the affected layout element and forwards the event to
it.
\see mousePressEvent, mouseReleaseEvent
*/
void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event)
{
emit mouseDoubleClick(event);
QVariant details;
QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details);
// emit specialized object double click signals:
if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(clickedLayerable))
emit plottableDoubleClick(ap, event);
else if (QCPAxis *ax = qobject_cast<QCPAxis*>(clickedLayerable))
emit axisDoubleClick(ax, details.value<QCPAxis::SelectablePart>(), event);
else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(clickedLayerable))
emit itemDoubleClick(ai, event);
else if (QCPLegend *lg = qobject_cast<QCPLegend*>(clickedLayerable))
emit legendDoubleClick(lg, 0, event);
else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(clickedLayerable))
emit legendDoubleClick(li->parentLegend(), li, event);
else if (QCPPlotTitle *pt = qobject_cast<QCPPlotTitle*>(clickedLayerable))
emit titleDoubleClick(event, pt);
// call double click event of affected layout element:
if (QCPLayoutElement *el = layoutElementAt(event->pos()))
el->mouseDoubleClickEvent(event);
// call release event of affected layout element (as in mouseReleaseEvent, since the mouseDoubleClick replaces the second release event in double click case):
if (mMouseEventElement)
{
mMouseEventElement->mouseReleaseEvent(event);
mMouseEventElement = 0;
}
//QWidget::mouseDoubleClickEvent(event); don't call base class implementation because it would just cause a mousePress/ReleaseEvent, which we don't want.
}
/*! \internal
Event handler for when a mouse button is pressed. Emits the mousePress signal. Then determines
the affected layout element and forwards the event to it.
\see mouseMoveEvent, mouseReleaseEvent
*/
void QCustomPlot::mousePressEvent(QMouseEvent *event)
{
emit mousePress(event);
mMousePressPos = event->pos(); // need this to determine in releaseEvent whether it was a click (no position change between press and release)
// call event of affected layout element:
mMouseEventElement = layoutElementAt(event->pos());
if (mMouseEventElement)
mMouseEventElement->mousePressEvent(event);
QWidget::mousePressEvent(event);
}
/*! \internal
Event handler for when the cursor is moved. Emits the \ref mouseMove signal.
If a layout element has mouse capture focus (a mousePressEvent happened on top of the layout
element before), the mouseMoveEvent is forwarded to that element.
\see mousePressEvent, mouseReleaseEvent
*/
void QCustomPlot::mouseMoveEvent(QMouseEvent *event)
{
emit mouseMove(event);
// call event of affected layout element:
if (mMouseEventElement)
mMouseEventElement->mouseMoveEvent(event);
QWidget::mouseMoveEvent(event);
}
/*! \internal
Event handler for when a mouse button is released. Emits the \ref mouseRelease signal.
If the mouse was moved less than a certain threshold in any direction since the \ref
mousePressEvent, it is considered a click which causes the selection mechanism (if activated via
\ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse
click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.)
If a layout element has mouse capture focus (a \ref mousePressEvent happened on top of the layout
element before), the \ref mouseReleaseEvent is forwarded to that element.
\see mousePressEvent, mouseMoveEvent
*/
void QCustomPlot::mouseReleaseEvent(QMouseEvent *event)
{
emit mouseRelease(event);
bool doReplot = false;
if ((mMousePressPos-event->pos()).manhattanLength() < 5) // determine whether it was a click operation
{
if (event->button() == Qt::LeftButton)
{
// handle selection mechanism:
QVariant details;
QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details);
bool selectionStateChanged = false;
bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier);
// deselect all other layerables if not additive selection:
if (!additive)
{
foreach (QCPLayer *layer, mLayers)
{
foreach (QCPLayerable *layerable, layer->children())
{
if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory()))
{
bool selChanged = false;
layerable->deselectEvent(&selChanged);
selectionStateChanged |= selChanged;
}
}
}
}
if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory()))
{
// a layerable was actually clicked, call its selectEvent:
bool selChanged = false;
clickedLayerable->selectEvent(event, additive, details, &selChanged);
selectionStateChanged |= selChanged;
}
if (selectionStateChanged)
{
doReplot = true;
emit selectionChangedByUser();
}
}
// emit specialized object click signals:
QVariant details;
QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details); // for these signals, selectability is ignored, that's why we call this again with onlySelectable set to false
if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(clickedLayerable))
emit plottableClick(ap, event);
else if (QCPAxis *ax = qobject_cast<QCPAxis*>(clickedLayerable))
emit axisClick(ax, details.value<QCPAxis::SelectablePart>(), event);
else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(clickedLayerable))
emit itemClick(ai, event);
else if (QCPLegend *lg = qobject_cast<QCPLegend*>(clickedLayerable))
emit legendClick(lg, 0, event);
else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(clickedLayerable))
emit legendClick(li->parentLegend(), li, event);
else if (QCPPlotTitle *pt = qobject_cast<QCPPlotTitle*>(clickedLayerable))
emit titleClick(event, pt);
}
// call event of affected layout element:
if (mMouseEventElement)
{
mMouseEventElement->mouseReleaseEvent(event);
mMouseEventElement = 0;
}
if (doReplot || noAntialiasingOnDrag())
replot();
QWidget::mouseReleaseEvent(event);
}
/*! \internal
Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then
determines the affected layout element and forwards the event to it.
*/
void QCustomPlot::wheelEvent(QWheelEvent *event)
{
emit mouseWheel(event);
// call event of affected layout element:
if (QCPLayoutElement *el = layoutElementAt(event->pos()))
el->wheelEvent(event);
QWidget::wheelEvent(event);
}
/*! \internal
This is the main draw function. It draws the entire plot, including background pixmap, with the
specified \a painter. Note that it does not fill the background with the background brush (as the
user may specify with \ref setBackground(const QBrush &brush)), this is up to the respective
functions calling this method (e.g. \ref replot, \ref toPixmap and \ref toPainter).
*/
void QCustomPlot::draw(QCPPainter *painter)
{
// run through layout phases:
mPlotLayout->update(QCPLayoutElement::upPreparation);
mPlotLayout->update(QCPLayoutElement::upMargins);
mPlotLayout->update(QCPLayoutElement::upLayout);
// draw viewport background pixmap:
drawBackground(painter);
// draw all layered objects (grid, axes, plottables, items, legend,...):
foreach (QCPLayer *layer, mLayers)
{
foreach (QCPLayerable *child, layer->children())
{
if (child->realVisibility())
{
painter->save();
painter->setClipRect(child->clipRect().translated(0, -1));
child->applyDefaultAntialiasingHint(painter);
child->draw(painter);
painter->restore();
}
}
}
/* Debug code to draw all layout element rects
foreach (QCPLayoutElement* el, findChildren<QCPLayoutElement*>())
{
painter->setBrush(Qt::NoBrush);
painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine));
painter->drawRect(el->rect());
painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine));
painter->drawRect(el->outerRect());
}
*/
}
/*! \internal
Draws the viewport background pixmap of the plot.
If a pixmap was provided via \ref setBackground, this function buffers the scaled version
depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
the viewport with the provided \a painter. The scaled version is buffered in
mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
the axis rect has changed in a way that requires a rescale of the background pixmap (this is
dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
set.
Note that this function does not draw a fill with the background brush (\ref setBackground(const
QBrush &brush)) beneath the pixmap.
\see setBackground, setBackgroundScaled, setBackgroundScaledMode
*/
void QCustomPlot::drawBackground(QCPPainter *painter)
{
// Note: background color is handled in individual replot/save functions
// draw background pixmap (on top of fill, if brush specified):
if (!mBackgroundPixmap.isNull())
{
if (mBackgroundScaled)
{
// check whether mScaledBackground needs to be updated:
QSize scaledSize(mBackgroundPixmap.size());
scaledSize.scale(mViewport.size(), mBackgroundScaledMode);
if (mScaledBackgroundPixmap.size() != scaledSize)
mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect());
} else
{
painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()));
}
}
}
/*! \internal
This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot
so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly.
*/
void QCustomPlot::axisRemoved(QCPAxis *axis)
{
if (xAxis == axis)
xAxis = 0;
if (xAxis2 == axis)
xAxis2 = 0;
if (yAxis == axis)
yAxis = 0;
if (yAxis2 == axis)
yAxis2 = 0;
// Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers
}
/*! \internal
This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so
it may clear its QCustomPlot::legend member accordingly.
*/
void QCustomPlot::legendRemoved(QCPLegend *legend)
{
if (this->legend == legend)
this->legend = 0;
}
/*! \internal
Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called
after every operation that changes the layer indices, like layer removal, layer creation, layer
moving.
*/
void QCustomPlot::updateLayerIndices() const
{
for (int i=0; i<mLayers.size(); ++i)
mLayers.at(i)->mIndex = i;
}
/*! \internal
Returns the layerable at pixel position \a pos. If \a onlySelectable is set to true, only those
layerables that are selectable will be considered. (Layerable subclasses communicate their
selectability via the QCPLayerable::selectTest method, by returning -1.)
\a selectionDetails is an output parameter that contains selection specifics of the affected
layerable. This is useful if the respective layerable shall be given a subsequent
QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
information about which part of the layerable was hit, in multi-part layerables (e.g.
QCPAxis::SelectablePart).
*/
QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const
{
for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex)
{
const QList<QCPLayerable*> layerables = mLayers.at(layerIndex)->children();
double minimumDistance = selectionTolerance()*1.1;
QCPLayerable *minimumDistanceLayerable = 0;
for (int i=layerables.size()-1; i>=0; --i)
{
if (!layerables.at(i)->realVisibility())
continue;
QVariant details;
double dist = layerables.at(i)->selectTest(pos, onlySelectable, &details);
if (dist >= 0 && dist < minimumDistance)
{
minimumDistance = dist;
minimumDistanceLayerable = layerables.at(i);
if (selectionDetails) *selectionDetails = details;
}
}
if (minimumDistance < selectionTolerance())
return minimumDistanceLayerable;
}
return 0;
}
/*!
Saves the plot to a rastered image file \a fileName in the image format \a format. The plot is
sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead
to a full resolution file with width 200.) If the \a format supports compression, \a quality may
be between 0 and 100 to control it.
Returns true on success. If this function fails, most likely the given \a format isn't supported
by the system, see Qt docs about QImageWriter::supportedImageFormats().
\see saveBmp, saveJpg, savePng, savePdf
*/
bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality)
{
QPixmap buffer = toPixmap(width, height, scale);
if (!buffer.isNull())
return buffer.save(fileName, format, quality);
else
return false;
}
/*!
Renders the plot to a pixmap and returns it.
The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and
scale 2.0 lead to a full resolution pixmap with width 200.)
\see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf
*/
QPixmap QCustomPlot::toPixmap(int width, int height, double scale)
{
// this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too.
int newWidth, newHeight;
if (width == 0 || height == 0)
{
newWidth = this->width();
newHeight = this->height();
} else
{
newWidth = width;
newHeight = height;
}
int scaledWidth = qRound(scale*newWidth);
int scaledHeight = qRound(scale*newHeight);
QPixmap result(scaledWidth, scaledHeight);
result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later
QCPPainter painter;
painter.begin(&result);
if (painter.isActive())
{
QRect oldViewport = viewport();
setViewport(QRect(0, 0, newWidth, newHeight));
painter.setMode(QCPPainter::pmNoCaching);
if (!qFuzzyCompare(scale, 1.0))
{
if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales
painter.setMode(QCPPainter::pmNonCosmetic);
painter.scale(scale, scale);
}
if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) // solid fills were done a few lines above with QPixmap::fill
painter.fillRect(mViewport, mBackgroundBrush);
draw(&painter);
setViewport(oldViewport);
painter.end();
} else // might happen if pixmap has width or height zero
{
qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap";
return QPixmap();
}
return result;
}
/*!
Renders the plot using the passed \a painter.
The plot is sized to \a width and \a height in pixels. If the \a painter's scale is not 1.0, the resulting plot will
appear scaled accordingly.
\note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter
on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with
the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter.
\see toPixmap
*/
void QCustomPlot::toPainter(QCPPainter *painter, int width, int height)
{
// this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too.
int newWidth, newHeight;
if (width == 0 || height == 0)
{
newWidth = this->width();
newHeight = this->height();
} else
{
newWidth = width;
newHeight = height;
}
if (painter->isActive())
{
QRect oldViewport = viewport();
setViewport(QRect(0, 0, newWidth, newHeight));
painter->setMode(QCPPainter::pmNoCaching);
if (mBackgroundBrush.style() != Qt::NoBrush) // unlike in toPixmap, we can't do QPixmap::fill for Qt::SolidPattern brush style, so we also draw solid fills with fillRect here
painter->fillRect(mViewport, mBackgroundBrush);
draw(painter);
setViewport(oldViewport);
} else
qDebug() << Q_FUNC_INFO << "Passed painter is not active";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPColorGradient
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPColorGradient
\brief Defines a color gradient for use with e.g. \ref QCPColorMap
This class describes a color gradient which can be used to encode data with color. For example,
QCPColorMap and QCPColorScale have \ref QCPColorMap::setGradient "setGradient" methods which
take an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color)
with a \a position from 0 to 1. In between these defined color positions, the
color will be interpolated linearly either in RGB or HSV space, see \ref setColorInterpolation.
Alternatively, load one of the preset color gradients shown in the image below, with \ref
loadPreset, or by directly specifying the preset in the constructor.
\image html QCPColorGradient.png
The fact that the \ref QCPColorGradient(GradientPreset preset) constructor allows directly
converting a \ref GradientPreset to a QCPColorGradient, you can also directly pass \ref
GradientPreset to all the \a setGradient methods, e.g.:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorgradient-setgradient
The total number of levels used in the gradient can be set with \ref setLevelCount. Whether the
color gradient shall be applied periodically (wrapping around) to data values that lie outside
the data range specified on the plottable instance can be controlled with \ref setPeriodic.
*/
/*!
Constructs a new QCPColorGradient initialized with the colors and color interpolation according
to \a preset.
The color level count is initialized to 350.
*/
QCPColorGradient::QCPColorGradient(GradientPreset preset) :
mLevelCount(350),
mColorInterpolation(ciRGB),
mPeriodic(false),
mColorBufferInvalidated(true)
{
mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
loadPreset(preset);
}
/* undocumented operator */
bool QCPColorGradient::operator==(const QCPColorGradient &other) const
{
return ((other.mLevelCount == this->mLevelCount) &&
(other.mColorInterpolation == this->mColorInterpolation) &&
(other.mPeriodic == this->mPeriodic) &&
(other.mColorStops == this->mColorStops));
}
/*!
Sets the number of discretization levels of the color gradient to \a n. The default is 350 which
is typically enough to create a smooth appearance.
\image html QCPColorGradient-levelcount.png
*/
void QCPColorGradient::setLevelCount(int n)
{
if (n < 2)
{
qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n;
n = 2;
}
if (n != mLevelCount)
{
mLevelCount = n;
mColorBufferInvalidated = true;
}
}
/*!
Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the
colors are the values of the passed QMap \a colorStops. In between these color stops, the color
is interpolated according to \ref setColorInterpolation.
A more convenient way to create a custom gradient may be to clear all color stops with \ref
clearColorStops and then adding them one by one with \ref setColorStopAt.
\see clearColorStops
*/
void QCPColorGradient::setColorStops(const QMap<double, QColor> &colorStops)
{
mColorStops = colorStops;
mColorBufferInvalidated = true;
}
/*!
Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between
these color stops, the color is interpolated according to \ref setColorInterpolation.
\see setColorStops, clearColorStops
*/
void QCPColorGradient::setColorStopAt(double position, const QColor &color)
{
mColorStops.insert(position, color);
mColorBufferInvalidated = true;
}
/*!
Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be
interpolated linearly in RGB or in HSV color space.
For example, a sweep in RGB space from red to green will have a muddy brown intermediate color,
whereas in HSV space the intermediate color is yellow.
*/
void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation)
{
if (interpolation != mColorInterpolation)
{
mColorInterpolation = interpolation;
mColorBufferInvalidated = true;
}
}
/*!
Sets whether data points that are outside the configured data range (e.g. \ref
QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether
they all have the same color, corresponding to the respective gradient boundary color.
\image html QCPColorGradient-periodic.png
As shown in the image above, gradients that have the same start and end color are especially
suitable for a periodic gradient mapping, since they produce smooth color transitions throughout
the color map. A preset that has this property is \ref gpHues.
In practice, using periodic color gradients makes sense when the data corresponds to a periodic
dimension, such as an angle or a phase. If this is not the case, the color encoding might become
ambiguous, because multiple different data values are shown as the same color.
*/
void QCPColorGradient::setPeriodic(bool enabled)
{
mPeriodic = enabled;
}
/*!
This method is used to quickly convert a \a data array to colors. The colors will be output in
the array \a scanLine. Both \a data and \a scanLine must have the length \a n when passed to this
function. The data range that shall be used for mapping the data value to the gradient is passed
in \a range. \a logarithmic indicates whether the data values shall be mapped to colors
logarithmically.
if \a data actually contains 2D-data linearized via <tt>[row*columnCount + column]</tt>, you can
set \a dataIndexFactor to <tt>columnCount</tt> to convert a column instead of a row of the data
array, in \a scanLine. \a scanLine will remain a regular (1D) array. This works because \a data
is addressed <tt>data[i*dataIndexFactor]</tt>.
*/
void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
{
// If you change something here, make sure to also adapt ::color()
if (!data)
{
qDebug() << Q_FUNC_INFO << "null pointer given as data";
return;
}
if (!scanLine)
{
qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
return;
}
if (mColorBufferInvalidated)
updateColorBuffer();
if (!logarithmic)
{
const double posToIndexFactor = (mLevelCount-1)/range.size();
if (mPeriodic)
{
for (int i=0; i<n; ++i)
{
int index = (int)((data[dataIndexFactor*i]-range.lower)*posToIndexFactor) % mLevelCount;
if (index < 0)
index += mLevelCount;
scanLine[i] = mColorBuffer.at(index);
}
} else
{
for (int i=0; i<n; ++i)
{
int index = (data[dataIndexFactor*i]-range.lower)*posToIndexFactor;
if (index < 0)
index = 0;
else if (index >= mLevelCount)
index = mLevelCount-1;
scanLine[i] = mColorBuffer.at(index);
}
}
} else // logarithmic == true
{
if (mPeriodic)
{
for (int i=0; i<n; ++i)
{
int index = (int)(qLn(data[dataIndexFactor*i]/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1)) % mLevelCount;
if (index < 0)
index += mLevelCount;
scanLine[i] = mColorBuffer.at(index);
}
} else
{
for (int i=0; i<n; ++i)
{
int index = qLn(data[dataIndexFactor*i]/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1);
if (index < 0)
index = 0;
else if (index >= mLevelCount)
index = mLevelCount-1;
scanLine[i] = mColorBuffer.at(index);
}
}
}
}
/*! \internal
This method is used to colorize a single data value given in \a position, to colors. The data
range that shall be used for mapping the data value to the gradient is passed in \a range. \a
logarithmic indicates whether the data value shall be mapped to a color logarithmically.
If an entire array of data values shall be converted, rather use \ref colorize, for better
performance.
*/
QRgb QCPColorGradient::color(double position, const QCPRange &range, bool logarithmic)
{
// If you change something here, make sure to also adapt ::colorize()
if (mColorBufferInvalidated)
updateColorBuffer();
int index = 0;
if (!logarithmic)
index = (position-range.lower)*(mLevelCount-1)/range.size();
else
index = qLn(position/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1);
if (mPeriodic)
{
index = index % mLevelCount;
if (index < 0)
index += mLevelCount;
} else
{
if (index < 0)
index = 0;
else if (index >= mLevelCount)
index = mLevelCount-1;
}
return mColorBuffer.at(index);
}
/*!
Clears the current color stops and loads the specified \a preset. A preset consists of predefined
color stops and the corresponding color interpolation method.
The available presets are:
\image html QCPColorGradient.png
*/
void QCPColorGradient::loadPreset(GradientPreset preset)
{
clearColorStops();
switch (preset)
{
case gpGrayscale:
setColorInterpolation(ciRGB);
setColorStopAt(0, Qt::black);
setColorStopAt(1, Qt::white);
break;
case gpHot:
setColorInterpolation(ciRGB);
setColorStopAt(0, QColor(50, 0, 0));
setColorStopAt(0.2, QColor(180, 10, 0));
setColorStopAt(0.4, QColor(245, 50, 0));
setColorStopAt(0.6, QColor(255, 150, 10));
setColorStopAt(0.8, QColor(255, 255, 50));
setColorStopAt(1, QColor(255, 255, 255));
break;
case gpCold:
setColorInterpolation(ciRGB);
setColorStopAt(0, QColor(0, 0, 50));
setColorStopAt(0.2, QColor(0, 10, 180));
setColorStopAt(0.4, QColor(0, 50, 245));
setColorStopAt(0.6, QColor(10, 150, 255));
setColorStopAt(0.8, QColor(50, 255, 255));
setColorStopAt(1, QColor(255, 255, 255));
break;
case gpNight:
setColorInterpolation(ciHSV);
setColorStopAt(0, QColor(10, 20, 30));
setColorStopAt(1, QColor(250, 255, 250));
break;
case gpCandy:
setColorInterpolation(ciHSV);
setColorStopAt(0, QColor(0, 0, 255));
setColorStopAt(1, QColor(255, 250, 250));
break;
case gpGeography:
setColorInterpolation(ciRGB);
setColorStopAt(0, QColor(70, 170, 210));
setColorStopAt(0.20, QColor(90, 160, 180));
setColorStopAt(0.25, QColor(45, 130, 175));
setColorStopAt(0.30, QColor(100, 140, 125));
setColorStopAt(0.5, QColor(100, 140, 100));
setColorStopAt(0.6, QColor(130, 145, 120));
setColorStopAt(0.7, QColor(140, 130, 120));
setColorStopAt(0.9, QColor(180, 190, 190));
setColorStopAt(1, QColor(210, 210, 230));
break;
case gpIon:
setColorInterpolation(ciHSV);
setColorStopAt(0, QColor(50, 10, 10));
setColorStopAt(0.45, QColor(0, 0, 255));
setColorStopAt(0.8, QColor(0, 255, 255));
setColorStopAt(1, QColor(0, 255, 0));
break;
case gpThermal:
setColorInterpolation(ciRGB);
setColorStopAt(0, QColor(0, 0, 50));
setColorStopAt(0.15, QColor(20, 0, 120));
setColorStopAt(0.33, QColor(200, 30, 140));
setColorStopAt(0.6, QColor(255, 100, 0));
setColorStopAt(0.85, QColor(255, 255, 40));
setColorStopAt(1, QColor(255, 255, 255));
break;
case gpPolar:
setColorInterpolation(ciRGB);
setColorStopAt(0, QColor(50, 255, 255));
setColorStopAt(0.18, QColor(10, 70, 255));
setColorStopAt(0.28, QColor(10, 10, 190));
setColorStopAt(0.5, QColor(0, 0, 0));
setColorStopAt(0.72, QColor(190, 10, 10));
setColorStopAt(0.82, QColor(255, 70, 10));
setColorStopAt(1, QColor(255, 255, 50));
break;
case gpSpectrum:
setColorInterpolation(ciHSV);
setColorStopAt(0, QColor(50, 0, 50));
setColorStopAt(0.15, QColor(0, 0, 255));
setColorStopAt(0.35, QColor(0, 255, 255));
setColorStopAt(0.6, QColor(255, 255, 0));
setColorStopAt(0.75, QColor(255, 30, 0));
setColorStopAt(1, QColor(50, 0, 0));
break;
case gpJet:
setColorInterpolation(ciRGB);
setColorStopAt(0, QColor(0, 0, 100));
setColorStopAt(0.15, QColor(0, 50, 255));
setColorStopAt(0.35, QColor(0, 255, 255));
setColorStopAt(0.65, QColor(255, 255, 0));
setColorStopAt(0.85, QColor(255, 30, 0));
setColorStopAt(1, QColor(100, 0, 0));
break;
case gpHues:
setColorInterpolation(ciHSV);
setColorStopAt(0, QColor(255, 0, 0));
setColorStopAt(1.0/3.0, QColor(0, 0, 255));
setColorStopAt(2.0/3.0, QColor(0, 255, 0));
setColorStopAt(1, QColor(255, 0, 0));
break;
}
}
/*!
Clears all color stops.
\see setColorStops, setColorStopAt
*/
void QCPColorGradient::clearColorStops()
{
mColorStops.clear();
mColorBufferInvalidated = true;
}
/*!
Returns an inverted gradient. The inverted gradient has all properties as this \ref
QCPColorGradient, but the order of the color stops is inverted.
\see setColorStops, setColorStopAt
*/
QCPColorGradient QCPColorGradient::inverted() const
{
QCPColorGradient result(*this);
result.clearColorStops();
for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it)
result.setColorStopAt(1.0-it.key(), it.value());
return result;
}
/*! \internal
Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly
convert positions to colors. This is where the interpolation between color stops is calculated.
*/
void QCPColorGradient::updateColorBuffer()
{
if (mColorBuffer.size() != mLevelCount)
mColorBuffer.resize(mLevelCount);
if (mColorStops.size() > 1)
{
double indexToPosFactor = 1.0/(double)(mLevelCount-1);
for (int i=0; i<mLevelCount; ++i)
{
double position = i*indexToPosFactor;
QMap<double, QColor>::const_iterator it = mColorStops.lowerBound(position);
if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop
{
mColorBuffer[i] = (it-1).value().rgb();
} else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop
{
mColorBuffer[i] = it.value().rgb();
} else // position is in between stops (or on an intermediate stop), interpolate color
{
QMap<double, QColor>::const_iterator high = it;
QMap<double, QColor>::const_iterator low = it-1;
double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1
switch (mColorInterpolation)
{
case ciRGB:
{
mColorBuffer[i] = qRgb((1-t)*low.value().red() + t*high.value().red(),
(1-t)*low.value().green() + t*high.value().green(),
(1-t)*low.value().blue() + t*high.value().blue());
break;
}
case ciHSV:
{
QColor lowHsv = low.value().toHsv();
QColor highHsv = high.value().toHsv();
double hue = 0;
double hueDiff = highHsv.hueF()-lowHsv.hueF();
if (hueDiff > 0.5)
hue = lowHsv.hueF() - t*(1.0-hueDiff);
else if (hueDiff < -0.5)
hue = lowHsv.hueF() + t*(1.0+hueDiff);
else
hue = lowHsv.hueF() + t*hueDiff;
if (hue < 0) hue += 1.0;
else if (hue >= 1.0) hue -= 1.0;
mColorBuffer[i] = QColor::fromHsvF(hue, (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(), (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
break;
}
}
}
}
} else if (mColorStops.size() == 1)
{
mColorBuffer.fill(mColorStops.constBegin().value().rgb());
} else // mColorStops is empty, fill color buffer with black
{
mColorBuffer.fill(qRgb(0, 0, 0));
}
mColorBufferInvalidated = false;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAxisRect
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAxisRect
\brief Holds multiple axes and arranges them in a rectangular shape.
This class represents an axis rect, a rectangular area that is bounded on all sides with an
arbitrary number of axes.
Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the
layout system allows to have multiple axis rects, e.g. arranged in a grid layout
(QCustomPlot::plotLayout).
By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be
accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index.
If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be
invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref
addAxes. To remove an axis, use \ref removeAxis.
The axis rect layerable itself only draws a background pixmap or color, if specified (\ref
setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an
explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be
placed on other layers, independently of the axis rect.
Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref
insetLayout and can be used to have other layout elements (or even other layouts with multiple
elements) hovering inside the axis rect.
If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The
behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel
is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable
via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are
only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref
QCP::iRangeZoom.
\image html AxisRectSpacingOverview.png
<center>Overview of the spacings and paddings that define the geometry of an axis. The dashed
line on the far left indicates the viewport/widget border.</center>
*/
/* start documentation of inline functions */
/*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const
Returns the inset layout of this axis rect. It can be used to place other layout elements (or
even layouts with multiple other elements) inside/on top of an axis rect.
\see QCPLayoutInset
*/
/*! \fn int QCPAxisRect::left() const
Returns the pixel position of the left border of this axis rect. Margins are not taken into
account here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn int QCPAxisRect::right() const
Returns the pixel position of the right border of this axis rect. Margins are not taken into
account here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn int QCPAxisRect::top() const
Returns the pixel position of the top border of this axis rect. Margins are not taken into
account here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn int QCPAxisRect::bottom() const
Returns the pixel position of the bottom border of this axis rect. Margins are not taken into
account here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn int QCPAxisRect::width() const
Returns the pixel width of this axis rect. Margins are not taken into account here, so the
returned value is with respect to the inner \ref rect.
*/
/*! \fn int QCPAxisRect::height() const
Returns the pixel height of this axis rect. Margins are not taken into account here, so the
returned value is with respect to the inner \ref rect.
*/
/*! \fn QSize QCPAxisRect::size() const
Returns the pixel size of this axis rect. Margins are not taken into account here, so the
returned value is with respect to the inner \ref rect.
*/
/*! \fn QPoint QCPAxisRect::topLeft() const
Returns the top left corner of this axis rect in pixels. Margins are not taken into account here,
so the returned value is with respect to the inner \ref rect.
*/
/*! \fn QPoint QCPAxisRect::topRight() const
Returns the top right corner of this axis rect in pixels. Margins are not taken into account
here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn QPoint QCPAxisRect::bottomLeft() const
Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account
here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn QPoint QCPAxisRect::bottomRight() const
Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account
here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn QPoint QCPAxisRect::center() const
Returns the center of this axis rect in pixels. Margins are not taken into account here, so the
returned value is with respect to the inner \ref rect.
*/
/* end documentation of inline functions */
/*!
Creates a QCPAxisRect instance and sets default values. An axis is added for each of the four
sides, the top and right axes are set invisible initially.
*/
QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) :
QCPLayoutElement(parentPlot),
mBackgroundBrush(Qt::NoBrush),
mBackgroundScaled(true),
mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
mInsetLayout(new QCPLayoutInset),
mRangeDrag(Qt::Horizontal|Qt::Vertical),
mRangeZoom(Qt::Horizontal|Qt::Vertical),
mRangeZoomFactorHorz(0.85),
mRangeZoomFactorVert(0.85),
mDragging(false)
{
mInsetLayout->initializeParentPlot(mParentPlot);
mInsetLayout->setParentLayerable(this);
mInsetLayout->setParent(this);
setMinimumSize(50, 50);
setMinimumMargins(QMargins(15, 15, 15, 15));
mAxes.insert(QCPAxis::atLeft, QList<QCPAxis*>());
mAxes.insert(QCPAxis::atRight, QList<QCPAxis*>());
mAxes.insert(QCPAxis::atTop, QList<QCPAxis*>());
mAxes.insert(QCPAxis::atBottom, QList<QCPAxis*>());
if (setupDefaultAxes)
{
QCPAxis *xAxis = addAxis(QCPAxis::atBottom);
QCPAxis *yAxis = addAxis(QCPAxis::atLeft);
QCPAxis *xAxis2 = addAxis(QCPAxis::atTop);
QCPAxis *yAxis2 = addAxis(QCPAxis::atRight);
setRangeDragAxes(xAxis, yAxis);
setRangeZoomAxes(xAxis, yAxis);
xAxis2->setVisible(false);
yAxis2->setVisible(false);
xAxis->grid()->setVisible(true);
yAxis->grid()->setVisible(true);
xAxis2->grid()->setVisible(false);
yAxis2->grid()->setVisible(false);
xAxis2->grid()->setZeroLinePen(Qt::NoPen);
yAxis2->grid()->setZeroLinePen(Qt::NoPen);
xAxis2->grid()->setVisible(false);
yAxis2->grid()->setVisible(false);
}
}
QCPAxisRect::~QCPAxisRect()
{
delete mInsetLayout;
mInsetLayout = 0;
QList<QCPAxis*> axesList = axes();
for (int i=0; i<axesList.size(); ++i)
removeAxis(axesList.at(i));
}
/*!
Returns the number of axes on the axis rect side specified with \a type.
\see axis
*/
int QCPAxisRect::axisCount(QCPAxis::AxisType type) const
{
return mAxes.value(type).size();
}
/*!
Returns the axis with the given \a index on the axis rect side specified with \a type.
\see axisCount, axes
*/
QCPAxis *QCPAxisRect::axis(QCPAxis::AxisType type, int index) const
{
QList<QCPAxis*> ax(mAxes.value(type));
if (index >= 0 && index < ax.size())
{
return ax.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index;
return 0;
}
}
/*!
Returns all axes on the axis rect sides specified with \a types.
\a types may be a single \ref QCPAxis::AxisType or an <tt>or</tt>-combination, to get the axes of
multiple sides.
\see axis
*/
QList<QCPAxis*> QCPAxisRect::axes(QCPAxis::AxisTypes types) const
{
QList<QCPAxis*> result;
if (types.testFlag(QCPAxis::atLeft))
result << mAxes.value(QCPAxis::atLeft);
if (types.testFlag(QCPAxis::atRight))
result << mAxes.value(QCPAxis::atRight);
if (types.testFlag(QCPAxis::atTop))
result << mAxes.value(QCPAxis::atTop);
if (types.testFlag(QCPAxis::atBottom))
result << mAxes.value(QCPAxis::atBottom);
return result;
}
/*! \overload
Returns all axes of this axis rect.
*/
QList<QCPAxis*> QCPAxisRect::axes() const
{
QList<QCPAxis*> result;
QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
while (it.hasNext())
{
it.next();
result << it.value();
}
return result;
}
/*!
Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a
new QCPAxis instance is created internally.
You may inject QCPAxis instances (or sublasses of QCPAxis) by setting \a axis to an axis that was
previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership
of the axis, so you may not delete it afterwards. Further, the \a axis must have been created
with this axis rect as parent and with the same axis type as specified in \a type. If this is not
the case, a debug output is generated, the axis is not added, and the method returns 0.
This method can not be used to move \a axis between axis rects. The same \a axis instance must
not be added multiple times to the same or different axis rects.
If an axis rect side already contains one or more axes, the lower and upper endings of the new
axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref
QCPLineEnding::esHalfBar.
\see addAxes, setupFullAxesBox
*/
QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type, QCPAxis *axis)
{
QCPAxis *newAxis = axis;
if (!newAxis)
{
newAxis = new QCPAxis(this, type);
} else // user provided existing axis instance, do some sanity checks
{
if (newAxis->axisType() != type)
{
qDebug() << Q_FUNC_INFO << "passed axis has different axis type than specified in type parameter";
return 0;
}
if (newAxis->axisRect() != this)
{
qDebug() << Q_FUNC_INFO << "passed axis doesn't have this axis rect as parent axis rect";
return 0;
}
if (axes().contains(newAxis))
{
qDebug() << Q_FUNC_INFO << "passed axis is already owned by this axis rect";
return 0;
}
}
if (mAxes[type].size() > 0) // multiple axes on one side, add half-bar axis ending to additional axes with offset
{
bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom);
newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert));
newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert));
}
mAxes[type].append(newAxis);
return newAxis;
}
/*!
Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an
<tt>or</tt>-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once.
Returns a list of the added axes.
\see addAxis, setupFullAxesBox
*/
QList<QCPAxis*> QCPAxisRect::addAxes(QCPAxis::AxisTypes types)
{
QList<QCPAxis*> result;
if (types.testFlag(QCPAxis::atLeft))
result << addAxis(QCPAxis::atLeft);
if (types.testFlag(QCPAxis::atRight))
result << addAxis(QCPAxis::atRight);
if (types.testFlag(QCPAxis::atTop))
result << addAxis(QCPAxis::atTop);
if (types.testFlag(QCPAxis::atBottom))
result << addAxis(QCPAxis::atBottom);
return result;
}
/*!
Removes the specified \a axis from the axis rect and deletes it.
Returns true on success, i.e. if \a axis was a valid axis in this axis rect.
\see addAxis
*/
bool QCPAxisRect::removeAxis(QCPAxis *axis)
{
// don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers:
QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
while (it.hasNext())
{
it.next();
if (it.value().contains(axis))
{
mAxes[it.key()].removeOne(axis);
if (qobject_cast<QCustomPlot*>(parentPlot())) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the axis rect is not in any layout and thus QObject-child of QCustomPlot)
parentPlot()->axisRemoved(axis);
delete axis;
return true;
}
}
qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast<quintptr>(axis);
return false;
}
/*!
Convenience function to create an axis on each side that doesn't have any axes yet and set their
visibility to true. Further, the top/right axes are assigned the following properties of the
bottom/left axes:
\li range (\ref QCPAxis::setRange)
\li range reversed (\ref QCPAxis::setRangeReversed)
\li scale type (\ref QCPAxis::setScaleType)
\li scale log base (\ref QCPAxis::setScaleLogBase)
\li ticks (\ref QCPAxis::setTicks)
\li auto (major) tick count (\ref QCPAxis::setAutoTickCount)
\li sub tick count (\ref QCPAxis::setSubTickCount)
\li auto sub ticks (\ref QCPAxis::setAutoSubTicks)
\li tick step (\ref QCPAxis::setTickStep)
\li auto tick step (\ref QCPAxis::setAutoTickStep)
\li number format (\ref QCPAxis::setNumberFormat)
\li number precision (\ref QCPAxis::setNumberPrecision)
\li tick label type (\ref QCPAxis::setTickLabelType)
\li date time format (\ref QCPAxis::setDateTimeFormat)
\li date time spec (\ref QCPAxis::setDateTimeSpec)
Tick labels (\ref QCPAxis::setTickLabels) of the right and top axes are set to false.
If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom
and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes.
*/
void QCPAxisRect::setupFullAxesBox(bool connectRanges)
{
QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2;
if (axisCount(QCPAxis::atBottom) == 0)
xAxis = addAxis(QCPAxis::atBottom);
else
xAxis = axis(QCPAxis::atBottom);
if (axisCount(QCPAxis::atLeft) == 0)
yAxis = addAxis(QCPAxis::atLeft);
else
yAxis = axis(QCPAxis::atLeft);
if (axisCount(QCPAxis::atTop) == 0)
xAxis2 = addAxis(QCPAxis::atTop);
else
xAxis2 = axis(QCPAxis::atTop);
if (axisCount(QCPAxis::atRight) == 0)
yAxis2 = addAxis(QCPAxis::atRight);
else
yAxis2 = axis(QCPAxis::atRight);
xAxis->setVisible(true);
yAxis->setVisible(true);
xAxis2->setVisible(true);
yAxis2->setVisible(true);
xAxis2->setTickLabels(false);
yAxis2->setTickLabels(false);
xAxis2->setRange(xAxis->range());
xAxis2->setRangeReversed(xAxis->rangeReversed());
xAxis2->setScaleType(xAxis->scaleType());
xAxis2->setScaleLogBase(xAxis->scaleLogBase());
xAxis2->setTicks(xAxis->ticks());
xAxis2->setAutoTickCount(xAxis->autoTickCount());
xAxis2->setSubTickCount(xAxis->subTickCount());
xAxis2->setAutoSubTicks(xAxis->autoSubTicks());
xAxis2->setTickStep(xAxis->tickStep());
xAxis2->setAutoTickStep(xAxis->autoTickStep());
xAxis2->setNumberFormat(xAxis->numberFormat());
xAxis2->setNumberPrecision(xAxis->numberPrecision());
xAxis2->setTickLabelType(xAxis->tickLabelType());
xAxis2->setDateTimeFormat(xAxis->dateTimeFormat());
xAxis2->setDateTimeSpec(xAxis->dateTimeSpec());
yAxis2->setRange(yAxis->range());
yAxis2->setRangeReversed(yAxis->rangeReversed());
yAxis2->setScaleType(yAxis->scaleType());
yAxis2->setScaleLogBase(yAxis->scaleLogBase());
yAxis2->setTicks(yAxis->ticks());
yAxis2->setAutoTickCount(yAxis->autoTickCount());
yAxis2->setSubTickCount(yAxis->subTickCount());
yAxis2->setAutoSubTicks(yAxis->autoSubTicks());
yAxis2->setTickStep(yAxis->tickStep());
yAxis2->setAutoTickStep(yAxis->autoTickStep());
yAxis2->setNumberFormat(yAxis->numberFormat());
yAxis2->setNumberPrecision(yAxis->numberPrecision());
yAxis2->setTickLabelType(yAxis->tickLabelType());
yAxis2->setDateTimeFormat(yAxis->dateTimeFormat());
yAxis2->setDateTimeSpec(yAxis->dateTimeSpec());
if (connectRanges)
{
connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange)));
connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange)));
}
}
/*!
Returns a list of all the plottables that are associated with this axis rect.
A plottable is considered associated with an axis rect if its key or value axis (or both) is in
this axis rect.
\see graphs, items
*/
QList<QCPAbstractPlottable*> QCPAxisRect::plottables() const
{
// Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries
QList<QCPAbstractPlottable*> result;
for (int i=0; i<mParentPlot->mPlottables.size(); ++i)
{
if (mParentPlot->mPlottables.at(i)->keyAxis()->axisRect() == this ||mParentPlot->mPlottables.at(i)->valueAxis()->axisRect() == this)
result.append(mParentPlot->mPlottables.at(i));
}
return result;
}
/*!
Returns a list of all the graphs that are associated with this axis rect.
A graph is considered associated with an axis rect if its key or value axis (or both) is in
this axis rect.
\see plottables, items
*/
QList<QCPGraph*> QCPAxisRect::graphs() const
{
// Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries
QList<QCPGraph*> result;
for (int i=0; i<mParentPlot->mGraphs.size(); ++i)
{
if (mParentPlot->mGraphs.at(i)->keyAxis()->axisRect() == this || mParentPlot->mGraphs.at(i)->valueAxis()->axisRect() == this)
result.append(mParentPlot->mGraphs.at(i));
}
return result;
}
/*!
Returns a list of all the items that are associated with this axis rect.
An item is considered associated with an axis rect if any of its positions has key or value axis
set to an axis that is in this axis rect, or if any of its positions has \ref
QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref
QCPAbstractItem::setClipAxisRect) is set to this axis rect.
\see plottables, graphs
*/
QList<QCPAbstractItem *> QCPAxisRect::items() const
{
// Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries
// and miss those items that have this axis rect as clipAxisRect.
QList<QCPAbstractItem*> result;
for (int itemId=0; itemId<mParentPlot->mItems.size(); ++itemId)
{
if (mParentPlot->mItems.at(itemId)->clipAxisRect() == this)
{
result.append(mParentPlot->mItems.at(itemId));
continue;
}
QList<QCPItemPosition*> positions = mParentPlot->mItems.at(itemId)->positions();
for (int posId=0; posId<positions.size(); ++posId)
{
if (positions.at(posId)->axisRect() == this ||
positions.at(posId)->keyAxis()->axisRect() == this ||
positions.at(posId)->valueAxis()->axisRect() == this)
{
result.append(mParentPlot->mItems.at(itemId));
break;
}
}
}
return result;
}
/*!
This method is called automatically upon replot and doesn't need to be called by users of
QCPAxisRect.
Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update),
and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its
QCPInsetLayout::update function.
*/
void QCPAxisRect::update(UpdatePhase phase)
{
QCPLayoutElement::update(phase);
switch (phase)
{
case upPreparation:
{
QList<QCPAxis*> allAxes = axes();
for (int i=0; i<allAxes.size(); ++i)
allAxes.at(i)->setupTickVectors();
break;
}
case upLayout:
{
mInsetLayout->setOuterRect(rect());
break;
}
default: break;
}
// pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout):
mInsetLayout->update(phase);
}
/* inherits documentation from base class */
QList<QCPLayoutElement*> QCPAxisRect::elements(bool recursive) const
{
QList<QCPLayoutElement*> result;
if (mInsetLayout)
{
result << mInsetLayout;
if (recursive)
result << mInsetLayout->elements(recursive);
}
return result;
}
/* inherits documentation from base class */
void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
painter->setAntialiasing(false);
}
/* inherits documentation from base class */
void QCPAxisRect::draw(QCPPainter *painter)
{
drawBackground(painter);
}
/*!
Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the
axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect
backgrounds are usually drawn below everything else.
For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be
enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio
is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
consider using the overloaded version of this function.
Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref
setBackground(const QBrush &brush).
\see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush)
*/
void QCPAxisRect::setBackground(const QPixmap &pm)
{
mBackgroundPixmap = pm;
mScaledBackgroundPixmap = QPixmap();
}
/*! \overload
Sets \a brush as the background brush. The axis rect background will be filled with this brush.
Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds
are usually drawn below everything else.
The brush will be drawn before (under) any background pixmap, which may be specified with \ref
setBackground(const QPixmap &pm).
To disable drawing of a background brush, set \a brush to Qt::NoBrush.
\see setBackground(const QPixmap &pm)
*/
void QCPAxisRect::setBackground(const QBrush &brush)
{
mBackgroundBrush = brush;
}
/*! \overload
Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it
shall be scaled in one call.
\see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
*/
void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
{
mBackgroundPixmap = pm;
mScaledBackgroundPixmap = QPixmap();
mBackgroundScaled = scaled;
mBackgroundScaledMode = mode;
}
/*!
Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled
is set to true, you may control whether and how the aspect ratio of the original pixmap is
preserved with \ref setBackgroundScaledMode.
Note that the scaled version of the original pixmap is buffered, so there is no performance
penalty on replots. (Except when the axis rect dimensions are changed continuously.)
\see setBackground, setBackgroundScaledMode
*/
void QCPAxisRect::setBackgroundScaled(bool scaled)
{
mBackgroundScaled = scaled;
}
/*!
If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to
define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved.
\see setBackground, setBackgroundScaled
*/
void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode)
{
mBackgroundScaledMode = mode;
}
/*!
Returns the range drag axis of the \a orientation provided.
\see setRangeDragAxes
*/
QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation)
{
return (orientation == Qt::Horizontal ? mRangeDragHorzAxis.data() : mRangeDragVertAxis.data());
}
/*!
Returns the range zoom axis of the \a orientation provided.
\see setRangeZoomAxes
*/
QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation)
{
return (orientation == Qt::Horizontal ? mRangeZoomHorzAxis.data() : mRangeZoomVertAxis.data());
}
/*!
Returns the range zoom factor of the \a orientation provided.
\see setRangeZoomFactor
*/
double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation)
{
return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert);
}
/*!
Sets which axis orientation may be range dragged by the user with mouse interaction.
What orientation corresponds to which specific axis can be set with
\ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By
default, the horizontal axis is the bottom axis (xAxis) and the vertical axis
is the left axis (yAxis).
To disable range dragging entirely, pass 0 as \a orientations or remove \ref QCP::iRangeDrag from \ref
QCustomPlot::setInteractions. To enable range dragging for both directions, pass <tt>Qt::Horizontal |
Qt::Vertical</tt> as \a orientations.
In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
contains \ref QCP::iRangeDrag to enable the range dragging interaction.
\see setRangeZoom, setRangeDragAxes, QCustomPlot::setNoAntialiasingOnDrag
*/
void QCPAxisRect::setRangeDrag(Qt::Orientations orientations)
{
mRangeDrag = orientations;
}
/*!
Sets which axis orientation may be zoomed by the user with the mouse wheel. What orientation
corresponds to which specific axis can be set with \ref setRangeZoomAxes(QCPAxis *horizontal,
QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical
axis is the left axis (yAxis).
To disable range zooming entirely, pass 0 as \a orientations or remove \ref QCP::iRangeZoom from \ref
QCustomPlot::setInteractions. To enable range zooming for both directions, pass <tt>Qt::Horizontal |
Qt::Vertical</tt> as \a orientations.
In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
contains \ref QCP::iRangeZoom to enable the range zooming interaction.
\see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag
*/
void QCPAxisRect::setRangeZoom(Qt::Orientations orientations)
{
mRangeZoom = orientations;
}
/*!
Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging
on the QCustomPlot widget.
\see setRangeZoomAxes
*/
void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical)
{
mRangeDragHorzAxis = horizontal;
mRangeDragVertAxis = vertical;
}
/*!
Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on the
QCustomPlot widget. The two axes can be zoomed with different strengths, when different factors
are passed to \ref setRangeZoomFactor(double horizontalFactor, double verticalFactor).
\see setRangeDragAxes
*/
void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical)
{
mRangeZoomHorzAxis = horizontal;
mRangeZoomVertAxis = vertical;
}
/*!
Sets how strong one rotation step of the mouse wheel zooms, when range zoom was activated with
\ref setRangeZoom. The two parameters \a horizontalFactor and \a verticalFactor provide a way to
let the horizontal axis zoom at different rates than the vertical axis. Which axis is horizontal
and which is vertical, can be set with \ref setRangeZoomAxes.
When the zoom factor is greater than one, scrolling the mouse wheel backwards (towards the user)
will zoom in (make the currently visible range smaller). For zoom factors smaller than one, the
same scrolling direction will zoom out.
*/
void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor)
{
mRangeZoomFactorHorz = horizontalFactor;
mRangeZoomFactorVert = verticalFactor;
}
/*! \overload
Sets both the horizontal and vertical zoom \a factor.
*/
void QCPAxisRect::setRangeZoomFactor(double factor)
{
mRangeZoomFactorHorz = factor;
mRangeZoomFactorVert = factor;
}
/*! \internal
Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a
pixmap.
If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an
according filling inside the axis rect with the provided \a painter.
Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version
depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
the axis rect with the provided \a painter. The scaled version is buffered in
mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
the axis rect has changed in a way that requires a rescale of the background pixmap (this is
dependant on the \ref setBackgroundScaledMode), or when a differend axis backgroud pixmap was
set.
\see setBackground, setBackgroundScaled, setBackgroundScaledMode
*/
void QCPAxisRect::drawBackground(QCPPainter *painter)
{
// draw background fill:
if (mBackgroundBrush != Qt::NoBrush)
painter->fillRect(mRect, mBackgroundBrush);
// draw background pixmap (on top of fill, if brush specified):
if (!mBackgroundPixmap.isNull())
{
if (mBackgroundScaled)
{
// check whether mScaledBackground needs to be updated:
QSize scaledSize(mBackgroundPixmap.size());
scaledSize.scale(mRect.size(), mBackgroundScaledMode);
if (mScaledBackgroundPixmap.size() != scaledSize)
mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect());
} else
{
painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()));
}
}
}
/*! \internal
This function makes sure multiple axes on the side specified with \a type don't collide, but are
distributed according to their respective space requirement (QCPAxis::calculateMargin).
It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the
one with index zero.
This function is called by \ref calculateAutoMargin.
*/
void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type)
{
const QList<QCPAxis*> axesList = mAxes.value(type);
if (axesList.isEmpty())
return;
bool isFirstVisible = !axesList.first()->visible(); // if the first axis is visible, the second axis (which is where the loop starts) isn't the first visible axis, so initialize with false
for (int i=1; i<axesList.size(); ++i)
{
int offset = axesList.at(i-1)->offset() + axesList.at(i-1)->calculateMargin();
if (axesList.at(i)->visible()) // only add inner tick length to offset if this axis is visible and it's not the first visible one (might happen if true first axis is invisible)
{
if (!isFirstVisible)
offset += axesList.at(i)->tickLengthIn();
isFirstVisible = false;
}
axesList.at(i)->setOffset(offset);
}
}
/* inherits documentation from base class */
int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side)
{
if (!mAutoMargins.testFlag(side))
qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin";
updateAxesOffset(QCPAxis::marginSideToAxisType(side));
// note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call
const QList<QCPAxis*> axesList = mAxes.value(QCPAxis::marginSideToAxisType(side));
if (axesList.size() > 0)
return axesList.last()->offset() + axesList.last()->calculateMargin();
else
return 0;
}
/*! \internal
Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is
pressed, the range dragging interaction is initialized (the actual range manipulation happens in
the \ref mouseMoveEvent).
The mDragging flag is set to true and some anchor points are set that are needed to determine the
distance the mouse was dragged in the mouse move/release events later.
\see mouseMoveEvent, mouseReleaseEvent
*/
void QCPAxisRect::mousePressEvent(QMouseEvent *event)
{
mDragStart = event->pos(); // need this even when not LeftButton is pressed, to determine in releaseEvent whether it was a full click (no position change between press and release)
if (event->buttons() & Qt::LeftButton)
{
mDragging = true;
// initialize antialiasing backup in case we start dragging:
if (mParentPlot->noAntialiasingOnDrag())
{
mAADragBackup = mParentPlot->antialiasedElements();
mNotAADragBackup = mParentPlot->notAntialiasedElements();
}
// Mouse range dragging interaction:
if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
{
if (mRangeDragHorzAxis)
mDragStartHorzRange = mRangeDragHorzAxis.data()->range();
if (mRangeDragVertAxis)
mDragStartVertRange = mRangeDragVertAxis.data()->range();
}
}
}
/*! \internal
Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a
preceding \ref mousePressEvent, the range is moved accordingly.
\see mousePressEvent, mouseReleaseEvent
*/
void QCPAxisRect::mouseMoveEvent(QMouseEvent *event)
{
// Mouse range dragging interaction:
if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag))
{
if (mRangeDrag.testFlag(Qt::Horizontal))
{
if (QCPAxis *rangeDragHorzAxis = mRangeDragHorzAxis.data())
{
if (rangeDragHorzAxis->mScaleType == QCPAxis::stLinear)
{
double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) - rangeDragHorzAxis->pixelToCoord(event->pos().x());
rangeDragHorzAxis->setRange(mDragStartHorzRange.lower+diff, mDragStartHorzRange.upper+diff);
} else if (rangeDragHorzAxis->mScaleType == QCPAxis::stLogarithmic)
{
double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) / rangeDragHorzAxis->pixelToCoord(event->pos().x());
rangeDragHorzAxis->setRange(mDragStartHorzRange.lower*diff, mDragStartHorzRange.upper*diff);
}
}
}
if (mRangeDrag.testFlag(Qt::Vertical))
{
if (QCPAxis *rangeDragVertAxis = mRangeDragVertAxis.data())
{
if (rangeDragVertAxis->mScaleType == QCPAxis::stLinear)
{
double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) - rangeDragVertAxis->pixelToCoord(event->pos().y());
rangeDragVertAxis->setRange(mDragStartVertRange.lower+diff, mDragStartVertRange.upper+diff);
} else if (rangeDragVertAxis->mScaleType == QCPAxis::stLogarithmic)
{
double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) / rangeDragVertAxis->pixelToCoord(event->pos().y());
rangeDragVertAxis->setRange(mDragStartVertRange.lower*diff, mDragStartVertRange.upper*diff);
}
}
}
if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot
{
if (mParentPlot->noAntialiasingOnDrag())
mParentPlot->setNotAntialiasedElements(QCP::aeAll);
mParentPlot->replot();
}
}
}
/* inherits documentation from base class */
void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event)
{
Q_UNUSED(event)
mDragging = false;
if (mParentPlot->noAntialiasingOnDrag())
{
mParentPlot->setAntialiasedElements(mAADragBackup);
mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
}
}
/*! \internal
Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the
ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of
the scaling operation is the current cursor position inside the axis rect. The scaling factor is
dependant on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse
wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be
multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as
exponent of the range zoom factor. This takes care of the wheel direction automatically, by
inverting the factor, when the wheel step is negative (f^-1 = 1/f).
*/
void QCPAxisRect::wheelEvent(QWheelEvent *event)
{
// Mouse range zooming interaction:
if (mParentPlot->interactions().testFlag(QCP::iRangeZoom))
{
if (mRangeZoom != 0)
{
double factor;
double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually
if (mRangeZoom.testFlag(Qt::Horizontal))
{
factor = qPow(mRangeZoomFactorHorz, wheelSteps);
if (mRangeZoomHorzAxis.data())
mRangeZoomHorzAxis.data()->scaleRange(factor, mRangeZoomHorzAxis.data()->pixelToCoord(event->pos().x()));
}
if (mRangeZoom.testFlag(Qt::Vertical))
{
factor = qPow(mRangeZoomFactorVert, wheelSteps);
if (mRangeZoomVertAxis.data())
mRangeZoomVertAxis.data()->scaleRange(factor, mRangeZoomVertAxis.data()->pixelToCoord(event->pos().y()));
}
mParentPlot->replot();
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAbstractLegendItem
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAbstractLegendItem
\brief The abstract base class for all entries in a QCPLegend.
It defines a very basic interface for entries in a QCPLegend. For representing plottables in the
legend, the subclass \ref QCPPlottableLegendItem is more suitable.
Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry
that's not even associated with a plottable).
You must implement the following pure virtual functions:
\li \ref draw (from QCPLayerable)
You inherit the following members you may use:
<table>
<tr>
<td>QCPLegend *\b mParentLegend</td>
<td>A pointer to the parent QCPLegend.</td>
</tr><tr>
<td>QFont \b mFont</td>
<td>The generic font of the item. You should use this font for all or at least the most prominent text of the item.</td>
</tr>
</table>
*/
/* start of documentation of signals */
/*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected)
This signal is emitted when the selection state of this legend item has changed, either by user
interaction or by a direct call to \ref setSelected.
*/
/* end of documentation of signals */
/*!
Constructs a QCPAbstractLegendItem and associates it with the QCPLegend \a parent. This does not
cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately.
*/
QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) :
QCPLayoutElement(parent->parentPlot()),
mParentLegend(parent),
mFont(parent->font()),
mTextColor(parent->textColor()),
mSelectedFont(parent->selectedFont()),
mSelectedTextColor(parent->selectedTextColor()),
mSelectable(true),
mSelected(false)
{
setLayer(QLatin1String("legend"));
setMargins(QMargins(8, 2, 8, 2));
}
/*!
Sets the default font of this specific legend item to \a font.
\see setTextColor, QCPLegend::setFont
*/
void QCPAbstractLegendItem::setFont(const QFont &font)
{
mFont = font;
}
/*!
Sets the default text color of this specific legend item to \a color.
\see setFont, QCPLegend::setTextColor
*/
void QCPAbstractLegendItem::setTextColor(const QColor &color)
{
mTextColor = color;
}
/*!
When this legend item is selected, \a font is used to draw generic text, instead of the normal
font set with \ref setFont.
\see setFont, QCPLegend::setSelectedFont
*/
void QCPAbstractLegendItem::setSelectedFont(const QFont &font)
{
mSelectedFont = font;
}
/*!
When this legend item is selected, \a color is used to draw generic text, instead of the normal
color set with \ref setTextColor.
\see setTextColor, QCPLegend::setSelectedTextColor
*/
void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color)
{
mSelectedTextColor = color;
}
/*!
Sets whether this specific legend item is selectable.
\see setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAbstractLegendItem::setSelectable(bool selectable)
{
if (mSelectable != selectable)
{
mSelectable = selectable;
emit selectableChanged(mSelectable);
}
}
/*!
Sets whether this specific legend item is selected.
It is possible to set the selection state of this item by calling this function directly, even if
setSelectable is set to false.
\see setSelectableParts, QCustomPlot::setInteractions
*/
void QCPAbstractLegendItem::setSelected(bool selected)
{
if (mSelected != selected)
{
mSelected = selected;
emit selectionChanged(mSelected);
}
}
/* inherits documentation from base class */
double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (!mParentPlot) return -1;
if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems)))
return -1;
if (mRect.contains(pos.toPoint()))
return mParentPlot->selectionTolerance()*0.99;
else
return -1;
}
/* inherits documentation from base class */
void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems);
}
/* inherits documentation from base class */
QRect QCPAbstractLegendItem::clipRect() const
{
return mOuterRect;
}
/* inherits documentation from base class */
void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
Q_UNUSED(details)
if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
{
bool selBefore = mSelected;
setSelected(additive ? !mSelected : true);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
/* inherits documentation from base class */
void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged)
{
if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
{
bool selBefore = mSelected;
setSelected(false);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPPlottableLegendItem
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPPlottableLegendItem
\brief A legend item representing a plottable with an icon and the plottable name.
This is the standard legend item for plottables. It displays an icon of the plottable next to the
plottable name. The icon is drawn by the respective plottable itself (\ref
QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable.
For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the
middle.
Legend items of this type are always associated with one plottable (retrievable via the
plottable() function and settable with the constructor). You may change the font of the plottable
name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref
QCPLegend::setIconBorderPen and \ref QCPLegend::setIconTextPadding.
The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend
creates/removes legend items of this type in the default implementation. However, these functions
may be reimplemented such that a different kind of legend item (e.g a direct subclass of
QCPAbstractLegendItem) is used for that plottable.
Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of
QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout
interface, QCPLegend has specialized functions for handling legend items conveniently, see the
documentation of \ref QCPLegend.
*/
/*!
Creates a new legend item associated with \a plottable.
Once it's created, it can be added to the legend via \ref QCPLegend::addItem.
A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref
QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend.
*/
QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) :
QCPAbstractLegendItem(parent),
mPlottable(plottable)
{
}
/*! \internal
Returns the pen that shall be used to draw the icon border, taking into account the selection
state of this item.
*/
QPen QCPPlottableLegendItem::getIconBorderPen() const
{
return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen();
}
/*! \internal
Returns the text color that shall be used to draw text, taking into account the selection state
of this item.
*/
QColor QCPPlottableLegendItem::getTextColor() const
{
return mSelected ? mSelectedTextColor : mTextColor;
}
/*! \internal
Returns the font that shall be used to draw text, taking into account the selection state of this
item.
*/
QFont QCPPlottableLegendItem::getFont() const
{
return mSelected ? mSelectedFont : mFont;
}
/*! \internal
Draws the item with \a painter. The size and position of the drawn legend item is defined by the
parent layout (typically a \ref QCPLegend) and the \ref minimumSizeHint and \ref maximumSizeHint
of this legend item.
*/
void QCPPlottableLegendItem::draw(QCPPainter *painter)
{
if (!mPlottable) return;
painter->setFont(getFont());
painter->setPen(QPen(getTextColor()));
QSizeF iconSize = mParentLegend->iconSize();
QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
QRectF iconRect(mRect.topLeft(), iconSize);
int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops
painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name());
// draw icon:
painter->save();
painter->setClipRect(iconRect, Qt::IntersectClip);
mPlottable->drawLegendIcon(painter, iconRect);
painter->restore();
// draw icon border:
if (getIconBorderPen().style() != Qt::NoPen)
{
painter->setPen(getIconBorderPen());
painter->setBrush(Qt::NoBrush);
painter->drawRect(iconRect);
}
}
/*! \internal
Calculates and returns the size of this item. This includes the icon, the text and the padding in
between.
*/
QSize QCPPlottableLegendItem::minimumSizeHint() const
{
if (!mPlottable) return QSize();
QSize result(0, 0);
QRect textRect;
QFontMetrics fontMetrics(getFont());
QSize iconSize = mParentLegend->iconSize();
textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width() + mMargins.left() + mMargins.right());
result.setHeight(qMax(textRect.height(), iconSize.height()) + mMargins.top() + mMargins.bottom());
return result;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLegend
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLegend
\brief Manages a legend inside a QCustomPlot.
A legend is a small box somewhere in the plot which lists plottables with their name and icon.
Normally, the legend is populated by calling \ref QCPAbstractPlottable::addToLegend. The
respective legend item can be removed with \ref QCPAbstractPlottable::removeFromLegend. However,
QCPLegend also offers an interface to add and manipulate legend items directly: \ref item, \ref
itemWithPlottable, \ref itemCount, \ref addItem, \ref removeItem, etc.
The QCPLegend derives from QCPLayoutGrid and as such can be placed in any position a
QCPLayoutElement may be positioned. The legend items are themselves QCPLayoutElements which are
placed in the grid layout of the legend. QCPLegend only adds an interface specialized for
handling child elements of type QCPAbstractLegendItem, as mentioned above. In principle, any
other layout elements may also be added to a legend via the normal \ref QCPLayoutGrid interface.
However, the QCPAbstractLegendItem-Interface will ignore those elements (e.g. \ref itemCount will
only return the number of items with QCPAbstractLegendItems type).
By default, every QCustomPlot has one legend (QCustomPlot::legend) which is placed in the inset
layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another
position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend
outside of the axis rect, place it anywhere else with the QCPLayout/QCPLayoutElement interface.
*/
/* start of documentation of signals */
/*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection);
This signal is emitted when the selection state of this legend has changed.
\see setSelectedParts, setSelectableParts
*/
/* end of documentation of signals */
/*!
Constructs a new QCPLegend instance with \a parentPlot as the containing plot and default values.
Note that by default, QCustomPlot already contains a legend ready to be used as
QCustomPlot::legend
*/
QCPLegend::QCPLegend()
{
setRowSpacing(0);
setColumnSpacing(10);
setMargins(QMargins(2, 3, 2, 2));
setAntialiased(false);
setIconSize(32, 18);
setIconTextPadding(7);
setSelectableParts(spLegendBox | spItems);
setSelectedParts(spNone);
setBorderPen(QPen(Qt::black));
setSelectedBorderPen(QPen(Qt::blue, 2));
setIconBorderPen(Qt::NoPen);
setSelectedIconBorderPen(QPen(Qt::blue, 2));
setBrush(Qt::white);
setSelectedBrush(Qt::white);
setTextColor(Qt::black);
setSelectedTextColor(Qt::blue);
}
QCPLegend::~QCPLegend()
{
clearItems();
if (qobject_cast<QCustomPlot*>(mParentPlot)) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the legend is not in any layout and thus QObject-child of QCustomPlot)
mParentPlot->legendRemoved(this);
}
/* no doc for getter, see setSelectedParts */
QCPLegend::SelectableParts QCPLegend::selectedParts() const
{
// check whether any legend elements selected, if yes, add spItems to return value
bool hasSelectedItems = false;
for (int i=0; i<itemCount(); ++i)
{
if (item(i) && item(i)->selected())
{
hasSelectedItems = true;
break;
}
}
if (hasSelectedItems)
return mSelectedParts | spItems;
else
return mSelectedParts & ~spItems;
}
/*!
Sets the pen, the border of the entire legend is drawn with.
*/
void QCPLegend::setBorderPen(const QPen &pen)
{
mBorderPen = pen;
}
/*!
Sets the brush of the legend background.
*/
void QCPLegend::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will
use this font by default. However, a different font can be specified on a per-item-basis by
accessing the specific legend item.
This function will also set \a font on all already existing legend items.
\see QCPAbstractLegendItem::setFont
*/
void QCPLegend::setFont(const QFont &font)
{
mFont = font;
for (int i=0; i<itemCount(); ++i)
{
if (item(i))
item(i)->setFont(mFont);
}
}
/*!
Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph)
will use this color by default. However, a different colors can be specified on a per-item-basis
by accessing the specific legend item.
This function will also set \a color on all already existing legend items.
\see QCPAbstractLegendItem::setTextColor
*/
void QCPLegend::setTextColor(const QColor &color)
{
mTextColor = color;
for (int i=0; i<itemCount(); ++i)
{
if (item(i))
item(i)->setTextColor(color);
}
}
/*!
Sets the size of legend icons. Legend items that draw an icon (e.g. a visual
representation of the graph) will use this size by default.
*/
void QCPLegend::setIconSize(const QSize &size)
{
mIconSize = size;
}
/*! \overload
*/
void QCPLegend::setIconSize(int width, int height)
{
mIconSize.setWidth(width);
mIconSize.setHeight(height);
}
/*!
Sets the horizontal space in pixels between the legend icon and the text next to it.
Legend items that draw an icon (e.g. a visual representation of the graph) and text (e.g. the
name of the graph) will use this space by default.
*/
void QCPLegend::setIconTextPadding(int padding)
{
mIconTextPadding = padding;
}
/*!
Sets the pen used to draw a border around each legend icon. Legend items that draw an
icon (e.g. a visual representation of the graph) will use this pen by default.
If no border is wanted, set this to \a Qt::NoPen.
*/
void QCPLegend::setIconBorderPen(const QPen &pen)
{
mIconBorderPen = pen;
}
/*!
Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
(When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.)
However, even when \a selectable is set to a value not allowing the selection of a specific part,
it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
directly.
\see SelectablePart, setSelectedParts
*/
void QCPLegend::setSelectableParts(const SelectableParts &selectable)
{
if (mSelectableParts != selectable)
{
mSelectableParts = selectable;
emit selectableChanged(mSelectableParts);
}
}
/*!
Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part
is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected
doesn't contain \ref spItems, those items become deselected.
The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions
contains iSelectLegend. You only need to call this function when you wish to change the selection
state manually.
This function can change the selection state of a part even when \ref setSelectableParts was set to a
value that actually excludes the part.
emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set
before, because there's no way to specify which exact items to newly select. Do this by calling
\ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select.
\see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush,
setSelectedFont
*/
void QCPLegend::setSelectedParts(const SelectableParts &selected)
{
SelectableParts newSelected = selected;
mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed
if (mSelectedParts != newSelected)
{
if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that)
{
qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function";
newSelected &= ~spItems;
}
if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection
{
for (int i=0; i<itemCount(); ++i)
{
if (item(i))
item(i)->setSelected(false);
}
}
mSelectedParts = newSelected;
emit selectionChanged(mSelectedParts);
}
}
/*!
When the legend box is selected, this pen is used to draw the border instead of the normal pen
set via \ref setBorderPen.
\see setSelectedParts, setSelectableParts, setSelectedBrush
*/
void QCPLegend::setSelectedBorderPen(const QPen &pen)
{
mSelectedBorderPen = pen;
}
/*!
Sets the pen legend items will use to draw their icon borders, when they are selected.
\see setSelectedParts, setSelectableParts, setSelectedFont
*/
void QCPLegend::setSelectedIconBorderPen(const QPen &pen)
{
mSelectedIconBorderPen = pen;
}
/*!
When the legend box is selected, this brush is used to draw the legend background instead of the normal brush
set via \ref setBrush.
\see setSelectedParts, setSelectableParts, setSelectedBorderPen
*/
void QCPLegend::setSelectedBrush(const QBrush &brush)
{
mSelectedBrush = brush;
}
/*!
Sets the default font that is used by legend items when they are selected.
This function will also set \a font on all already existing legend items.
\see setFont, QCPAbstractLegendItem::setSelectedFont
*/
void QCPLegend::setSelectedFont(const QFont &font)
{
mSelectedFont = font;
for (int i=0; i<itemCount(); ++i)
{
if (item(i))
item(i)->setSelectedFont(font);
}
}
/*!
Sets the default text color that is used by legend items when they are selected.
This function will also set \a color on all already existing legend items.
\see setTextColor, QCPAbstractLegendItem::setSelectedTextColor
*/
void QCPLegend::setSelectedTextColor(const QColor &color)
{
mSelectedTextColor = color;
for (int i=0; i<itemCount(); ++i)
{
if (item(i))
item(i)->setSelectedTextColor(color);
}
}
/*!
Returns the item with index \a i.
\see itemCount
*/
QCPAbstractLegendItem *QCPLegend::item(int index) const
{
return qobject_cast<QCPAbstractLegendItem*>(elementAt(index));
}
/*!
Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
If such an item isn't in the legend, returns 0.
\see hasItemWithPlottable
*/
QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const
{
for (int i=0; i<itemCount(); ++i)
{
if (QCPPlottableLegendItem *pli = qobject_cast<QCPPlottableLegendItem*>(item(i)))
{
if (pli->plottable() == plottable)
return pli;
}
}
return 0;
}
/*!
Returns the number of items currently in the legend.
\see item
*/
int QCPLegend::itemCount() const
{
return elementCount();
}
/*!
Returns whether the legend contains \a itm.
*/
bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const
{
for (int i=0; i<itemCount(); ++i)
{
if (item == this->item(i))
return true;
}
return false;
}
/*!
Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
If such an item isn't in the legend, returns false.
\see itemWithPlottable
*/
bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const
{
return itemWithPlottable(plottable);
}
/*!
Adds \a item to the legend, if it's not present already.
Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly added.
The legend takes ownership of the item.
*/
bool QCPLegend::addItem(QCPAbstractLegendItem *item)
{
if (!hasItem(item))
{
return addElement(rowCount(), 0, item);
} else
return false;
}
/*!
Removes the item with index \a index from the legend.
Returns true, if successful.
\see itemCount, clearItems
*/
bool QCPLegend::removeItem(int index)
{
if (QCPAbstractLegendItem *ali = item(index))
{
bool success = remove(ali);
simplify();
return success;
} else
return false;
}
/*! \overload
Removes \a item from the legend.
Returns true, if successful.
\see clearItems
*/
bool QCPLegend::removeItem(QCPAbstractLegendItem *item)
{
bool success = remove(item);
simplify();
return success;
}
/*!
Removes all items from the legend.
*/
void QCPLegend::clearItems()
{
for (int i=itemCount()-1; i>=0; --i)
removeItem(i);
}
/*!
Returns the legend items that are currently selected. If no items are selected,
the list is empty.
\see QCPAbstractLegendItem::setSelected, setSelectable
*/
QList<QCPAbstractLegendItem *> QCPLegend::selectedItems() const
{
QList<QCPAbstractLegendItem*> result;
for (int i=0; i<itemCount(); ++i)
{
if (QCPAbstractLegendItem *ali = item(i))
{
if (ali->selected())
result.append(ali);
}
}
return result;
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing main legend elements.
This is the antialiasing state the painter passed to the \ref draw method is in by default.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased
*/
void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend);
}
/*! \internal
Returns the pen used to paint the border of the legend, taking into account the selection state
of the legend box.
*/
QPen QCPLegend::getBorderPen() const
{
return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen;
}
/*! \internal
Returns the brush used to paint the background of the legend, taking into account the selection
state of the legend box.
*/
QBrush QCPLegend::getBrush() const
{
return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush;
}
/*! \internal
Draws the legend box with the provided \a painter. The individual legend items are layerables
themselves, thus are drawn independently.
*/
void QCPLegend::draw(QCPPainter *painter)
{
// draw background rect:
painter->setBrush(getBrush());
painter->setPen(getBorderPen());
painter->drawRect(mOuterRect);
}
/* inherits documentation from base class */
double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
if (!mParentPlot) return -1;
if (onlySelectable && !mSelectableParts.testFlag(spLegendBox))
return -1;
if (mOuterRect.contains(pos.toPoint()))
{
if (details) details->setValue(spLegendBox);
return mParentPlot->selectionTolerance()*0.99;
}
return -1;
}
/* inherits documentation from base class */
void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
mSelectedParts = selectedParts(); // in case item selection has changed
if (details.value<SelectablePart>() == spLegendBox && mSelectableParts.testFlag(spLegendBox))
{
SelectableParts selBefore = mSelectedParts;
setSelectedParts(additive ? mSelectedParts^spLegendBox : mSelectedParts|spLegendBox); // no need to unset spItems in !additive case, because they will be deselected by QCustomPlot (they're normal QCPLayerables with own deselectEvent)
if (selectionStateChanged)
*selectionStateChanged = mSelectedParts != selBefore;
}
}
/* inherits documentation from base class */
void QCPLegend::deselectEvent(bool *selectionStateChanged)
{
mSelectedParts = selectedParts(); // in case item selection has changed
if (mSelectableParts.testFlag(spLegendBox))
{
SelectableParts selBefore = mSelectedParts;
setSelectedParts(selectedParts() & ~spLegendBox);
if (selectionStateChanged)
*selectionStateChanged = mSelectedParts != selBefore;
}
}
/* inherits documentation from base class */
QCP::Interaction QCPLegend::selectionCategory() const
{
return QCP::iSelectLegend;
}
/* inherits documentation from base class */
QCP::Interaction QCPAbstractLegendItem::selectionCategory() const
{
return QCP::iSelectLegend;
}
/* inherits documentation from base class */
void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot)
{
Q_UNUSED(parentPlot)
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPPlotTitle
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPPlotTitle
\brief A layout element displaying a plot title text
The text may be specified with \ref setText, theformatting can be controlled with \ref setFont
and \ref setTextColor.
A plot title can be added as follows:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpplottitle-creation
Since a plot title is a common requirement, QCustomPlot offers specialized selection signals for
easy interaction with QCPPlotTitle. If a layout element of type QCPPlotTitle is clicked, the
signal \ref QCustomPlot::titleClick is emitted. A double click emits the \ref
QCustomPlot::titleDoubleClick signal.
*/
/* start documentation of signals */
/*! \fn void QCPPlotTitle::selectionChanged(bool selected)
This signal is emitted when the selection state has changed to \a selected, either by user
interaction or by a direct call to \ref setSelected.
\see setSelected, setSelectable
*/
/* end documentation of signals */
/*!
Creates a new QCPPlotTitle instance and sets default values. The initial text is empty (\ref setText).
To set the title text in the constructor, rather use \ref QCPPlotTitle(QCustomPlot *parentPlot, const QString &text).
*/
QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot) :
QCPLayoutElement(parentPlot),
mFont(QFont(QLatin1String("sans serif"), 13*1.5, QFont::Bold)),
mTextColor(Qt::black),
mSelectedFont(QFont(QLatin1String("sans serif"), 13*1.6, QFont::Bold)),
mSelectedTextColor(Qt::blue),
mSelectable(false),
mSelected(false)
{
if (parentPlot)
{
setLayer(parentPlot->currentLayer());
mFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold);
mSelectedFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold);
}
setMargins(QMargins(5, 5, 5, 0));
}
/*! \overload
Creates a new QCPPlotTitle instance and sets default values. The initial text is set to \a text.
*/
QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot, const QString &text) :
QCPLayoutElement(parentPlot),
mText(text),
mFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold)),
mTextColor(Qt::black),
mSelectedFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold)),
mSelectedTextColor(Qt::blue),
mSelectable(false),
mSelected(false)
{
setLayer(QLatin1String("axes"));
setMargins(QMargins(5, 5, 5, 0));
}
/*!
Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n".
\see setFont, setTextColor
*/
void QCPPlotTitle::setText(const QString &text)
{
mText = text;
}
/*!
Sets the \a font of the title text.
\see setTextColor, setSelectedFont
*/
void QCPPlotTitle::setFont(const QFont &font)
{
mFont = font;
}
/*!
Sets the \a color of the title text.
\see setFont, setSelectedTextColor
*/
void QCPPlotTitle::setTextColor(const QColor &color)
{
mTextColor = color;
}
/*!
Sets the \a font of the title text that will be used if the plot title is selected (\ref setSelected).
\see setFont
*/
void QCPPlotTitle::setSelectedFont(const QFont &font)
{
mSelectedFont = font;
}
/*!
Sets the \a color of the title text that will be used if the plot title is selected (\ref setSelected).
\see setTextColor
*/
void QCPPlotTitle::setSelectedTextColor(const QColor &color)
{
mSelectedTextColor = color;
}
/*!
Sets whether the user may select this plot title to \a selectable.
Note that even when \a selectable is set to <tt>false</tt>, the selection state may be changed
programmatically via \ref setSelected.
*/
void QCPPlotTitle::setSelectable(bool selectable)
{
if (mSelectable != selectable)
{
mSelectable = selectable;
emit selectableChanged(mSelectable);
}
}
/*!
Sets the selection state of this plot title to \a selected. If the selection has changed, \ref
selectionChanged is emitted.
Note that this function can change the selection state independently of the current \ref
setSelectable state.
*/
void QCPPlotTitle::setSelected(bool selected)
{
if (mSelected != selected)
{
mSelected = selected;
emit selectionChanged(mSelected);
}
}
/* inherits documentation from base class */
void QCPPlotTitle::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeNone);
}
/* inherits documentation from base class */
void QCPPlotTitle::draw(QCPPainter *painter)
{
painter->setFont(mainFont());
painter->setPen(QPen(mainTextColor()));
painter->drawText(mRect, Qt::AlignCenter, mText, &mTextBoundingRect);
}
/* inherits documentation from base class */
QSize QCPPlotTitle::minimumSizeHint() const
{
QFontMetrics metrics(mFont);
QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size();
result.rwidth() += mMargins.left() + mMargins.right();
result.rheight() += mMargins.top() + mMargins.bottom();
return result;
}
/* inherits documentation from base class */
QSize QCPPlotTitle::maximumSizeHint() const
{
QFontMetrics metrics(mFont);
QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size();
result.rheight() += mMargins.top() + mMargins.bottom();
result.setWidth(QWIDGETSIZE_MAX);
return result;
}
/* inherits documentation from base class */
void QCPPlotTitle::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
Q_UNUSED(details)
if (mSelectable)
{
bool selBefore = mSelected;
setSelected(additive ? !mSelected : true);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
/* inherits documentation from base class */
void QCPPlotTitle::deselectEvent(bool *selectionStateChanged)
{
if (mSelectable)
{
bool selBefore = mSelected;
setSelected(false);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
/* inherits documentation from base class */
double QCPPlotTitle::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
if (mTextBoundingRect.contains(pos.toPoint()))
return mParentPlot->selectionTolerance()*0.99;
else
return -1;
}
/*! \internal
Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to
<tt>true</tt>, else mFont is returned.
*/
QFont QCPPlotTitle::mainFont() const
{
return mSelected ? mSelectedFont : mFont;
}
/*! \internal
Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to
<tt>true</tt>, else mTextColor is returned.
*/
QColor QCPPlotTitle::mainTextColor() const
{
return mSelected ? mSelectedTextColor : mTextColor;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPColorScale
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPColorScale
\brief A color scale for use with color coding data such as QCPColorMap
This layout element can be placed on the plot to correlate a color gradient with data values. It
is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps".
\image html QCPColorScale.png
The color scale can be either horizontal or vertical, as shown in the image above. The
orientation and the side where the numbers appear is controlled with \ref setType.
Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are
connected, they share their gradient, data range and data scale type (\ref setGradient, \ref
setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color
scale, to make them all synchronize these properties.
To have finer control over the number display and axis behaviour, you can directly access the
\ref axis. See the documentation of QCPAxis for details about configuring axes. For example, if
you want to change the number of automatically generated ticks, call
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-autotickcount
Placing a color scale next to the main axis rect works like with any other layout element:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-creation
In this case we have placed it to the right of the default axis rect, so it wasn't necessary to
call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color
scale can be set with \ref setLabel.
For optimum appearance (like in the image above), it may be desirable to line up the axis rect and
the borders of the color scale. Use a \ref QCPMarginGroup to achieve this:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-margingroup
Color scales are initialized with a non-zero minimum top and bottom margin (\ref
setMinimumMargins), because vertical color scales are most common and the minimum top/bottom
margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a
horizontal color scale by setting \ref setType to \ref QCPAxis::atBottom or \ref QCPAxis::atTop, you
might want to also change the minimum margins accordingly, e.g. <tt>setMinimumMargins(QMargins(6, 0, 6, 0))</tt>.
*/
/* start documentation of inline functions */
/*! \fn QCPAxis *QCPColorScale::axis() const
Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the
appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its
interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref
setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref
QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on
the QCPColorScale or on its QCPAxis.
If the type of the color scale is changed with \ref setType, the axis returned by this method
will change, too, to either the left, right, bottom or top axis, depending on which type was set.
*/
/* end documentation of signals */
/* start documentation of signals */
/*! \fn void QCPColorScale::dataRangeChanged(QCPRange newRange);
This signal is emitted when the data range changes.
\see setDataRange
*/
/*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
This signal is emitted when the data scale type changes.
\see setDataScaleType
*/
/*! \fn void QCPColorScale::gradientChanged(QCPColorGradient newGradient);
This signal is emitted when the gradient changes.
\see setGradient
*/
/* end documentation of signals */
/*!
Constructs a new QCPColorScale.
*/
QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) :
QCPLayoutElement(parentPlot),
mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight
mDataScaleType(QCPAxis::stLinear),
mBarWidth(20),
mAxisRect(new QCPColorScaleAxisRectPrivate(this))
{
setMinimumMargins(QMargins(0, 6, 0, 6)); // for default right color scale types, keep some room at bottom and top (important if no margin group is used)
setType(QCPAxis::atRight);
setDataRange(QCPRange(0, 6));
}
QCPColorScale::~QCPColorScale()
{
delete mAxisRect;
}
/* undocumented getter */
QString QCPColorScale::label() const
{
if (!mColorAxis)
{
qDebug() << Q_FUNC_INFO << "internal color axis undefined";
return QString();
}
return mColorAxis.data()->label();
}
/* undocumented getter */
bool QCPColorScale::rangeDrag() const
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return false;
}
return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) &&
mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) &&
mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
}
/* undocumented getter */
bool QCPColorScale::rangeZoom() const
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return false;
}
return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) &&
mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) &&
mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
}
/*!
Sets at which side of the color scale the axis is placed, and thus also its orientation.
Note that after setting \a type to a different value, the axis returned by \ref axis() will
be a different one. The new axis will adopt the following properties from the previous axis: The
range, scale type, log base and label.
*/
void QCPColorScale::setType(QCPAxis::AxisType type)
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return;
}
if (mType != type)
{
mType = type;
QCPRange rangeTransfer(0, 6);
double logBaseTransfer = 10;
QString labelTransfer;
// revert some settings on old axis:
if (mColorAxis)
{
rangeTransfer = mColorAxis.data()->range();
labelTransfer = mColorAxis.data()->label();
logBaseTransfer = mColorAxis.data()->scaleLogBase();
mColorAxis.data()->setLabel(QString());
disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
}
QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop;
foreach (QCPAxis::AxisType atype, allAxisTypes)
{
mAxisRect.data()->axis(atype)->setTicks(atype == mType);
mAxisRect.data()->axis(atype)->setTickLabels(atype== mType);
}
// set new mColorAxis pointer:
mColorAxis = mAxisRect.data()->axis(mType);
// transfer settings to new axis:
mColorAxis.data()->setRange(rangeTransfer); // transfer range of old axis to new one (necessary if axis changes from vertical to horizontal or vice versa)
mColorAxis.data()->setLabel(labelTransfer);
mColorAxis.data()->setScaleLogBase(logBaseTransfer); // scaleType is synchronized among axes in realtime via signals (connected in QCPColorScale ctor), so we only need to take care of log base here
connect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
connect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
mAxisRect.data()->setRangeDragAxes(QCPAxis::orientation(mType) == Qt::Horizontal ? mColorAxis.data() : 0,
QCPAxis::orientation(mType) == Qt::Vertical ? mColorAxis.data() : 0);
}
}
/*!
Sets the range spanned by the color gradient and that is shown by the axis in the color scale.
It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is
also equivalent to directly accessing the \ref axis and setting its range with \ref
QCPAxis::setRange.
\see setDataScaleType, setGradient, rescaleDataRange
*/
void QCPColorScale::setDataRange(const QCPRange &dataRange)
{
if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper)
{
mDataRange = dataRange;
if (mColorAxis)
mColorAxis.data()->setRange(mDataRange);
emit dataRangeChanged(mDataRange);
}
}
/*!
Sets the scale type of the color scale, i.e. whether values are linearly associated with colors
or logarithmically.
It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is
also equivalent to directly accessing the \ref axis and setting its scale type with \ref
QCPAxis::setScaleType.
\see setDataRange, setGradient
*/
void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType)
{
if (mDataScaleType != scaleType)
{
mDataScaleType = scaleType;
if (mColorAxis)
mColorAxis.data()->setScaleType(mDataScaleType);
if (mDataScaleType == QCPAxis::stLogarithmic)
setDataRange(mDataRange.sanitizedForLogScale());
emit dataScaleTypeChanged(mDataScaleType);
}
}
/*!
Sets the color gradient that will be used to represent data values.
It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps.
\see setDataRange, setDataScaleType
*/
void QCPColorScale::setGradient(const QCPColorGradient &gradient)
{
if (mGradient != gradient)
{
mGradient = gradient;
if (mAxisRect)
mAxisRect.data()->mGradientImageInvalidated = true;
emit gradientChanged(mGradient);
}
}
/*!
Sets the axis label of the color scale. This is equivalent to calling \ref QCPAxis::setLabel on
the internal \ref axis.
*/
void QCPColorScale::setLabel(const QString &str)
{
if (!mColorAxis)
{
qDebug() << Q_FUNC_INFO << "internal color axis undefined";
return;
}
mColorAxis.data()->setLabel(str);
}
/*!
Sets the width (or height, for horizontal color scales) the bar where the gradient is displayed
will have.
*/
void QCPColorScale::setBarWidth(int width)
{
mBarWidth = width;
}
/*!
Sets whether the user can drag the data range (\ref setDataRange).
Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref
QCustomPlot::setInteractions) to allow range dragging.
*/
void QCPColorScale::setRangeDrag(bool enabled)
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return;
}
if (enabled)
mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType));
else
mAxisRect.data()->setRangeDrag(0);
}
/*!
Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel.
Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref
QCustomPlot::setInteractions) to allow range dragging.
*/
void QCPColorScale::setRangeZoom(bool enabled)
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return;
}
if (enabled)
mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType));
else
mAxisRect.data()->setRangeZoom(0);
}
/*!
Returns a list of all the color maps associated with this color scale.
*/
QList<QCPColorMap*> QCPColorScale::colorMaps() const
{
QList<QCPColorMap*> result;
for (int i=0; i<mParentPlot->plottableCount(); ++i)
{
if (QCPColorMap *cm = qobject_cast<QCPColorMap*>(mParentPlot->plottable(i)))
if (cm->colorScale() == this)
result.append(cm);
}
return result;
}
/*!
Changes the data range such that all color maps associated with this color scale are fully mapped
to the gradient in the data dimension.
\see setDataRange
*/
void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps)
{
QList<QCPColorMap*> maps = colorMaps();
QCPRange newRange;
bool haveRange = false;
int sign = 0; // TODO: should change this to QCPAbstractPlottable::SignDomain later (currently is protected, maybe move to QCP namespace)
if (mDataScaleType == QCPAxis::stLogarithmic)
sign = (mDataRange.upper < 0 ? -1 : 1);
for (int i=0; i<maps.size(); ++i)
{
if (!maps.at(i)->realVisibility() && onlyVisibleMaps)
continue;
QCPRange mapRange;
if (maps.at(i)->colorScale() == this)
{
bool currentFoundRange = true;
mapRange = maps.at(i)->data()->dataBounds();
if (sign == 1)
{
if (mapRange.lower <= 0 && mapRange.upper > 0)
mapRange.lower = mapRange.upper*1e-3;
else if (mapRange.lower <= 0 && mapRange.upper <= 0)
currentFoundRange = false;
} else if (sign == -1)
{
if (mapRange.upper >= 0 && mapRange.lower < 0)
mapRange.upper = mapRange.lower*1e-3;
else if (mapRange.upper >= 0 && mapRange.lower >= 0)
currentFoundRange = false;
}
if (currentFoundRange)
{
if (!haveRange)
newRange = mapRange;
else
newRange.expand(mapRange);
haveRange = true;
}
}
}
if (haveRange)
{
if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this dimension), shift current range to at least center the data
{
double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
if (mDataScaleType == QCPAxis::stLinear)
{
newRange.lower = center-mDataRange.size()/2.0;
newRange.upper = center+mDataRange.size()/2.0;
} else // mScaleType == stLogarithmic
{
newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower);
newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower);
}
}
setDataRange(newRange);
}
}
/* inherits documentation from base class */
void QCPColorScale::update(UpdatePhase phase)
{
QCPLayoutElement::update(phase);
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return;
}
mAxisRect.data()->update(phase);
switch (phase)
{
case upMargins:
{
if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop)
{
setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom());
setMinimumSize(0, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom());
} else
{
setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), QWIDGETSIZE_MAX);
setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), 0);
}
break;
}
case upLayout:
{
mAxisRect.data()->setOuterRect(rect());
break;
}
default: break;
}
}
/* inherits documentation from base class */
void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
painter->setAntialiasing(false);
}
/* inherits documentation from base class */
void QCPColorScale::mousePressEvent(QMouseEvent *event)
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return;
}
mAxisRect.data()->mousePressEvent(event);
}
/* inherits documentation from base class */
void QCPColorScale::mouseMoveEvent(QMouseEvent *event)
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return;
}
mAxisRect.data()->mouseMoveEvent(event);
}
/* inherits documentation from base class */
void QCPColorScale::mouseReleaseEvent(QMouseEvent *event)
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return;
}
mAxisRect.data()->mouseReleaseEvent(event);
}
/* inherits documentation from base class */
void QCPColorScale::wheelEvent(QWheelEvent *event)
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return;
}
mAxisRect.data()->wheelEvent(event);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPColorScaleAxisRectPrivate
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPColorScaleAxisRectPrivate
\internal
\brief An axis rect subclass for use in a QCPColorScale
This is a private class and not part of the public QCustomPlot interface.
It provides the axis rect functionality for the QCPColorScale class.
*/
/*!
Creates a new instance, as a child of \a parentColorScale.
*/
QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) :
QCPAxisRect(parentColorScale->parentPlot(), true),
mParentColorScale(parentColorScale),
mGradientImageInvalidated(true)
{
setParentLayerable(parentColorScale);
setMinimumMargins(QMargins(0, 0, 0, 0));
QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
foreach (QCPAxis::AxisType type, allAxisTypes)
{
axis(type)->setVisible(true);
axis(type)->grid()->setVisible(false);
axis(type)->setPadding(0);
connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts)));
connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts)));
}
connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange)));
connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange)));
connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange)));
connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange)));
connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType)));
connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType)));
connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType)));
connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType)));
// make layer transfers of color scale transfer to axis rect and axes
// the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect:
connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*)));
foreach (QCPAxis::AxisType type, allAxisTypes)
connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*)));
}
/*! \internal
Updates the color gradient image if necessary, by calling \ref updateGradientImage, then draws
it. Then the axes are drawn by calling the \ref QCPAxisRect::draw base class implementation.
*/
void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter)
{
if (mGradientImageInvalidated)
updateGradientImage();
bool mirrorHorz = false;
bool mirrorVert = false;
if (mParentColorScale->mColorAxis)
{
mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop);
mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight);
}
painter->drawImage(rect().adjusted(0, -1, 0, -1), mGradientImage.mirrored(mirrorHorz, mirrorVert));
QCPAxisRect::draw(painter);
}
/*! \internal
Uses the current gradient of the parent \ref QCPColorScale (specified in the constructor) to
generate a gradient image. This gradient image will be used in the \ref draw method.
*/
void QCPColorScaleAxisRectPrivate::updateGradientImage()
{
if (rect().isEmpty())
return;
int n = mParentColorScale->mGradient.levelCount();
int w, h;
QVector<double> data(n);
for (int i=0; i<n; ++i)
data[i] = i;
if (mParentColorScale->mType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop)
{
w = n;
h = rect().height();
mGradientImage = QImage(w, h, QImage::Format_RGB32);
QVector<QRgb*> pixels;
for (int y=0; y<h; ++y)
pixels.append(reinterpret_cast<QRgb*>(mGradientImage.scanLine(y)));
mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n-1), pixels.first(), n);
for (int y=1; y<h; ++y)
memcpy(pixels.at(y), pixels.first(), n*sizeof(QRgb));
} else
{
w = rect().width();
h = n;
mGradientImage = QImage(w, h, QImage::Format_RGB32);
for (int y=0; y<h; ++y)
{
QRgb *pixels = reinterpret_cast<QRgb*>(mGradientImage.scanLine(y));
const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1));
for (int x=0; x<w; ++x)
pixels[x] = lineColor;
}
}
mGradientImageInvalidated = false;
}
/*! \internal
This slot is connected to the selectionChanged signals of the four axes in the constructor. It
synchronizes the selection state of the axes.
*/
void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts selectedParts)
{
// axis bases of four axes shall always (de-)selected synchronously:
QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
foreach (QCPAxis::AxisType type, allAxisTypes)
{
if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
if (senderAxis->axisType() == type)
continue;
if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
{
if (selectedParts.testFlag(QCPAxis::spAxis))
axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis);
else
axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis);
}
}
}
/*! \internal
This slot is connected to the selectableChanged signals of the four axes in the constructor. It
synchronizes the selectability of the axes.
*/
void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts)
{
// synchronize axis base selectability:
QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
foreach (QCPAxis::AxisType type, allAxisTypes)
{
if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
if (senderAxis->axisType() == type)
continue;
if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
{
if (selectableParts.testFlag(QCPAxis::spAxis))
axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis);
else
axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPData
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPData
\brief Holds the data of one single data point for QCPGraph.
The container for storing multiple data points is \ref QCPDataMap.
The stored data is:
\li \a key: coordinate on the key axis of this data point
\li \a value: coordinate on the value axis of this data point
\li \a keyErrorMinus: negative error in the key dimension (for error bars)
\li \a keyErrorPlus: positive error in the key dimension (for error bars)
\li \a valueErrorMinus: negative error in the value dimension (for error bars)
\li \a valueErrorPlus: positive error in the value dimension (for error bars)
\see QCPDataMap
*/
/*!
Constructs a data point with key, value and all errors set to zero.
*/
QCPData::QCPData() :
key(0),
value(0),
keyErrorPlus(0),
keyErrorMinus(0),
valueErrorPlus(0),
valueErrorMinus(0)
{
}
/*!
Constructs a data point with the specified \a key and \a value. All errors are set to zero.
*/
QCPData::QCPData(double key, double value) :
key(key),
value(value),
keyErrorPlus(0),
keyErrorMinus(0),
valueErrorPlus(0),
valueErrorMinus(0)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPGraph
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPGraph
\brief A plottable representing a graph in a plot.
\image html QCPGraph.png
Usually you create new graphs by calling QCustomPlot::addGraph. The resulting instance can be
accessed via QCustomPlot::graph.
To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
also access and modify the graph's data via the \ref data method, which returns a pointer to the
internal \ref QCPDataMap.
Graphs are used to display single-valued data. Single-valued means that there should only be one
data point per unique key coordinate. In other words, the graph can't have \a loops. If you do
want to plot non-single-valued curves, rather use the QCPCurve plottable.
Gaps in the graph line can be created by adding data points with NaN as value
(<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be
separated.
\section appearance Changing the appearance
The appearance of the graph is mainly determined by the line style, scatter style, brush and pen
of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen).
\subsection filling Filling under or between graphs
QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to
the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill,
just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent.
By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill
between this graph and another one, call \ref setChannelFillGraph with the other graph as
parameter.
\see QCustomPlot::addGraph, QCustomPlot::graph
*/
/* start of documentation of inline functions */
/*! \fn QCPDataMap *QCPGraph::data() const
Returns a pointer to the internal data storage of type \ref QCPDataMap. You may use it to
directly manipulate the data, which may be more convenient and faster than using the regular \ref
setData or \ref addData methods, in certain situations.
*/
/* end of documentation of inline functions */
/*!
Constructs a graph which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
the same orientation. If either of these restrictions is violated, a corresponding message is
printed to the debug output (qDebug), the construction is not aborted, though.
The constructed QCPGraph can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
then takes ownership of the graph.
To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph function.
*/
QCPGraph::QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPAbstractPlottable(keyAxis, valueAxis)
{
mData = new QCPDataMap;
setPen(QPen(Qt::blue, 0));
setErrorPen(QPen(Qt::black));
setBrush(Qt::NoBrush);
setSelectedPen(QPen(QColor(80, 80, 255), 2.5));
setSelectedBrush(Qt::NoBrush);
setLineStyle(lsLine);
setErrorType(etNone);
setErrorBarSize(6);
setErrorBarSkipSymbol(true);
setChannelFillGraph(0);
setAdaptiveSampling(true);
}
QCPGraph::~QCPGraph()
{
delete mData;
}
/*!
Replaces the current data with the provided \a data.
If \a copy is set to true, data points in \a data will only be copied. if false, the graph
takes ownership of the passed data and replaces the internal data pointer with it. This is
significantly faster than copying for large datasets.
Alternatively, you can also access and modify the graph's data via the \ref data method, which
returns a pointer to the internal \ref QCPDataMap.
*/
void QCPGraph::setData(QCPDataMap *data, bool copy)
{
if (mData == data)
{
qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast<quintptr>(data);
return;
}
if (copy)
{
*mData = *data;
} else
{
delete mData;
mData = data;
}
}
/*! \overload
Replaces the current data with the provided points in \a key and \a value pairs. The provided
vectors should have equal length. Else, the number of added points will be the size of the
smallest vector.
*/
void QCPGraph::setData(const QVector<double> &key, const QVector<double> &value)
{
mData->clear();
int n = key.size();
n = qMin(n, value.size());
QCPData newData;
for (int i=0; i<n; ++i)
{
newData.key = key[i];
newData.value = value[i];
mData->insertMulti(newData.key, newData);
}
}
/*!
Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
symmetrical value error of the data points are set to the values in \a valueError.
For error bars to show appropriately, see \ref setErrorType.
The provided vectors should have equal length. Else, the number of added points will be the size of the
smallest vector.
For asymmetrical errors (plus different from minus), see the overloaded version of this function.
*/
void QCPGraph::setDataValueError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &valueError)
{
mData->clear();
int n = key.size();
n = qMin(n, value.size());
n = qMin(n, valueError.size());
QCPData newData;
for (int i=0; i<n; ++i)
{
newData.key = key[i];
newData.value = value[i];
newData.valueErrorMinus = valueError[i];
newData.valueErrorPlus = valueError[i];
mData->insertMulti(key[i], newData);
}
}
/*!
\overload
Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
negative value error of the data points are set to the values in \a valueErrorMinus, the positive
value error to \a valueErrorPlus.
For error bars to show appropriately, see \ref setErrorType.
The provided vectors should have equal length. Else, the number of added points will be the size of the
smallest vector.
*/
void QCPGraph::setDataValueError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &valueErrorMinus, const QVector<double> &valueErrorPlus)
{
mData->clear();
int n = key.size();
n = qMin(n, value.size());
n = qMin(n, valueErrorMinus.size());
n = qMin(n, valueErrorPlus.size());
QCPData newData;
for (int i=0; i<n; ++i)
{
newData.key = key[i];
newData.value = value[i];
newData.valueErrorMinus = valueErrorMinus[i];
newData.valueErrorPlus = valueErrorPlus[i];
mData->insertMulti(key[i], newData);
}
}
/*!
Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
symmetrical key error of the data points are set to the values in \a keyError.
For error bars to show appropriately, see \ref setErrorType.
The provided vectors should have equal length. Else, the number of added points will be the size of the
smallest vector.
For asymmetrical errors (plus different from minus), see the overloaded version of this function.
*/
void QCPGraph::setDataKeyError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyError)
{
mData->clear();
int n = key.size();
n = qMin(n, value.size());
n = qMin(n, keyError.size());
QCPData newData;
for (int i=0; i<n; ++i)
{
newData.key = key[i];
newData.value = value[i];
newData.keyErrorMinus = keyError[i];
newData.keyErrorPlus = keyError[i];
mData->insertMulti(key[i], newData);
}
}
/*!
\overload
Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
negative key error of the data points are set to the values in \a keyErrorMinus, the positive
key error to \a keyErrorPlus.
For error bars to show appropriately, see \ref setErrorType.
The provided vectors should have equal length. Else, the number of added points will be the size of the
smallest vector.
*/
void QCPGraph::setDataKeyError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyErrorMinus, const QVector<double> &keyErrorPlus)
{
mData->clear();
int n = key.size();
n = qMin(n, value.size());
n = qMin(n, keyErrorMinus.size());
n = qMin(n, keyErrorPlus.size());
QCPData newData;
for (int i=0; i<n; ++i)
{
newData.key = key[i];
newData.value = value[i];
newData.keyErrorMinus = keyErrorMinus[i];
newData.keyErrorPlus = keyErrorPlus[i];
mData->insertMulti(key[i], newData);
}
}
/*!
Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
symmetrical key and value errors of the data points are set to the values in \a keyError and \a valueError.
For error bars to show appropriately, see \ref setErrorType.
The provided vectors should have equal length. Else, the number of added points will be the size of the
smallest vector.
For asymmetrical errors (plus different from minus), see the overloaded version of this function.
*/
void QCPGraph::setDataBothError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyError, const QVector<double> &valueError)
{
mData->clear();
int n = key.size();
n = qMin(n, value.size());
n = qMin(n, valueError.size());
n = qMin(n, keyError.size());
QCPData newData;
for (int i=0; i<n; ++i)
{
newData.key = key[i];
newData.value = value[i];
newData.keyErrorMinus = keyError[i];
newData.keyErrorPlus = keyError[i];
newData.valueErrorMinus = valueError[i];
newData.valueErrorPlus = valueError[i];
mData->insertMulti(key[i], newData);
}
}
/*!
\overload
Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
negative key and value errors of the data points are set to the values in \a keyErrorMinus and \a valueErrorMinus. The positive
key and value errors are set to the values in \a keyErrorPlus \a valueErrorPlus.
For error bars to show appropriately, see \ref setErrorType.
The provided vectors should have equal length. Else, the number of added points will be the size of the
smallest vector.
*/
void QCPGraph::setDataBothError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyErrorMinus, const QVector<double> &keyErrorPlus, const QVector<double> &valueErrorMinus, const QVector<double> &valueErrorPlus)
{
mData->clear();
int n = key.size();
n = qMin(n, value.size());
n = qMin(n, valueErrorMinus.size());
n = qMin(n, valueErrorPlus.size());
n = qMin(n, keyErrorMinus.size());
n = qMin(n, keyErrorPlus.size());
QCPData newData;
for (int i=0; i<n; ++i)
{
newData.key = key[i];
newData.value = value[i];
newData.keyErrorMinus = keyErrorMinus[i];
newData.keyErrorPlus = keyErrorPlus[i];
newData.valueErrorMinus = valueErrorMinus[i];
newData.valueErrorPlus = valueErrorPlus[i];
mData->insertMulti(key[i], newData);
}
}
/*!
Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to
\ref lsNone and \ref setScatterStyle to the desired scatter style.
\see setScatterStyle
*/
void QCPGraph::setLineStyle(LineStyle ls)
{
mLineStyle = ls;
}
/*!
Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points
are drawn (e.g. for line-only-plots with appropriate line style).
\see QCPScatterStyle, setLineStyle
*/
void QCPGraph::setScatterStyle(const QCPScatterStyle &style)
{
mScatterStyle = style;
}
/*!
Sets which kind of error bars (Key Error, Value Error or both) should be drawn on each data
point. If you set \a errorType to something other than \ref etNone, make sure to actually pass
error data via the specific setData functions along with the data points (e.g. \ref
setDataValueError, \ref setDataKeyError, \ref setDataBothError).
\see ErrorType
*/
void QCPGraph::setErrorType(ErrorType errorType)
{
mErrorType = errorType;
}
/*!
Sets the pen with which the error bars will be drawn.
\see setErrorBarSize, setErrorType
*/
void QCPGraph::setErrorPen(const QPen &pen)
{
mErrorPen = pen;
}
/*!
Sets the width of the handles at both ends of an error bar in pixels.
*/
void QCPGraph::setErrorBarSize(double size)
{
mErrorBarSize = size;
}
/*!
If \a enabled is set to true, the error bar will not be drawn as a solid line under the scatter symbol but
leave some free space around the symbol.
This feature uses the current scatter size (\ref QCPScatterStyle::setSize) to determine the size
of the area to leave blank. So when drawing Pixmaps as scatter points (\ref
QCPScatterStyle::ssPixmap), the scatter size must be set manually to a value corresponding to the
size of the Pixmap, if the error bars should leave gaps to its boundaries.
\ref setErrorType, setErrorBarSize, setScatterStyle
*/
void QCPGraph::setErrorBarSkipSymbol(bool enabled)
{
mErrorBarSkipSymbol = enabled;
}
/*!
Sets the target graph for filling the area between this graph and \a targetGraph with the current
brush (\ref setBrush).
When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To
disable any filling, set the brush to Qt::NoBrush.
\see setBrush
*/
void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph)
{
// prevent setting channel target to this graph itself:
if (targetGraph == this)
{
qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself";
mChannelFillGraph = 0;
return;
}
// prevent setting channel target to a graph not in the plot:
if (targetGraph && targetGraph->mParentPlot != mParentPlot)
{
qDebug() << Q_FUNC_INFO << "targetGraph not in same plot";
mChannelFillGraph = 0;
return;
}
mChannelFillGraph = targetGraph;
}
/*!
Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive
sampling technique can drastically improve the replot performance for graphs with a larger number
of points (e.g. above 10,000), without notably changing the appearance of the graph.
By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive
sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no
disadvantage in almost all cases.
\image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling"
As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are
reproduced reliably, as well as the overall shape of the data set. The replot time reduces
dramatically though. This allows QCustomPlot to display large amounts of data in realtime.
\image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling"
Care must be taken when using high-density scatter plots in combination with adaptive sampling.
The adaptive sampling algorithm treats scatter plots more carefully than line plots which still
gives a significant reduction of replot times, but not quite as much as for line plots. This is
because scatter plots inherently need more data points to be preserved in order to still resemble
the original, non-adaptive-sampling plot. As shown above, the results still aren't quite
identical, as banding occurs for the outer data points. This is in fact intentional, such that
the boundaries of the data cloud stay visible to the viewer. How strong the banding appears,
depends on the point density, i.e. the number of points in the plot.
For some situations with scatter plots it might thus be desirable to manually turn adaptive
sampling off. For example, when saving the plot to disk. This can be achieved by setting \a
enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled
back to true afterwards.
*/
void QCPGraph::setAdaptiveSampling(bool enabled)
{
mAdaptiveSampling = enabled;
}
/*!
Adds the provided data points in \a dataMap to the current data.
Alternatively, you can also access and modify the graph's data via the \ref data method, which
returns a pointer to the internal \ref QCPDataMap.
\see removeData
*/
void QCPGraph::addData(const QCPDataMap &dataMap)
{
mData->unite(dataMap);
}
/*! \overload
Adds the provided single data point in \a data to the current data.
Alternatively, you can also access and modify the graph's data via the \ref data method, which
returns a pointer to the internal \ref QCPDataMap.
\see removeData
*/
void QCPGraph::addData(const QCPData &data)
{
mData->insertMulti(data.key, data);
}
/*! \overload
Adds the provided single data point as \a key and \a value pair to the current data.
Alternatively, you can also access and modify the graph's data via the \ref data method, which
returns a pointer to the internal \ref QCPDataMap.
\see removeData
*/
void QCPGraph::addData(double key, double value)
{
QCPData newData;
newData.key = key;
newData.value = value;
mData->insertMulti(newData.key, newData);
}
/*! \overload
Adds the provided data points as \a key and \a value pairs to the current data.
Alternatively, you can also access and modify the graph's data via the \ref data method, which
returns a pointer to the internal \ref QCPDataMap.
\see removeData
*/
void QCPGraph::addData(const QVector<double> &keys, const QVector<double> &values)
{
int n = qMin(keys.size(), values.size());
QCPData newData;
for (int i=0; i<n; ++i)
{
newData.key = keys[i];
newData.value = values[i];
mData->insertMulti(newData.key, newData);
}
}
/*!
Removes all data points with keys smaller than \a key.
\see addData, clearData
*/
void QCPGraph::removeDataBefore(double key)
{
QCPDataMap::iterator it = mData->begin();
while (it != mData->end() && it.key() < key)
it = mData->erase(it);
}
/*!
Removes all data points with keys greater than \a key.
\see addData, clearData
*/
void QCPGraph::removeDataAfter(double key)
{
if (mData->isEmpty()) return;
QCPDataMap::iterator it = mData->upperBound(key);
while (it != mData->end())
it = mData->erase(it);
}
/*!
Removes all data points with keys between \a fromKey and \a toKey.
if \a fromKey is greater or equal to \a toKey, the function does nothing. To remove
a single data point with known key, use \ref removeData(double key).
\see addData, clearData
*/
void QCPGraph::removeData(double fromKey, double toKey)
{
if (fromKey >= toKey || mData->isEmpty()) return;
QCPDataMap::iterator it = mData->upperBound(fromKey);
QCPDataMap::iterator itEnd = mData->upperBound(toKey);
while (it != itEnd)
it = mData->erase(it);
}
/*! \overload
Removes a single data point at \a key. If the position is not known with absolute precision,
consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval around
the suspected position, depeding on the precision with which the key is known.
\see addData, clearData
*/
void QCPGraph::removeData(double key)
{
mData->remove(key);
}
/*!
Removes all data points.
\see removeData, removeDataAfter, removeDataBefore
*/
void QCPGraph::clearData()
{
mData->clear();
}
/* inherits documentation from base class */
double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if ((onlySelectable && !mSelectable) || mData->isEmpty())
return -1;
if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
return pointDistance(pos);
else
return -1;
}
/*! \overload
Allows to define whether error bars are taken into consideration when determining the new axis
range.
\see rescaleKeyAxis, rescaleValueAxis, QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
*/
void QCPGraph::rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const
{
rescaleKeyAxis(onlyEnlarge, includeErrorBars);
rescaleValueAxis(onlyEnlarge, includeErrorBars);
}
/*! \overload
Allows to define whether error bars (of kind \ref QCPGraph::etKey) are taken into consideration
when determining the new axis range.
\see rescaleAxes, QCPAbstractPlottable::rescaleKeyAxis
*/
void QCPGraph::rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const
{
// this code is a copy of QCPAbstractPlottable::rescaleKeyAxis with the only change
// that getKeyRange is passed the includeErrorBars value.
if (mData->isEmpty()) return;
QCPAxis *keyAxis = mKeyAxis.data();
if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
SignDomain signDomain = sdBoth;
if (keyAxis->scaleType() == QCPAxis::stLogarithmic)
signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive);
bool foundRange;
QCPRange newRange = getKeyRange(foundRange, signDomain, includeErrorBars);
if (foundRange)
{
if (onlyEnlarge)
{
if (keyAxis->range().lower < newRange.lower)
newRange.lower = keyAxis->range().lower;
if (keyAxis->range().upper > newRange.upper)
newRange.upper = keyAxis->range().upper;
}
keyAxis->setRange(newRange);
}
}
/*! \overload
Allows to define whether error bars (of kind \ref QCPGraph::etValue) are taken into consideration
when determining the new axis range.
\see rescaleAxes, QCPAbstractPlottable::rescaleValueAxis
*/
void QCPGraph::rescaleValueAxis(bool onlyEnlarge, bool includeErrorBars) const
{
// this code is a copy of QCPAbstractPlottable::rescaleValueAxis with the only change
// is that getValueRange is passed the includeErrorBars value.
if (mData->isEmpty()) return;
QCPAxis *valueAxis = mValueAxis.data();
if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; }
SignDomain signDomain = sdBoth;
if (valueAxis->scaleType() == QCPAxis::stLogarithmic)
signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive);
bool foundRange;
QCPRange newRange = getValueRange(foundRange, signDomain, includeErrorBars);
if (foundRange)
{
if (onlyEnlarge)
{
if (valueAxis->range().lower < newRange.lower)
newRange.lower = valueAxis->range().lower;
if (valueAxis->range().upper > newRange.upper)
newRange.upper = valueAxis->range().upper;
}
valueAxis->setRange(newRange);
}
}
/* inherits documentation from base class */
void QCPGraph::draw(QCPPainter *painter)
{
if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (mKeyAxis.data()->range().size() <= 0 || mData->isEmpty()) return;
if (mLineStyle == lsNone && mScatterStyle.isNone()) return;
// allocate line and (if necessary) point vectors:
QVector<QPointF> *lineData = new QVector<QPointF>;
QVector<QCPData> *scatterData = 0;
if (!mScatterStyle.isNone())
scatterData = new QVector<QCPData>;
// fill vectors with data appropriate to plot style:
getPlotData(lineData, scatterData);
// check data validity if flag set:
#ifdef QCUSTOMPLOT_CHECK_DATA
QCPDataMap::const_iterator it;
for (it = mData->constBegin(); it != mData->constEnd(); ++it)
{
if (QCP::isInvalidData(it.value().key, it.value().value) ||
QCP::isInvalidData(it.value().keyErrorPlus, it.value().keyErrorMinus) ||
QCP::isInvalidData(it.value().valueErrorPlus, it.value().valueErrorPlus))
qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name();
}
#endif
// draw fill of graph:
if (mLineStyle != lsNone)
drawFill(painter, lineData);
// draw line:
if (mLineStyle == lsImpulse)
drawImpulsePlot(painter, lineData);
else if (mLineStyle != lsNone)
drawLinePlot(painter, lineData); // also step plots can be drawn as a line plot
// draw scatters:
if (scatterData)
drawScatterPlot(painter, scatterData);
// free allocated line and point vectors:
delete lineData;
if (scatterData)
delete scatterData;
}
/* inherits documentation from base class */
void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
{
// draw fill:
if (mBrush.style() != Qt::NoBrush)
{
applyFillAntialiasingHint(painter);
painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
}
// draw line vertically centered:
if (mLineStyle != lsNone)
{
applyDefaultAntialiasingHint(painter);
painter->setPen(mPen);
painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens
}
// draw scatter symbol:
if (!mScatterStyle.isNone())
{
applyScattersAntialiasingHint(painter);
// scale scatter pixmap if it's too large to fit in legend icon rect:
if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
{
QCPScatterStyle scaledStyle(mScatterStyle);
scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
scaledStyle.applyTo(painter, mPen);
scaledStyle.drawShape(painter, QRectF(rect).center());
} else
{
mScatterStyle.applyTo(painter, mPen);
mScatterStyle.drawShape(painter, QRectF(rect).center());
}
}
}
/*! \internal
This function branches out to the line style specific "get(...)PlotData" functions, according to
the line style of the graph.
\a lineData will be filled with raw points that will be drawn with the according draw functions,
e.g. \ref drawLinePlot and \ref drawImpulsePlot. These aren't necessarily the original data
points, since for step plots for example, additional points are needed for drawing lines that
make up steps. If the line style of the graph is \ref lsNone, the \a lineData vector will be left
untouched.
\a scatterData will be filled with the original data points so \ref drawScatterPlot can draw the
scatter symbols accordingly. If no scatters need to be drawn, i.e. the scatter style's shape is
\ref QCPScatterStyle::ssNone, pass 0 as \a scatterData, and this step will be skipped.
\see getScatterPlotData, getLinePlotData, getStepLeftPlotData, getStepRightPlotData,
getStepCenterPlotData, getImpulsePlotData
*/
void QCPGraph::getPlotData(QVector<QPointF> *lineData, QVector<QCPData> *scatterData) const
{
switch(mLineStyle)
{
case lsNone: getScatterPlotData(scatterData); break;
case lsLine: getLinePlotData(lineData, scatterData); break;
case lsStepLeft: getStepLeftPlotData(lineData, scatterData); break;
case lsStepRight: getStepRightPlotData(lineData, scatterData); break;
case lsStepCenter: getStepCenterPlotData(lineData, scatterData); break;
case lsImpulse: getImpulsePlotData(lineData, scatterData); break;
}
}
/*! \internal
If line style is \ref lsNone and the scatter style's shape is not \ref QCPScatterStyle::ssNone,
this function serves at providing the visible data points in \a scatterData, so the \ref
drawScatterPlot function can draw the scatter points accordingly.
If line style is not \ref lsNone, this function is not called and the data for the scatter points
are (if needed) calculated inside the corresponding other "get(...)PlotData" functions.
\see drawScatterPlot
*/
void QCPGraph::getScatterPlotData(QVector<QCPData> *scatterData) const
{
getPreparedData(0, scatterData);
}
/*! \internal
Places the raw data points needed for a normal linearly connected graph in \a linePixelData.
As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter)
points that are visible for drawing scatter points, if necessary. If drawing scatter points is
disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
scatterData, and the function will skip filling the vector.
\see drawLinePlot
*/
void QCPGraph::getLinePlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; return; }
QVector<QCPData> lineData;
getPreparedData(&lineData, scatterData);
linePixelData->reserve(lineData.size()+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
linePixelData->resize(lineData.size());
// transform lineData points to pixels:
if (keyAxis->orientation() == Qt::Vertical)
{
for (int i=0; i<lineData.size(); ++i)
{
(*linePixelData)[i].setX(valueAxis->coordToPixel(lineData.at(i).value));
(*linePixelData)[i].setY(keyAxis->coordToPixel(lineData.at(i).key));
}
} else // key axis is horizontal
{
for (int i=0; i<lineData.size(); ++i)
{
(*linePixelData)[i].setX(keyAxis->coordToPixel(lineData.at(i).key));
(*linePixelData)[i].setY(valueAxis->coordToPixel(lineData.at(i).value));
}
}
}
/*!
\internal
Places the raw data points needed for a step plot with left oriented steps in \a lineData.
As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter)
points that are visible for drawing scatter points, if necessary. If drawing scatter points is
disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
scatterData, and the function will skip filling the vector.
\see drawLinePlot
*/
void QCPGraph::getStepLeftPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; }
QVector<QCPData> lineData;
getPreparedData(&lineData, scatterData);
linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
linePixelData->resize(lineData.size()*2);
// calculate steps from lineData and transform to pixel coordinates:
if (keyAxis->orientation() == Qt::Vertical)
{
double lastValue = valueAxis->coordToPixel(lineData.first().value);
double key;
for (int i=0; i<lineData.size(); ++i)
{
key = keyAxis->coordToPixel(lineData.at(i).key);
(*linePixelData)[i*2+0].setX(lastValue);
(*linePixelData)[i*2+0].setY(key);
lastValue = valueAxis->coordToPixel(lineData.at(i).value);
(*linePixelData)[i*2+1].setX(lastValue);
(*linePixelData)[i*2+1].setY(key);
}
} else // key axis is horizontal
{
double lastValue = valueAxis->coordToPixel(lineData.first().value);
double key;
for (int i=0; i<lineData.size(); ++i)
{
key = keyAxis->coordToPixel(lineData.at(i).key);
(*linePixelData)[i*2+0].setX(key);
(*linePixelData)[i*2+0].setY(lastValue);
lastValue = valueAxis->coordToPixel(lineData.at(i).value);
(*linePixelData)[i*2+1].setX(key);
(*linePixelData)[i*2+1].setY(lastValue);
}
}
}
/*!
\internal
Places the raw data points needed for a step plot with right oriented steps in \a lineData.
As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter)
points that are visible for drawing scatter points, if necessary. If drawing scatter points is
disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
scatterData, and the function will skip filling the vector.
\see drawLinePlot
*/
void QCPGraph::getStepRightPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; }
QVector<QCPData> lineData;
getPreparedData(&lineData, scatterData);
linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
linePixelData->resize(lineData.size()*2);
// calculate steps from lineData and transform to pixel coordinates:
if (keyAxis->orientation() == Qt::Vertical)
{
double lastKey = keyAxis->coordToPixel(lineData.first().key);
double value;
for (int i=0; i<lineData.size(); ++i)
{
value = valueAxis->coordToPixel(lineData.at(i).value);
(*linePixelData)[i*2+0].setX(value);
(*linePixelData)[i*2+0].setY(lastKey);
lastKey = keyAxis->coordToPixel(lineData.at(i).key);
(*linePixelData)[i*2+1].setX(value);
(*linePixelData)[i*2+1].setY(lastKey);
}
} else // key axis is horizontal
{
double lastKey = keyAxis->coordToPixel(lineData.first().key);
double value;
for (int i=0; i<lineData.size(); ++i)
{
value = valueAxis->coordToPixel(lineData.at(i).value);
(*linePixelData)[i*2+0].setX(lastKey);
(*linePixelData)[i*2+0].setY(value);
lastKey = keyAxis->coordToPixel(lineData.at(i).key);
(*linePixelData)[i*2+1].setX(lastKey);
(*linePixelData)[i*2+1].setY(value);
}
}
}
/*!
\internal
Places the raw data points needed for a step plot with centered steps in \a lineData.
As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter)
points that are visible for drawing scatter points, if necessary. If drawing scatter points is
disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
scatterData, and the function will skip filling the vector.
\see drawLinePlot
*/
void QCPGraph::getStepCenterPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; }
QVector<QCPData> lineData;
getPreparedData(&lineData, scatterData);
linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
linePixelData->resize(lineData.size()*2);
// calculate steps from lineData and transform to pixel coordinates:
if (keyAxis->orientation() == Qt::Vertical)
{
double lastKey = keyAxis->coordToPixel(lineData.first().key);
double lastValue = valueAxis->coordToPixel(lineData.first().value);
double key;
(*linePixelData)[0].setX(lastValue);
(*linePixelData)[0].setY(lastKey);
for (int i=1; i<lineData.size(); ++i)
{
key = (keyAxis->coordToPixel(lineData.at(i).key)+lastKey)*0.5;
(*linePixelData)[i*2-1].setX(lastValue);
(*linePixelData)[i*2-1].setY(key);
lastValue = valueAxis->coordToPixel(lineData.at(i).value);
lastKey = keyAxis->coordToPixel(lineData.at(i).key);
(*linePixelData)[i*2+0].setX(lastValue);
(*linePixelData)[i*2+0].setY(key);
}
(*linePixelData)[lineData.size()*2-1].setX(lastValue);
(*linePixelData)[lineData.size()*2-1].setY(lastKey);
} else // key axis is horizontal
{
double lastKey = keyAxis->coordToPixel(lineData.first().key);
double lastValue = valueAxis->coordToPixel(lineData.first().value);
double key;
(*linePixelData)[0].setX(lastKey);
(*linePixelData)[0].setY(lastValue);
for (int i=1; i<lineData.size(); ++i)
{
key = (keyAxis->coordToPixel(lineData.at(i).key)+lastKey)*0.5;
(*linePixelData)[i*2-1].setX(key);
(*linePixelData)[i*2-1].setY(lastValue);
lastValue = valueAxis->coordToPixel(lineData.at(i).value);
lastKey = keyAxis->coordToPixel(lineData.at(i).key);
(*linePixelData)[i*2+0].setX(key);
(*linePixelData)[i*2+0].setY(lastValue);
}
(*linePixelData)[lineData.size()*2-1].setX(lastKey);
(*linePixelData)[lineData.size()*2-1].setY(lastValue);
}
}
/*!
\internal
Places the raw data points needed for an impulse plot in \a lineData.
As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter)
points that are visible for drawing scatter points, if necessary. If drawing scatter points is
disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
scatterData, and the function will skip filling the vector.
\see drawImpulsePlot
*/
void QCPGraph::getImpulsePlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; return; }
QVector<QCPData> lineData;
getPreparedData(&lineData, scatterData);
linePixelData->resize(lineData.size()*2); // no need to reserve 2 extra points because impulse plot has no fill
// transform lineData points to pixels:
if (keyAxis->orientation() == Qt::Vertical)
{
double zeroPointX = valueAxis->coordToPixel(0);
double key;
for (int i=0; i<lineData.size(); ++i)
{
key = keyAxis->coordToPixel(lineData.at(i).key);
(*linePixelData)[i*2+0].setX(zeroPointX);
(*linePixelData)[i*2+0].setY(key);
(*linePixelData)[i*2+1].setX(valueAxis->coordToPixel(lineData.at(i).value));
(*linePixelData)[i*2+1].setY(key);
}
} else // key axis is horizontal
{
double zeroPointY = valueAxis->coordToPixel(0);
double key;
for (int i=0; i<lineData.size(); ++i)
{
key = keyAxis->coordToPixel(lineData.at(i).key);
(*linePixelData)[i*2+0].setX(key);
(*linePixelData)[i*2+0].setY(zeroPointY);
(*linePixelData)[i*2+1].setX(key);
(*linePixelData)[i*2+1].setY(valueAxis->coordToPixel(lineData.at(i).value));
}
}
}
/*! \internal
Draws the fill of the graph with the specified brush.
If the fill is a normal fill towards the zero-value-line, only the \a lineData is required (and
two extra points at the zero-value-line, which are added by \ref addFillBasePoints and removed by
\ref removeFillBasePoints after the fill drawing is done).
If the fill is a channel fill between this QCPGraph and another QCPGraph (mChannelFillGraph), the
more complex polygon is calculated with the \ref getChannelFillPolygon function.
\see drawLinePlot
*/
void QCPGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lineData) const
{
if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot
if (mainBrush().style() == Qt::NoBrush || mainBrush().color().alpha() == 0) return;
applyFillAntialiasingHint(painter);
if (!mChannelFillGraph)
{
// draw base fill under graph, fill goes all the way to the zero-value-line:
addFillBasePoints(lineData);
painter->setPen(Qt::NoPen);
painter->setBrush(mainBrush());
painter->drawPolygon(QPolygonF(*lineData));
removeFillBasePoints(lineData);
} else
{
// draw channel fill between this graph and mChannelFillGraph:
painter->setPen(Qt::NoPen);
painter->setBrush(mainBrush());
painter->drawPolygon(getChannelFillPolygon(lineData));
}
}
/*! \internal
Draws scatter symbols at every data point passed in \a scatterData. scatter symbols are independent
of the line style and are always drawn if the scatter style's shape is not \ref
QCPScatterStyle::ssNone. Hence, the \a scatterData vector is outputted by all "get(...)PlotData"
functions, together with the (line style dependent) line data.
\see drawLinePlot, drawImpulsePlot
*/
void QCPGraph::drawScatterPlot(QCPPainter *painter, QVector<QCPData> *scatterData) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
// draw error bars:
if (mErrorType != etNone)
{
applyErrorBarsAntialiasingHint(painter);
painter->setPen(mErrorPen);
if (keyAxis->orientation() == Qt::Vertical)
{
for (int i=0; i<scatterData->size(); ++i)
drawError(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key), scatterData->at(i));
} else
{
for (int i=0; i<scatterData->size(); ++i)
drawError(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value), scatterData->at(i));
}
}
// draw scatter point symbols:
applyScattersAntialiasingHint(painter);
mScatterStyle.applyTo(painter, mPen);
if (keyAxis->orientation() == Qt::Vertical)
{
for (int i=0; i<scatterData->size(); ++i)
if (!qIsNaN(scatterData->at(i).value))
mScatterStyle.drawShape(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key));
} else
{
for (int i=0; i<scatterData->size(); ++i)
if (!qIsNaN(scatterData->at(i).value))
mScatterStyle.drawShape(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value));
}
}
/*! \internal
Draws line graphs from the provided data. It connects all points in \a lineData, which was
created by one of the "get(...)PlotData" functions for line styles that require simple line
connections between the point vector they create. These are for example \ref getLinePlotData,
\ref getStepLeftPlotData, \ref getStepRightPlotData and \ref getStepCenterPlotData.
\see drawScatterPlot, drawImpulsePlot
*/
void QCPGraph::drawLinePlot(QCPPainter *painter, QVector<QPointF> *lineData) const
{
// draw line of graph:
if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)
{
applyDefaultAntialiasingHint(painter);
painter->setPen(mainPen());
painter->setBrush(Qt::NoBrush);
/* Draws polyline in batches, currently not used:
int p = 0;
while (p < lineData->size())
{
int batch = qMin(25, lineData->size()-p);
if (p != 0)
{
++batch;
--p; // to draw the connection lines between two batches
}
painter->drawPolyline(lineData->constData()+p, batch);
p += batch;
}
*/
// if drawing solid line and not in PDF, use much faster line drawing instead of polyline:
if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) &&
painter->pen().style() == Qt::SolidLine &&
!painter->modes().testFlag(QCPPainter::pmVectorized) &&
!painter->modes().testFlag(QCPPainter::pmNoCaching))
{
int i = 0;
bool lastIsNan = false;
const int lineDataSize = lineData->size();
while (i < lineDataSize && (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x()))) // make sure first point is not NaN
++i;
++i; // because drawing works in 1 point retrospect
while (i < lineDataSize)
{
if (!qIsNaN(lineData->at(i).y()) && !qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line
{
if (!lastIsNan)
painter->drawLine(lineData->at(i-1), lineData->at(i));
else
lastIsNan = false;
} else
lastIsNan = true;
++i;
}
} else
{
int segmentStart = 0;
int i = 0;
const int lineDataSize = lineData->size();
while (i < lineDataSize)
{
if (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x()) || qIsInf(lineData->at(i).y())) // NaNs create a gap in the line. Also filter Infs which make drawPolyline block
{
painter->drawPolyline(lineData->constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point
segmentStart = i+1;
}
++i;
}
// draw last segment:
painter->drawPolyline(lineData->constData()+segmentStart, lineDataSize-segmentStart);
}
}
}
/*! \internal
Draws impulses from the provided data, i.e. it connects all line pairs in \a lineData, which was
created by \ref getImpulsePlotData.
\see drawScatterPlot, drawLinePlot
*/
void QCPGraph::drawImpulsePlot(QCPPainter *painter, QVector<QPointF> *lineData) const
{
// draw impulses:
if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)
{
applyDefaultAntialiasingHint(painter);
QPen pen = mainPen();
pen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line
painter->setPen(pen);
painter->setBrush(Qt::NoBrush);
painter->drawLines(*lineData);
}
}
/*! \internal
Returns the \a lineData and \a scatterData that need to be plotted for this graph taking into
consideration the current axis ranges and, if \ref setAdaptiveSampling is enabled, local point
densities.
0 may be passed as \a lineData or \a scatterData to indicate that the respective dataset isn't
needed. For example, if the scatter style (\ref setScatterStyle) is \ref QCPScatterStyle::ssNone, \a
scatterData should be 0 to prevent unnecessary calculations.
This method is used by the various "get(...)PlotData" methods to get the basic working set of data.
*/
void QCPGraph::getPreparedData(QVector<QCPData> *lineData, QVector<QCPData> *scatterData) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
// get visible data range:
QCPDataMap::const_iterator lower, upper; // note that upper is the actual upper point, and not 1 step after the upper point
getVisibleDataBounds(lower, upper);
if (lower == mData->constEnd() || upper == mData->constEnd())
return;
// count points in visible range, taking into account that we only need to count to the limit maxCount if using adaptive sampling:
int maxCount = std::numeric_limits<int>::max();
if (mAdaptiveSampling)
{
int keyPixelSpan = qAbs(keyAxis->coordToPixel(lower.key())-keyAxis->coordToPixel(upper.key()));
maxCount = 2*keyPixelSpan+2;
}
int dataCount = countDataInBounds(lower, upper, maxCount);
if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
{
if (lineData)
{
QCPDataMap::const_iterator it = lower;
QCPDataMap::const_iterator upperEnd = upper+1;
double minValue = it.value().value;
double maxValue = it.value().value;
QCPDataMap::const_iterator currentIntervalFirstPoint = it;
int reversedFactor = keyAxis->rangeReversed() != (keyAxis->orientation()==Qt::Vertical) ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction
int reversedRound = keyAxis->rangeReversed() != (keyAxis->orientation()==Qt::Vertical) ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound));
double lastIntervalEndKey = currentIntervalStartKey;
double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
int intervalDataCount = 1;
++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect
while (it != upperEnd)
{
if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary
{
if (it.value().value < minValue)
minValue = it.value().value;
else if (it.value().value > maxValue)
maxValue = it.value().value;
++intervalDataCount;
} else // new pixel interval started
{
if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
{
if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point is further away, so first point of this cluster must be at a real data point
lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint.value().value));
lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
if (it.key() > currentIntervalStartKey+keyEpsilon*2) // new pixel started further away from previous cluster, so make sure the last point of the cluster is at a real data point
lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.8, (it-1).value().value));
} else
lineData->append(QCPData(currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value));
lastIntervalEndKey = (it-1).value().key;
minValue = it.value().value;
maxValue = it.value().value;
currentIntervalFirstPoint = it;
currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key())+reversedRound));
if (keyEpsilonVariable)
keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
intervalDataCount = 1;
}
++it;
}
// handle last interval:
if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
{
if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point wasn't a cluster, so first point of this cluster must be at a real data point
lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint.value().value));
lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
} else
lineData->append(QCPData(currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value));
}
if (scatterData)
{
double valueMaxRange = valueAxis->range().upper;
double valueMinRange = valueAxis->range().lower;
QCPDataMap::const_iterator it = lower;
QCPDataMap::const_iterator upperEnd = upper+1;
double minValue = it.value().value;
double maxValue = it.value().value;
QCPDataMap::const_iterator minValueIt = it;
QCPDataMap::const_iterator maxValueIt = it;
QCPDataMap::const_iterator currentIntervalStart = it;
int reversedFactor = keyAxis->rangeReversed() ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction
int reversedRound = keyAxis->rangeReversed() ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound));
double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
int intervalDataCount = 1;
++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect
while (it != upperEnd)
{
if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary
{
if (it.value().value < minValue && it.value().value > valueMinRange && it.value().value < valueMaxRange)
{
minValue = it.value().value;
minValueIt = it;
} else if (it.value().value > maxValue && it.value().value > valueMinRange && it.value().value < valueMaxRange)
{
maxValue = it.value().value;
maxValueIt = it;
}
++intervalDataCount;
} else // new pixel started
{
if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
{
// determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
QCPDataMap::const_iterator intervalIt = currentIntervalStart;
int c = 0;
while (intervalIt != it)
{
if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange)
scatterData->append(intervalIt.value());
++c;
++intervalIt;
}
} else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange)
scatterData->append(currentIntervalStart.value());
minValue = it.value().value;
maxValue = it.value().value;
currentIntervalStart = it;
currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key())+reversedRound));
if (keyEpsilonVariable)
keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
intervalDataCount = 1;
}
++it;
}
// handle last interval:
if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
{
// determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
QCPDataMap::const_iterator intervalIt = currentIntervalStart;
int c = 0;
while (intervalIt != it)
{
if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange)
scatterData->append(intervalIt.value());
++c;
++intervalIt;
}
} else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange)
scatterData->append(currentIntervalStart.value());
}
} else // don't use adaptive sampling algorithm, transfer points one-to-one from the map into the output parameters
{
QVector<QCPData> *dataVector = 0;
if (lineData)
dataVector = lineData;
else if (scatterData)
dataVector = scatterData;
if (dataVector)
{
QCPDataMap::const_iterator it = lower;
QCPDataMap::const_iterator upperEnd = upper+1;
dataVector->reserve(dataCount+2); // +2 for possible fill end points
while (it != upperEnd)
{
dataVector->append(it.value());
++it;
}
}
if (lineData && scatterData)
*scatterData = *dataVector;
}
}
/*! \internal
called by the scatter drawing function (\ref drawScatterPlot) to draw the error bars on one data
point. \a x and \a y pixel positions of the data point are passed since they are already known in
pixel coordinates in the drawing function, so we save some extra coordToPixel transforms here. \a
data is therefore only used for the errors, not key and value.
*/
void QCPGraph::drawError(QCPPainter *painter, double x, double y, const QCPData &data) const
{
if (qIsNaN(data.value))
return;
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
double a, b; // positions of error bar bounds in pixels
double barWidthHalf = mErrorBarSize*0.5;
double skipSymbolMargin = mScatterStyle.size(); // pixels left blank per side, when mErrorBarSkipSymbol is true
if (keyAxis->orientation() == Qt::Vertical)
{
// draw key error vertically and value error horizontally
if (mErrorType == etKey || mErrorType == etBoth)
{
a = keyAxis->coordToPixel(data.key-data.keyErrorMinus);
b = keyAxis->coordToPixel(data.key+data.keyErrorPlus);
if (keyAxis->rangeReversed())
qSwap(a,b);
// draw spine:
if (mErrorBarSkipSymbol)
{
if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin
painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin));
if (y-b > skipSymbolMargin)
painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b));
} else
painter->drawLine(QLineF(x, a, x, b));
// draw handles:
painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a));
painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b));
}
if (mErrorType == etValue || mErrorType == etBoth)
{
a = valueAxis->coordToPixel(data.value-data.valueErrorMinus);
b = valueAxis->coordToPixel(data.value+data.valueErrorPlus);
if (valueAxis->rangeReversed())
qSwap(a,b);
// draw spine:
if (mErrorBarSkipSymbol)
{
if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin
painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y));
if (b-x > skipSymbolMargin)
painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y));
} else
painter->drawLine(QLineF(a, y, b, y));
// draw handles:
painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf));
painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf));
}
} else // mKeyAxis->orientation() is Qt::Horizontal
{
// draw value error vertically and key error horizontally
if (mErrorType == etKey || mErrorType == etBoth)
{
a = keyAxis->coordToPixel(data.key-data.keyErrorMinus);
b = keyAxis->coordToPixel(data.key+data.keyErrorPlus);
if (keyAxis->rangeReversed())
qSwap(a,b);
// draw spine:
if (mErrorBarSkipSymbol)
{
if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin
painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y));
if (b-x > skipSymbolMargin)
painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y));
} else
painter->drawLine(QLineF(a, y, b, y));
// draw handles:
painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf));
painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf));
}
if (mErrorType == etValue || mErrorType == etBoth)
{
a = valueAxis->coordToPixel(data.value-data.valueErrorMinus);
b = valueAxis->coordToPixel(data.value+data.valueErrorPlus);
if (valueAxis->rangeReversed())
qSwap(a,b);
// draw spine:
if (mErrorBarSkipSymbol)
{
if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin
painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin));
if (y-b > skipSymbolMargin)
painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b));
} else
painter->drawLine(QLineF(x, a, x, b));
// draw handles:
painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a));
painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b));
}
}
}
/*! \internal
called by \ref getPreparedData to determine which data (key) range is visible at the current key
axis range setting, so only that needs to be processed.
\a lower returns an iterator to the lowest data point that needs to be taken into account when
plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
lower may still be just outside the visible range.
\a upper returns an iterator to the highest data point. Same as before, \a upper may also lie
just outside of the visible range.
if the graph contains no data, both \a lower and \a upper point to constEnd.
*/
void QCPGraph::getVisibleDataBounds(QCPDataMap::const_iterator &lower, QCPDataMap::const_iterator &upper) const
{
if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
if (mData->isEmpty())
{
lower = mData->constEnd();
upper = mData->constEnd();
return;
}
// get visible data range as QMap iterators
QCPDataMap::const_iterator lbound = mData->lowerBound(mKeyAxis.data()->range().lower);
QCPDataMap::const_iterator ubound = mData->upperBound(mKeyAxis.data()->range().upper);
bool lowoutlier = lbound != mData->constBegin(); // indicates whether there exist points below axis range
bool highoutlier = ubound != mData->constEnd(); // indicates whether there exist points above axis range
lower = (lowoutlier ? lbound-1 : lbound); // data point range that will be actually drawn
upper = (highoutlier ? ubound : ubound-1); // data point range that will be actually drawn
}
/*! \internal
Counts the number of data points between \a lower and \a upper (including them), up to a maximum
of \a maxCount.
This function is used by \ref getPreparedData to determine whether adaptive sampling shall be
used (if enabled via \ref setAdaptiveSampling) or not. This is also why counting of data points
only needs to be done until \a maxCount is reached, which should be set to the number of data
points at which adaptive sampling sets in.
*/
int QCPGraph::countDataInBounds(const QCPDataMap::const_iterator &lower, const QCPDataMap::const_iterator &upper, int maxCount) const
{
if (upper == mData->constEnd() && lower == mData->constEnd())
return 0;
QCPDataMap::const_iterator it = lower;
int count = 1;
while (it != upper && count < maxCount)
{
++it;
++count;
}
return count;
}
/*! \internal
The line data vector generated by e.g. getLinePlotData contains only the line that connects the
data points. If the graph needs to be filled, two additional points need to be added at the
value-zero-line in the lower and upper key positions of the graph. This function calculates these
points and adds them to the end of \a lineData. Since the fill is typically drawn before the line
stroke, these added points need to be removed again after the fill is done, with the
removeFillBasePoints function.
The expanding of \a lineData by two points will not cause unnecessary memory reallocations,
because the data vector generation functions (getLinePlotData etc.) reserve two extra points when
they allocate memory for \a lineData.
\see removeFillBasePoints, lowerFillBasePoint, upperFillBasePoint
*/
void QCPGraph::addFillBasePoints(QVector<QPointF> *lineData) const
{
if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
if (!lineData) { qDebug() << Q_FUNC_INFO << "passed null as lineData"; return; }
if (lineData->isEmpty()) return;
// append points that close the polygon fill at the key axis:
if (mKeyAxis.data()->orientation() == Qt::Vertical)
{
*lineData << upperFillBasePoint(lineData->last().y());
*lineData << lowerFillBasePoint(lineData->first().y());
} else
{
*lineData << upperFillBasePoint(lineData->last().x());
*lineData << lowerFillBasePoint(lineData->first().x());
}
}
/*! \internal
removes the two points from \a lineData that were added by \ref addFillBasePoints.
\see addFillBasePoints, lowerFillBasePoint, upperFillBasePoint
*/
void QCPGraph::removeFillBasePoints(QVector<QPointF> *lineData) const
{
if (!lineData) { qDebug() << Q_FUNC_INFO << "passed null as lineData"; return; }
if (lineData->isEmpty()) return;
lineData->remove(lineData->size()-2, 2);
}
/*! \internal
called by \ref addFillBasePoints to conveniently assign the point which closes the fill polygon
on the lower side of the zero-value-line parallel to the key axis. The logarithmic axis scale
case is a bit special, since the zero-value-line in pixel coordinates is in positive or negative
infinity. So this case is handled separately by just closing the fill polygon on the axis which
lies in the direction towards the zero value.
\a lowerKey will be the the key (in pixels) of the returned point. Depending on whether the key
axis is horizontal or vertical, \a lowerKey will end up as the x or y value of the returned
point, respectively.
\see upperFillBasePoint, addFillBasePoints
*/
QPointF QCPGraph::lowerFillBasePoint(double lowerKey) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
QPointF point;
if (valueAxis->scaleType() == QCPAxis::stLinear)
{
if (keyAxis->axisType() == QCPAxis::atLeft)
{
point.setX(valueAxis->coordToPixel(0));
point.setY(lowerKey);
} else if (keyAxis->axisType() == QCPAxis::atRight)
{
point.setX(valueAxis->coordToPixel(0));
point.setY(lowerKey);
} else if (keyAxis->axisType() == QCPAxis::atTop)
{
point.setX(lowerKey);
point.setY(valueAxis->coordToPixel(0));
} else if (keyAxis->axisType() == QCPAxis::atBottom)
{
point.setX(lowerKey);
point.setY(valueAxis->coordToPixel(0));
}
} else // valueAxis->mScaleType == QCPAxis::stLogarithmic
{
// In logarithmic scaling we can't just draw to value zero so we just fill all the way
// to the axis which is in the direction towards zero
if (keyAxis->orientation() == Qt::Vertical)
{
if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
(valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
point.setX(keyAxis->axisRect()->right());
else
point.setX(keyAxis->axisRect()->left());
point.setY(lowerKey);
} else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom)
{
point.setX(lowerKey);
if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
(valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
point.setY(keyAxis->axisRect()->top());
else
point.setY(keyAxis->axisRect()->bottom());
}
}
return point;
}
/*! \internal
called by \ref addFillBasePoints to conveniently assign the point which closes the fill
polygon on the upper side of the zero-value-line parallel to the key axis. The logarithmic axis
scale case is a bit special, since the zero-value-line in pixel coordinates is in positive or
negative infinity. So this case is handled separately by just closing the fill polygon on the
axis which lies in the direction towards the zero value.
\a upperKey will be the the key (in pixels) of the returned point. Depending on whether the key
axis is horizontal or vertical, \a upperKey will end up as the x or y value of the returned
point, respectively.
\see lowerFillBasePoint, addFillBasePoints
*/
QPointF QCPGraph::upperFillBasePoint(double upperKey) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
QPointF point;
if (valueAxis->scaleType() == QCPAxis::stLinear)
{
if (keyAxis->axisType() == QCPAxis::atLeft)
{
point.setX(valueAxis->coordToPixel(0));
point.setY(upperKey);
} else if (keyAxis->axisType() == QCPAxis::atRight)
{
point.setX(valueAxis->coordToPixel(0));
point.setY(upperKey);
} else if (keyAxis->axisType() == QCPAxis::atTop)
{
point.setX(upperKey);
point.setY(valueAxis->coordToPixel(0));
} else if (keyAxis->axisType() == QCPAxis::atBottom)
{
point.setX(upperKey);
point.setY(valueAxis->coordToPixel(0));
}
} else // valueAxis->mScaleType == QCPAxis::stLogarithmic
{
// In logarithmic scaling we can't just draw to value 0 so we just fill all the way
// to the axis which is in the direction towards 0
if (keyAxis->orientation() == Qt::Vertical)
{
if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
(valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
point.setX(keyAxis->axisRect()->right());
else
point.setX(keyAxis->axisRect()->left());
point.setY(upperKey);
} else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom)
{
point.setX(upperKey);
if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
(valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
point.setY(keyAxis->axisRect()->top());
else
point.setY(keyAxis->axisRect()->bottom());
}
}
return point;
}
/*! \internal
Generates the polygon needed for drawing channel fills between this graph (data passed via \a
lineData) and the graph specified by mChannelFillGraph (data generated by calling its \ref
getPlotData function). May return an empty polygon if the key ranges have no overlap or fill
target graph and this graph don't have same orientation (i.e. both key axes horizontal or both
key axes vertical). For increased performance (due to implicit sharing), keep the returned
QPolygonF const.
*/
const QPolygonF QCPGraph::getChannelFillPolygon(const QVector<QPointF> *lineData) const
{
if (!mChannelFillGraph)
return QPolygonF();
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); }
if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); }
if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation())
return QPolygonF(); // don't have same axis orientation, can't fill that (Note: if keyAxis fits, valueAxis will fit too, because it's always orthogonal to keyAxis)
if (lineData->isEmpty()) return QPolygonF();
QVector<QPointF> otherData;
mChannelFillGraph.data()->getPlotData(&otherData, 0);
if (otherData.isEmpty()) return QPolygonF();
QVector<QPointF> thisData;
thisData.reserve(lineData->size()+otherData.size()); // because we will join both vectors at end of this function
for (int i=0; i<lineData->size(); ++i) // don't use the vector<<(vector), it squeezes internally, which ruins the performance tuning with reserve()
thisData << lineData->at(i);
// pointers to be able to swap them, depending which data range needs cropping:
QVector<QPointF> *staticData = &thisData;
QVector<QPointF> *croppedData = &otherData;
// crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType):
if (keyAxis->orientation() == Qt::Horizontal)
{
// x is key
// if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys:
if (staticData->first().x() > staticData->last().x())
{
int size = staticData->size();
for (int i=0; i<size/2; ++i)
qSwap((*staticData)[i], (*staticData)[size-1-i]);
}
if (croppedData->first().x() > croppedData->last().x())
{
int size = croppedData->size();
for (int i=0; i<size/2; ++i)
qSwap((*croppedData)[i], (*croppedData)[size-1-i]);
}
// crop lower bound:
if (staticData->first().x() < croppedData->first().x()) // other one must be cropped
qSwap(staticData, croppedData);
int lowBound = findIndexBelowX(croppedData, staticData->first().x());
if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
croppedData->remove(0, lowBound);
// set lowest point of cropped data to fit exactly key position of first static data
// point via linear interpolation:
if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
double slope;
if (croppedData->at(1).x()-croppedData->at(0).x() != 0)
slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x());
else
slope = 0;
(*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x()));
(*croppedData)[0].setX(staticData->first().x());
// crop upper bound:
if (staticData->last().x() > croppedData->last().x()) // other one must be cropped
qSwap(staticData, croppedData);
int highBound = findIndexAboveX(croppedData, staticData->last().x());
if (highBound == -1) return QPolygonF(); // key ranges have no overlap
croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
// set highest point of cropped data to fit exactly key position of last static data
// point via linear interpolation:
if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
int li = croppedData->size()-1; // last index
if (croppedData->at(li).x()-croppedData->at(li-1).x() != 0)
slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x());
else
slope = 0;
(*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x()));
(*croppedData)[li].setX(staticData->last().x());
} else // mKeyAxis->orientation() == Qt::Vertical
{
// y is key
// similar to "x is key" but switched x,y. Further, lower/upper meaning is inverted compared to x,
// because in pixel coordinates, y increases from top to bottom, not bottom to top like data coordinate.
// if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys:
if (staticData->first().y() < staticData->last().y())
{
int size = staticData->size();
for (int i=0; i<size/2; ++i)
qSwap((*staticData)[i], (*staticData)[size-1-i]);
}
if (croppedData->first().y() < croppedData->last().y())
{
int size = croppedData->size();
for (int i=0; i<size/2; ++i)
qSwap((*croppedData)[i], (*croppedData)[size-1-i]);
}
// crop lower bound:
if (staticData->first().y() > croppedData->first().y()) // other one must be cropped
qSwap(staticData, croppedData);
int lowBound = findIndexAboveY(croppedData, staticData->first().y());
if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
croppedData->remove(0, lowBound);
// set lowest point of cropped data to fit exactly key position of first static data
// point via linear interpolation:
if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
double slope;
if (croppedData->at(1).y()-croppedData->at(0).y() != 0) // avoid division by zero in step plots
slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y());
else
slope = 0;
(*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y()));
(*croppedData)[0].setY(staticData->first().y());
// crop upper bound:
if (staticData->last().y() < croppedData->last().y()) // other one must be cropped
qSwap(staticData, croppedData);
int highBound = findIndexBelowY(croppedData, staticData->last().y());
if (highBound == -1) return QPolygonF(); // key ranges have no overlap
croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
// set highest point of cropped data to fit exactly key position of last static data
// point via linear interpolation:
if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
int li = croppedData->size()-1; // last index
if (croppedData->at(li).y()-croppedData->at(li-1).y() != 0) // avoid division by zero in step plots
slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y());
else
slope = 0;
(*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y()));
(*croppedData)[li].setY(staticData->last().y());
}
// return joined:
for (int i=otherData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted
thisData << otherData.at(i);
return QPolygonF(thisData);
}
/*! \internal
Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in
\a data points are ordered ascending, as is the case when plotting with horizontal key axis.
Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
*/
int QCPGraph::findIndexAboveX(const QVector<QPointF> *data, double x) const
{
for (int i=data->size()-1; i>=0; --i)
{
if (data->at(i).x() < x)
{
if (i<data->size()-1)
return i+1;
else
return data->size()-1;
}
}
return -1;
}
/*! \internal
Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in
\a data points are ordered ascending, as is the case when plotting with horizontal key axis.
Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
*/
int QCPGraph::findIndexBelowX(const QVector<QPointF> *data, double x) const
{
for (int i=0; i<data->size(); ++i)
{
if (data->at(i).x() > x)
{
if (i>0)
return i-1;
else
return 0;
}
}
return -1;
}
/*! \internal
Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in
\a data points are ordered descending, as is the case when plotting with vertical key axis.
Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
*/
int QCPGraph::findIndexAboveY(const QVector<QPointF> *data, double y) const
{
for (int i=0; i<data->size(); ++i)
{
if (data->at(i).y() < y)
{
if (i>0)
return i-1;
else
return 0;
}
}
return -1;
}
/*! \internal
Calculates the (minimum) distance (in pixels) the graph's representation has from the given \a
pixelPoint in pixels. This is used to determine whether the graph was clicked or not, e.g. in
\ref selectTest.
If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape
is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns -1.0.
*/
double QCPGraph::pointDistance(const QPointF &pixelPoint) const
{
if (mData->isEmpty())
return -1.0;
if (mLineStyle == lsNone && mScatterStyle.isNone())
return -1.0;
// calculate minimum distances to graph representation:
if (mLineStyle == lsNone)
{
// no line displayed, only calculate distance to scatter points:
QVector<QCPData> scatterData;
getScatterPlotData(&scatterData);
if (scatterData.size() > 0)
{
double minDistSqr = std::numeric_limits<double>::max();
for (int i=0; i<scatterData.size(); ++i)
{
double currentDistSqr = QVector2D(coordsToPixels(scatterData.at(i).key, scatterData.at(i).value)-pixelPoint).lengthSquared();
if (currentDistSqr < minDistSqr)
minDistSqr = currentDistSqr;
}
return qSqrt(minDistSqr);
} else // no data available in view to calculate distance to
return -1.0;
} else
{
// line displayed, calculate distance to line segments:
QVector<QPointF> lineData;
getPlotData(&lineData, 0); // unlike with getScatterPlotData we get pixel coordinates here
if (lineData.size() > 1) // at least one line segment, compare distance to line segments
{
double minDistSqr = std::numeric_limits<double>::max();
if (mLineStyle == lsImpulse)
{
// impulse plot differs from other line styles in that the lineData points are only pairwise connected:
for (int i=0; i<lineData.size()-1; i+=2) // iterate pairs
{
double currentDistSqr = distSqrToLine(lineData.at(i), lineData.at(i+1), pixelPoint);
if (currentDistSqr < minDistSqr)
minDistSqr = currentDistSqr;
}
} else
{
// all other line plots (line and step) connect points directly:
for (int i=0; i<lineData.size()-1; ++i)
{
double currentDistSqr = distSqrToLine(lineData.at(i), lineData.at(i+1), pixelPoint);
if (currentDistSqr < minDistSqr)
minDistSqr = currentDistSqr;
}
}
return qSqrt(minDistSqr);
} else if (lineData.size() > 0) // only single data point, calculate distance to that point
{
return QVector2D(lineData.at(0)-pixelPoint).length();
} else // no data available in view to calculate distance to
return -1.0;
}
}
/*! \internal
Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in
\a data points are ordered descending, as is the case when plotting with vertical key axis (since
keys are ordered ascending).
Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
*/
int QCPGraph::findIndexBelowY(const QVector<QPointF> *data, double y) const
{
for (int i=data->size()-1; i>=0; --i)
{
if (data->at(i).y() > y)
{
if (i<data->size()-1)
return i+1;
else
return data->size()-1;
}
}
return -1;
}
/* inherits documentation from base class */
QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain) const
{
// just call the specialized version which takes an additional argument whether error bars
// should also be taken into consideration for range calculation. We set this to true here.
return getKeyRange(foundRange, inSignDomain, true);
}
/* inherits documentation from base class */
QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain) const
{
// just call the specialized version which takes an additional argument whether error bars
// should also be taken into consideration for range calculation. We set this to true here.
return getValueRange(foundRange, inSignDomain, true);
}
/*! \overload
Allows to specify whether the error bars should be included in the range calculation.
\see getKeyRange(bool &foundRange, SignDomain inSignDomain)
*/
QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const
{
QCPRange range;
bool haveLower = false;
bool haveUpper = false;
double current, currentErrorMinus, currentErrorPlus;
if (inSignDomain == sdBoth) // range may be anywhere
{
QCPDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
if (!qIsNaN(it.value().value))
{
current = it.value().key;
currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0);
currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0);
if (current-currentErrorMinus < range.lower || !haveLower)
{
range.lower = current-currentErrorMinus;
haveLower = true;
}
if (current+currentErrorPlus > range.upper || !haveUpper)
{
range.upper = current+currentErrorPlus;
haveUpper = true;
}
}
++it;
}
} else if (inSignDomain == sdNegative) // range may only be in the negative sign domain
{
QCPDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
if (!qIsNaN(it.value().value))
{
current = it.value().key;
currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0);
currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0);
if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0)
{
range.lower = current-currentErrorMinus;
haveLower = true;
}
if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0)
{
range.upper = current+currentErrorPlus;
haveUpper = true;
}
if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point.
{
if ((current < range.lower || !haveLower) && current < 0)
{
range.lower = current;
haveLower = true;
}
if ((current > range.upper || !haveUpper) && current < 0)
{
range.upper = current;
haveUpper = true;
}
}
}
++it;
}
} else if (inSignDomain == sdPositive) // range may only be in the positive sign domain
{
QCPDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
if (!qIsNaN(it.value().value))
{
current = it.value().key;
currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0);
currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0);
if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0)
{
range.lower = current-currentErrorMinus;
haveLower = true;
}
if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0)
{
range.upper = current+currentErrorPlus;
haveUpper = true;
}
if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point.
{
if ((current < range.lower || !haveLower) && current > 0)
{
range.lower = current;
haveLower = true;
}
if ((current > range.upper || !haveUpper) && current > 0)
{
range.upper = current;
haveUpper = true;
}
}
}
++it;
}
}
foundRange = haveLower && haveUpper;
return range;
}
/*! \overload
Allows to specify whether the error bars should be included in the range calculation.
\see getValueRange(bool &foundRange, SignDomain inSignDomain)
*/
QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const
{
QCPRange range;
bool haveLower = false;
bool haveUpper = false;
double current, currentErrorMinus, currentErrorPlus;
if (inSignDomain == sdBoth) // range may be anywhere
{
QCPDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
current = it.value().value;
if (!qIsNaN(current))
{
currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0);
currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0);
if (current-currentErrorMinus < range.lower || !haveLower)
{
range.lower = current-currentErrorMinus;
haveLower = true;
}
if (current+currentErrorPlus > range.upper || !haveUpper)
{
range.upper = current+currentErrorPlus;
haveUpper = true;
}
}
++it;
}
} else if (inSignDomain == sdNegative) // range may only be in the negative sign domain
{
QCPDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
current = it.value().value;
if (!qIsNaN(current))
{
currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0);
currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0);
if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0)
{
range.lower = current-currentErrorMinus;
haveLower = true;
}
if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0)
{
range.upper = current+currentErrorPlus;
haveUpper = true;
}
if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point.
{
if ((current < range.lower || !haveLower) && current < 0)
{
range.lower = current;
haveLower = true;
}
if ((current > range.upper || !haveUpper) && current < 0)
{
range.upper = current;
haveUpper = true;
}
}
}
++it;
}
} else if (inSignDomain == sdPositive) // range may only be in the positive sign domain
{
QCPDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
current = it.value().value;
if (!qIsNaN(current))
{
currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0);
currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0);
if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0)
{
range.lower = current-currentErrorMinus;
haveLower = true;
}
if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0)
{
range.upper = current+currentErrorPlus;
haveUpper = true;
}
if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point.
{
if ((current < range.lower || !haveLower) && current > 0)
{
range.lower = current;
haveLower = true;
}
if ((current > range.upper || !haveUpper) && current > 0)
{
range.upper = current;
haveUpper = true;
}
}
}
++it;
}
}
foundRange = haveLower && haveUpper;
return range;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPCurveData
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPCurveData
\brief Holds the data of one single data point for QCPCurve.
The container for storing multiple data points is \ref QCPCurveDataMap.
The stored data is:
\li \a t: the free parameter of the curve at this curve point (cp. the mathematical vector <em>(x(t), y(t))</em>)
\li \a key: coordinate on the key axis of this curve point
\li \a value: coordinate on the value axis of this curve point
\see QCPCurveDataMap
*/
/*!
Constructs a curve data point with t, key and value set to zero.
*/
QCPCurveData::QCPCurveData() :
t(0),
key(0),
value(0)
{
}
/*!
Constructs a curve data point with the specified \a t, \a key and \a value.
*/
QCPCurveData::QCPCurveData(double t, double key, double value) :
t(t),
key(key),
value(value)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPCurve
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPCurve
\brief A plottable representing a parametric curve in a plot.
\image html QCPCurve.png
Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate,
so their visual representation can have \a loops. This is realized by introducing a third
coordinate \a t, which defines the order of the points described by the other two coordinates \a
x and \a y.
To plot data, assign it with the \ref setData or \ref addData functions.
Gaps in the curve can be created by adding data points with NaN as key and value
(<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be
separated.
\section appearance Changing the appearance
The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush).
\section usage Usage
Like all data representing objects in QCustomPlot, the QCPCurve is a plottable (QCPAbstractPlottable). So
the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.)
Usually, you first create an instance and add it to the customPlot:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-1
and then modify the properties of the newly created plottable, e.g.:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-2
*/
/*!
Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
the same orientation. If either of these restrictions is violated, a corresponding message is
printed to the debug output (qDebug), the construction is not aborted, though.
The constructed QCPCurve can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
then takes ownership of the graph.
*/
QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPAbstractPlottable(keyAxis, valueAxis)
{
mData = new QCPCurveDataMap;
mPen.setColor(Qt::blue);
mPen.setStyle(Qt::SolidLine);
mBrush.setColor(Qt::blue);
mBrush.setStyle(Qt::NoBrush);
mSelectedPen = mPen;
mSelectedPen.setWidthF(2.5);
mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen
mSelectedBrush = mBrush;
setScatterStyle(QCPScatterStyle());
setLineStyle(lsLine);
}
QCPCurve::~QCPCurve()
{
delete mData;
}
/*!
Replaces the current data with the provided \a data.
If \a copy is set to true, data points in \a data will only be copied. if false, the plottable
takes ownership of the passed data and replaces the internal data pointer with it. This is
significantly faster than copying for large datasets.
*/
void QCPCurve::setData(QCPCurveDataMap *data, bool copy)
{
if (mData == data)
{
qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast<quintptr>(data);
return;
}
if (copy)
{
*mData = *data;
} else
{
delete mData;
mData = data;
}
}
/*! \overload
Replaces the current data with the provided points in \a t, \a key and \a value tuples. The
provided vectors should have equal length. Else, the number of added points will be the size of
the smallest vector.
*/
void QCPCurve::setData(const QVector<double> &t, const QVector<double> &key, const QVector<double> &value)
{
mData->clear();
int n = t.size();
n = qMin(n, key.size());
n = qMin(n, value.size());
QCPCurveData newData;
for (int i=0; i<n; ++i)
{
newData.t = t[i];
newData.key = key[i];
newData.value = value[i];
mData->insertMulti(newData.t, newData);
}
}
/*! \overload
Replaces the current data with the provided \a key and \a value pairs. The t parameter
of each data point will be set to the integer index of the respective key/value pair.
*/
void QCPCurve::setData(const QVector<double> &key, const QVector<double> &value)
{
mData->clear();
int n = key.size();
n = qMin(n, value.size());
QCPCurveData newData;
for (int i=0; i<n; ++i)
{
newData.t = i; // no t vector given, so we assign t the index of the key/value pair
newData.key = key[i];
newData.value = value[i];
mData->insertMulti(newData.t, newData);
}
}
/*!
Sets the visual appearance of single data points in the plot. If set to \ref
QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate
line style).
\see QCPScatterStyle, setLineStyle
*/
void QCPCurve::setScatterStyle(const QCPScatterStyle &style)
{
mScatterStyle = style;
}
/*!
Sets how the single data points are connected in the plot or how they are represented visually
apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref
setScatterStyle to the desired scatter style.
\see setScatterStyle
*/
void QCPCurve::setLineStyle(QCPCurve::LineStyle style)
{
mLineStyle = style;
}
/*!
Adds the provided data points in \a dataMap to the current data.
\see removeData
*/
void QCPCurve::addData(const QCPCurveDataMap &dataMap)
{
mData->unite(dataMap);
}
/*! \overload
Adds the provided single data point in \a data to the current data.
\see removeData
*/
void QCPCurve::addData(const QCPCurveData &data)
{
mData->insertMulti(data.t, data);
}
/*! \overload
Adds the provided single data point as \a t, \a key and \a value tuple to the current data
\see removeData
*/
void QCPCurve::addData(double t, double key, double value)
{
QCPCurveData newData;
newData.t = t;
newData.key = key;
newData.value = value;
mData->insertMulti(newData.t, newData);
}
/*! \overload
Adds the provided single data point as \a key and \a value pair to the current data The t
parameter of the data point is set to the t of the last data point plus 1. If there is no last
data point, t will be set to 0.
\see removeData
*/
void QCPCurve::addData(double key, double value)
{
QCPCurveData newData;
if (!mData->isEmpty())
newData.t = (mData->constEnd()-1).key()+1;
else
newData.t = 0;
newData.key = key;
newData.value = value;
mData->insertMulti(newData.t, newData);
}
/*! \overload
Adds the provided data points as \a t, \a key and \a value tuples to the current data.
\see removeData
*/
void QCPCurve::addData(const QVector<double> &ts, const QVector<double> &keys, const QVector<double> &values)
{
int n = ts.size();
n = qMin(n, keys.size());
n = qMin(n, values.size());
QCPCurveData newData;
for (int i=0; i<n; ++i)
{
newData.t = ts[i];
newData.key = keys[i];
newData.value = values[i];
mData->insertMulti(newData.t, newData);
}
}
/*!
Removes all data points with curve parameter t smaller than \a t.
\see addData, clearData
*/
void QCPCurve::removeDataBefore(double t)
{
QCPCurveDataMap::iterator it = mData->begin();
while (it != mData->end() && it.key() < t)
it = mData->erase(it);
}
/*!
Removes all data points with curve parameter t greater than \a t.
\see addData, clearData
*/
void QCPCurve::removeDataAfter(double t)
{
if (mData->isEmpty()) return;
QCPCurveDataMap::iterator it = mData->upperBound(t);
while (it != mData->end())
it = mData->erase(it);
}
/*!
Removes all data points with curve parameter t between \a fromt and \a tot. if \a fromt is
greater or equal to \a tot, the function does nothing. To remove a single data point with known
t, use \ref removeData(double t).
\see addData, clearData
*/
void QCPCurve::removeData(double fromt, double tot)
{
if (fromt >= tot || mData->isEmpty()) return;
QCPCurveDataMap::iterator it = mData->upperBound(fromt);
QCPCurveDataMap::iterator itEnd = mData->upperBound(tot);
while (it != itEnd)
it = mData->erase(it);
}
/*! \overload
Removes a single data point at curve parameter \a t. If the position is not known with absolute
precision, consider using \ref removeData(double fromt, double tot) with a small fuzziness
interval around the suspected position, depeding on the precision with which the curve parameter
is known.
\see addData, clearData
*/
void QCPCurve::removeData(double t)
{
mData->remove(t);
}
/*!
Removes all data points.
\see removeData, removeDataAfter, removeDataBefore
*/
void QCPCurve::clearData()
{
mData->clear();
}
/* inherits documentation from base class */
double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if ((onlySelectable && !mSelectable) || mData->isEmpty())
return -1;
if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
return pointDistance(pos);
else
return -1;
}
/* inherits documentation from base class */
void QCPCurve::draw(QCPPainter *painter)
{
if (mData->isEmpty()) return;
// allocate line vector:
QVector<QPointF> *lineData = new QVector<QPointF>;
// fill with curve data:
getCurveData(lineData);
// check data validity if flag set:
#ifdef QCUSTOMPLOT_CHECK_DATA
QCPCurveDataMap::const_iterator it;
for (it = mData->constBegin(); it != mData->constEnd(); ++it)
{
if (QCP::isInvalidData(it.value().t) ||
QCP::isInvalidData(it.value().key, it.value().value))
qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name();
}
#endif
// draw curve fill:
if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0)
{
applyFillAntialiasingHint(painter);
painter->setPen(Qt::NoPen);
painter->setBrush(mainBrush());
painter->drawPolygon(QPolygonF(*lineData));
}
// draw curve line:
if (mLineStyle != lsNone && mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)
{
applyDefaultAntialiasingHint(painter);
painter->setPen(mainPen());
painter->setBrush(Qt::NoBrush);
// if drawing solid line and not in PDF, use much faster line drawing instead of polyline:
if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) &&
painter->pen().style() == Qt::SolidLine &&
!painter->modes().testFlag(QCPPainter::pmVectorized) &&
!painter->modes().testFlag(QCPPainter::pmNoCaching))
{
int i = 0;
bool lastIsNan = false;
const int lineDataSize = lineData->size();
while (i < lineDataSize && (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x()))) // make sure first point is not NaN
++i;
++i; // because drawing works in 1 point retrospect
while (i < lineDataSize)
{
if (!qIsNaN(lineData->at(i).y()) && !qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line
{
if (!lastIsNan)
painter->drawLine(lineData->at(i-1), lineData->at(i));
else
lastIsNan = false;
} else
lastIsNan = true;
++i;
}
} else
{
int segmentStart = 0;
int i = 0;
const int lineDataSize = lineData->size();
while (i < lineDataSize)
{
if (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line
{
painter->drawPolyline(lineData->constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point
segmentStart = i+1;
}
++i;
}
// draw last segment:
painter->drawPolyline(lineData->constData()+segmentStart, lineDataSize-segmentStart);
}
}
// draw scatters:
if (!mScatterStyle.isNone())
drawScatterPlot(painter, lineData);
// free allocated line data:
delete lineData;
}
/* inherits documentation from base class */
void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
{
// draw fill:
if (mBrush.style() != Qt::NoBrush)
{
applyFillAntialiasingHint(painter);
painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
}
// draw line vertically centered:
if (mLineStyle != lsNone)
{
applyDefaultAntialiasingHint(painter);
painter->setPen(mPen);
painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens
}
// draw scatter symbol:
if (!mScatterStyle.isNone())
{
applyScattersAntialiasingHint(painter);
// scale scatter pixmap if it's too large to fit in legend icon rect:
if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
{
QCPScatterStyle scaledStyle(mScatterStyle);
scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
scaledStyle.applyTo(painter, mPen);
scaledStyle.drawShape(painter, QRectF(rect).center());
} else
{
mScatterStyle.applyTo(painter, mPen);
mScatterStyle.drawShape(painter, QRectF(rect).center());
}
}
}
/*! \internal
Draws scatter symbols at every data point passed in \a pointData. scatter symbols are independent of
the line style and are always drawn if scatter shape is not \ref QCPScatterStyle::ssNone.
*/
void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> *pointData) const
{
// draw scatter point symbols:
applyScattersAntialiasingHint(painter);
mScatterStyle.applyTo(painter, mPen);
for (int i=0; i<pointData->size(); ++i)
if (!qIsNaN(pointData->at(i).x()) && !qIsNaN(pointData->at(i).y()))
mScatterStyle.drawShape(painter, pointData->at(i));
}
/*! \internal
called by QCPCurve::draw to generate a point vector (in pixel coordinates) which represents the
line of the curve.
Line segments that aren't visible in the current axis rect are handled in an optimized way. They
are projected onto a rectangle slightly larger than the visible axis rect and simplified
regarding point count. The algorithm makes sure to preserve appearance of lines and fills inside
the visible axis rect by generating new temporary points on the outer rect if necessary.
Methods that are also involved in the algorithm are: \ref getRegion, \ref getOptimizedPoint, \ref
getOptimizedCornerPoints \ref mayTraverse, \ref getTraverse, \ref getTraverseCornerPoints.
*/
void QCPCurve::getCurveData(QVector<QPointF> *lineData) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
// add margins to rect to compensate for stroke width
double strokeMargin = qMax(qreal(1.0), qreal(mainPen().widthF()*0.75)); // stroke radius + 50% safety
if (!mScatterStyle.isNone())
strokeMargin = qMax(strokeMargin, mScatterStyle.size());
double rectLeft = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().lower)-strokeMargin*((keyAxis->orientation()==Qt::Vertical)!=keyAxis->rangeReversed()?-1:1));
double rectRight = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().upper)+strokeMargin*((keyAxis->orientation()==Qt::Vertical)!=keyAxis->rangeReversed()?-1:1));
double rectBottom = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().lower)+strokeMargin*((valueAxis->orientation()==Qt::Horizontal)!=valueAxis->rangeReversed()?-1:1));
double rectTop = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().upper)-strokeMargin*((valueAxis->orientation()==Qt::Horizontal)!=valueAxis->rangeReversed()?-1:1));
int currentRegion;
QCPCurveDataMap::const_iterator it = mData->constBegin();
QCPCurveDataMap::const_iterator prevIt = mData->constEnd()-1;
int prevRegion = getRegion(prevIt.value().key, prevIt.value().value, rectLeft, rectTop, rectRight, rectBottom);
QVector<QPointF> trailingPoints; // points that must be applied after all other points (are generated only when handling first point to get virtual segment between last and first point right)
while (it != mData->constEnd())
{
currentRegion = getRegion(it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom);
if (currentRegion != prevRegion) // changed region, possibly need to add some optimized edge points or original points if entering R
{
if (currentRegion != 5) // segment doesn't end in R, so it's a candidate for removal
{
QPointF crossA, crossB;
if (prevRegion == 5) // we're coming from R, so add this point optimized
{
lineData->append(getOptimizedPoint(currentRegion, it.value().key, it.value().value, prevIt.value().key, prevIt.value().value, rectLeft, rectTop, rectRight, rectBottom));
// in the situations 5->1/7/9/3 the segment may leave R and directly cross through two outer regions. In these cases we need to add an additional corner point
*lineData << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom);
} else if (mayTraverse(prevRegion, currentRegion) &&
getTraverse(prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom, crossA, crossB))
{
// add the two cross points optimized if segment crosses R and if segment isn't virtual zeroth segment between last and first curve point:
QVector<QPointF> beforeTraverseCornerPoints, afterTraverseCornerPoints;
getTraverseCornerPoints(prevRegion, currentRegion, rectLeft, rectTop, rectRight, rectBottom, beforeTraverseCornerPoints, afterTraverseCornerPoints);
if (it != mData->constBegin())
{
*lineData << beforeTraverseCornerPoints;
lineData->append(crossA);
lineData->append(crossB);
*lineData << afterTraverseCornerPoints;
} else
{
lineData->append(crossB);
*lineData << afterTraverseCornerPoints;
trailingPoints << beforeTraverseCornerPoints << crossA ;
}
} else // doesn't cross R, line is just moving around in outside regions, so only need to add optimized point(s) at the boundary corner(s)
{
*lineData << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom);
}
} else // segment does end in R, so we add previous point optimized and this point at original position
{
if (it == mData->constBegin()) // it is first point in curve and prevIt is last one. So save optimized point for adding it to the lineData in the end
trailingPoints << getOptimizedPoint(prevRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom);
else
lineData->append(getOptimizedPoint(prevRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom));
lineData->append(coordsToPixels(it.value().key, it.value().value));
}
} else // region didn't change
{
if (currentRegion == 5) // still in R, keep adding original points
{
lineData->append(coordsToPixels(it.value().key, it.value().value));
} else // still outside R, no need to add anything
{
// see how this is not doing anything? That's the main optimization...
}
}
prevIt = it;
prevRegion = currentRegion;
++it;
}
*lineData << trailingPoints;
}
/*! \internal
This function is part of the curve optimization algorithm of \ref getCurveData.
It returns the region of the given point (\a x, \a y) with respect to a rectangle defined by \a
rectLeft, \a rectTop, \a rectRight, and \a rectBottom.
The regions are enumerated from top to bottom and left to right:
<table style="width:10em; text-align:center">
<tr><td>1</td><td>4</td><td>7</td></tr>
<tr><td>2</td><td style="border:1px solid black">5</td><td>8</td></tr>
<tr><td>3</td><td>6</td><td>9</td></tr>
</table>
With the rectangle being region 5, and the outer regions extending infinitely outwards. In the
curve optimization algorithm, region 5 is considered to be the visible portion of the plot.
*/
int QCPCurve::getRegion(double x, double y, double rectLeft, double rectTop, double rectRight, double rectBottom) const
{
if (x < rectLeft) // region 123
{
if (y > rectTop)
return 1;
else if (y < rectBottom)
return 3;
else
return 2;
} else if (x > rectRight) // region 789
{
if (y > rectTop)
return 7;
else if (y < rectBottom)
return 9;
else
return 8;
} else // region 456
{
if (y > rectTop)
return 4;
else if (y < rectBottom)
return 6;
else
return 5;
}
}
/*! \internal
This function is part of the curve optimization algorithm of \ref getCurveData.
This method is used in case the current segment passes from inside the visible rect (region 5,
see \ref getRegion) to any of the outer regions (\a otherRegion). The current segment is given by
the line connecting (\a key, \a value) with (\a otherKey, \a otherValue).
It returns the intersection point of the segment with the border of region 5.
For this function it doesn't matter whether (\a key, \a value) is the point inside region 5 or
whether it's (\a otherKey, \a otherValue), i.e. whether the segment is coming from region 5 or
leaving it. It is important though that \a otherRegion correctly identifies the other region not
equal to 5.
*/
QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const
{
double intersectKey = rectLeft; // initial value is just fail-safe
double intersectValue = rectTop; // initial value is just fail-safe
switch (otherRegion)
{
case 1: // top and left edge
{
intersectValue = rectTop;
intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue);
if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other:
{
intersectKey = rectLeft;
intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey);
}
break;
}
case 2: // left edge
{
intersectKey = rectLeft;
intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey);
break;
}
case 3: // bottom and left edge
{
intersectValue = rectBottom;
intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue);
if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other:
{
intersectKey = rectLeft;
intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey);
}
break;
}
case 4: // top edge
{
intersectValue = rectTop;
intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue);
break;
}
case 5:
{
break; // case 5 shouldn't happen for this function but we add it anyway to prevent potential discontinuity in branch table
}
case 6: // bottom edge
{
intersectValue = rectBottom;
intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue);
break;
}
case 7: // top and right edge
{
intersectValue = rectTop;
intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue);
if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other:
{
intersectKey = rectRight;
intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey);
}
break;
}
case 8: // right edge
{
intersectKey = rectRight;
intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey);
break;
}
case 9: // bottom and right edge
{
intersectValue = rectBottom;
intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue);
if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other:
{
intersectKey = rectRight;
intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey);
}
break;
}
}
return coordsToPixels(intersectKey, intersectValue);
}
/*! \internal
This function is part of the curve optimization algorithm of \ref getCurveData.
In situations where a single segment skips over multiple regions it might become necessary to add
extra points at the corners of region 5 (see \ref getRegion) such that the optimized segment
doesn't unintentionally cut through the visible area of the axis rect and create plot artifacts.
This method provides these points that must be added, assuming the original segment doesn't
start, end, or traverse region 5. (Corner points where region 5 is traversed are calculated by
\ref getTraverseCornerPoints.)
For example, consider a segment which directly goes from region 4 to 2 but originally is far out
to the top left such that it doesn't cross region 5. Naively optimizing these points by
projecting them on the top and left borders of region 5 will create a segment that surely crosses
5, creating a visual artifact in the plot. This method prevents this by providing extra points at
the top left corner, making the optimized curve correctly pass from region 4 to 1 to 2 without
traversing 5.
*/
QVector<QPointF> QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const
{
QVector<QPointF> result;
switch (prevRegion)
{
case 1:
{
switch (currentRegion)
{
case 2: { result << coordsToPixels(rectLeft, rectTop); break; }
case 4: { result << coordsToPixels(rectLeft, rectTop); break; }
case 3: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom); break; }
case 7: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop); break; }
case 6: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; }
case 8: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; }
case 9: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points
if ((value-prevValue)/(key-prevKey)*(rectLeft-key)+value < rectBottom) // segment passes below R
{ result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); }
else
{ result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); }
break;
}
}
break;
}
case 2:
{
switch (currentRegion)
{
case 1: { result << coordsToPixels(rectLeft, rectTop); break; }
case 3: { result << coordsToPixels(rectLeft, rectBottom); break; }
case 4: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; }
case 6: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; }
case 7: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); break; }
case 9: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); break; }
}
break;
}
case 3:
{
switch (currentRegion)
{
case 2: { result << coordsToPixels(rectLeft, rectBottom); break; }
case 6: { result << coordsToPixels(rectLeft, rectBottom); break; }
case 1: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop); break; }
case 9: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectRight, rectBottom); break; }
case 4: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; }
case 8: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; }
case 7: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points
if ((value-prevValue)/(key-prevKey)*(rectRight-key)+value < rectBottom) // segment passes below R
{ result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); }
else
{ result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); }
break;
}
}
break;
}
case 4:
{
switch (currentRegion)
{
case 1: { result << coordsToPixels(rectLeft, rectTop); break; }
case 7: { result << coordsToPixels(rectRight, rectTop); break; }
case 2: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; }
case 8: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; }
case 3: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); break; }
case 9: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); break; }
}
break;
}
case 5:
{
switch (currentRegion)
{
case 1: { result << coordsToPixels(rectLeft, rectTop); break; }
case 7: { result << coordsToPixels(rectRight, rectTop); break; }
case 9: { result << coordsToPixels(rectRight, rectBottom); break; }
case 3: { result << coordsToPixels(rectLeft, rectBottom); break; }
}
break;
}
case 6:
{
switch (currentRegion)
{
case 3: { result << coordsToPixels(rectLeft, rectBottom); break; }
case 9: { result << coordsToPixels(rectRight, rectBottom); break; }
case 2: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; }
case 8: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; }
case 1: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); break; }
case 7: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); break; }
}
break;
}
case 7:
{
switch (currentRegion)
{
case 4: { result << coordsToPixels(rectRight, rectTop); break; }
case 8: { result << coordsToPixels(rectRight, rectTop); break; }
case 1: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop); break; }
case 9: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectRight, rectBottom); break; }
case 2: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; }
case 6: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; }
case 3: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points
if ((value-prevValue)/(key-prevKey)*(rectRight-key)+value < rectBottom) // segment passes below R
{ result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); }
else
{ result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); }
break;
}
}
break;
}
case 8:
{
switch (currentRegion)
{
case 7: { result << coordsToPixels(rectRight, rectTop); break; }
case 9: { result << coordsToPixels(rectRight, rectBottom); break; }
case 4: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; }
case 6: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; }
case 1: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); break; }
case 3: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); break; }
}
break;
}
case 9:
{
switch (currentRegion)
{
case 6: { result << coordsToPixels(rectRight, rectBottom); break; }
case 8: { result << coordsToPixels(rectRight, rectBottom); break; }
case 3: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectLeft, rectBottom); break; }
case 7: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop); break; }
case 2: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; }
case 4: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; }
case 1: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points
if ((value-prevValue)/(key-prevKey)*(rectLeft-key)+value < rectBottom) // segment passes below R
{ result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); }
else
{ result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); }
break;
}
}
break;
}
}
return result;
}
/*! \internal
This function is part of the curve optimization algorithm of \ref getCurveData.
This method returns whether a segment going from \a prevRegion to \a currentRegion (see \ref
getRegion) may traverse the visible region 5. This function assumes that neither \a prevRegion
nor \a currentRegion is 5 itself.
If this method returns false, the segment for sure doesn't pass region 5. If it returns true, the
segment may or may not pass region 5 and a more fine-grained calculation must be used (\ref
getTraverse).
*/
bool QCPCurve::mayTraverse(int prevRegion, int currentRegion) const
{
switch (prevRegion)
{
case 1:
{
switch (currentRegion)
{
case 4:
case 7:
case 2:
case 3: return false;
default: return true;
}
}
case 2:
{
switch (currentRegion)
{
case 1:
case 3: return false;
default: return true;
}
}
case 3:
{
switch (currentRegion)
{
case 1:
case 2:
case 6:
case 9: return false;
default: return true;
}
}
case 4:
{
switch (currentRegion)
{
case 1:
case 7: return false;
default: return true;
}
}
case 5: return false; // should never occur
case 6:
{
switch (currentRegion)
{
case 3:
case 9: return false;
default: return true;
}
}
case 7:
{
switch (currentRegion)
{
case 1:
case 4:
case 8:
case 9: return false;
default: return true;
}
}
case 8:
{
switch (currentRegion)
{
case 7:
case 9: return false;
default: return true;
}
}
case 9:
{
switch (currentRegion)
{
case 3:
case 6:
case 8:
case 7: return false;
default: return true;
}
}
default: return true;
}
}
/*! \internal
This function is part of the curve optimization algorithm of \ref getCurveData.
This method assumes that the \ref mayTraverse test has returned true, so there is a chance the
segment defined by (\a prevKey, \a prevValue) and (\a key, \a value) goes through the visible
region 5.
The return value of this method indicates whether the segment actually traverses region 5 or not.
If the segment traverses 5, the output parameters \a crossA and \a crossB indicate the entry and
exit points of region 5. They will become the optimized points for that segment.
*/
bool QCPCurve::getTraverse(double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom, QPointF &crossA, QPointF &crossB) const
{
QList<QPointF> intersections; // x of QPointF corresponds to key and y to value
if (qFuzzyIsNull(key-prevKey)) // line is parallel to value axis
{
// due to region filter in mayTraverseR(), if line is parallel to value or key axis, R is traversed here
intersections.append(QPointF(key, rectBottom)); // direction will be taken care of at end of method
intersections.append(QPointF(key, rectTop));
} else if (qFuzzyIsNull(value-prevValue)) // line is parallel to key axis
{
// due to region filter in mayTraverseR(), if line is parallel to value or key axis, R is traversed here
intersections.append(QPointF(rectLeft, value)); // direction will be taken care of at end of method
intersections.append(QPointF(rectRight, value));
} else // line is skewed
{
double gamma;
double keyPerValue = (key-prevKey)/(value-prevValue);
// check top of rect:
gamma = prevKey + (rectTop-prevValue)*keyPerValue;
if (gamma >= rectLeft && gamma <= rectRight)
intersections.append(QPointF(gamma, rectTop));
// check bottom of rect:
gamma = prevKey + (rectBottom-prevValue)*keyPerValue;
if (gamma >= rectLeft && gamma <= rectRight)
intersections.append(QPointF(gamma, rectBottom));
double valuePerKey = 1.0/keyPerValue;
// check left of rect:
gamma = prevValue + (rectLeft-prevKey)*valuePerKey;
if (gamma >= rectBottom && gamma <= rectTop)
intersections.append(QPointF(rectLeft, gamma));
// check right of rect:
gamma = prevValue + (rectRight-prevKey)*valuePerKey;
if (gamma >= rectBottom && gamma <= rectTop)
intersections.append(QPointF(rectRight, gamma));
}
// handle cases where found points isn't exactly 2:
if (intersections.size() > 2)
{
// line probably goes through corner of rect, and we got duplicate points there. single out the point pair with greatest distance in between:
double distSqrMax = 0;
QPointF pv1, pv2;
for (int i=0; i<intersections.size()-1; ++i)
{
for (int k=i+1; k<intersections.size(); ++k)
{
QPointF distPoint = intersections.at(i)-intersections.at(k);
double distSqr = distPoint.x()*distPoint.x()+distPoint.y()+distPoint.y();
if (distSqr > distSqrMax)
{
pv1 = intersections.at(i);
pv2 = intersections.at(k);
distSqrMax = distSqr;
}
}
}
intersections = QList<QPointF>() << pv1 << pv2;
} else if (intersections.size() != 2)
{
// one or even zero points found (shouldn't happen unless line perfectly tangent to corner), no need to draw segment
return false;
}
// possibly re-sort points so optimized point segment has same direction as original segment:
if ((key-prevKey)*(intersections.at(1).x()-intersections.at(0).x()) + (value-prevValue)*(intersections.at(1).y()-intersections.at(0).y()) < 0) // scalar product of both segments < 0 -> opposite direction
intersections.move(0, 1);
crossA = coordsToPixels(intersections.at(0).x(), intersections.at(0).y());
crossB = coordsToPixels(intersections.at(1).x(), intersections.at(1).y());
return true;
}
/*! \internal
This function is part of the curve optimization algorithm of \ref getCurveData.
This method assumes that the \ref getTraverse test has returned true, so the segment definitely
traverses the visible region 5 when going from \a prevRegion to \a currentRegion.
In certain situations it is not sufficient to merely generate the entry and exit points of the
segment into/out of region 5, as \ref getTraverse provides. It may happen that a single segment, in
addition to traversing region 5, skips another region outside of region 5, which makes it
necessary to add an optimized corner point there (very similar to the job \ref
getOptimizedCornerPoints does for segments that are completely in outside regions and don't
traverse 5).
As an example, consider a segment going from region 1 to region 6, traversing the lower left
corner of region 5. In this configuration, the segment additionally crosses the border between
region 1 and 2 before entering region 5. This makes it necessary to add an additional point in
the top left corner, before adding the optimized traverse points. So in this case, the output
parameter \a beforeTraverse will contain the top left corner point, and \a afterTraverse will be
empty.
In some cases, such as when going from region 1 to 9, it may even be necessary to add additional
corner points before and after the traverse. Then both \a beforeTraverse and \a afterTraverse
return the respective corner points.
*/
void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double rectLeft, double rectTop, double rectRight, double rectBottom, QVector<QPointF> &beforeTraverse, QVector<QPointF> &afterTraverse) const
{
switch (prevRegion)
{
case 1:
{
switch (currentRegion)
{
case 6: { beforeTraverse << coordsToPixels(rectLeft, rectTop); break; }
case 9: { beforeTraverse << coordsToPixels(rectLeft, rectTop); afterTraverse << coordsToPixels(rectRight, rectBottom); break; }
case 8: { beforeTraverse << coordsToPixels(rectLeft, rectTop); break; }
}
break;
}
case 2:
{
switch (currentRegion)
{
case 7: { afterTraverse << coordsToPixels(rectRight, rectTop); break; }
case 9: { afterTraverse << coordsToPixels(rectRight, rectBottom); break; }
}
break;
}
case 3:
{
switch (currentRegion)
{
case 4: { beforeTraverse << coordsToPixels(rectLeft, rectBottom); break; }
case 7: { beforeTraverse << coordsToPixels(rectLeft, rectBottom); afterTraverse << coordsToPixels(rectRight, rectTop); break; }
case 8: { beforeTraverse << coordsToPixels(rectLeft, rectBottom); break; }
}
break;
}
case 4:
{
switch (currentRegion)
{
case 3: { afterTraverse << coordsToPixels(rectLeft, rectBottom); break; }
case 9: { afterTraverse << coordsToPixels(rectRight, rectBottom); break; }
}
break;
}
case 5: { break; } // shouldn't happen because this method only handles full traverses
case 6:
{
switch (currentRegion)
{
case 1: { afterTraverse << coordsToPixels(rectLeft, rectTop); break; }
case 7: { afterTraverse << coordsToPixels(rectRight, rectTop); break; }
}
break;
}
case 7:
{
switch (currentRegion)
{
case 2: { beforeTraverse << coordsToPixels(rectRight, rectTop); break; }
case 3: { beforeTraverse << coordsToPixels(rectRight, rectTop); afterTraverse << coordsToPixels(rectLeft, rectBottom); break; }
case 6: { beforeTraverse << coordsToPixels(rectRight, rectTop); break; }
}
break;
}
case 8:
{
switch (currentRegion)
{
case 1: { afterTraverse << coordsToPixels(rectLeft, rectTop); break; }
case 3: { afterTraverse << coordsToPixels(rectLeft, rectBottom); break; }
}
break;
}
case 9:
{
switch (currentRegion)
{
case 2: { beforeTraverse << coordsToPixels(rectRight, rectBottom); break; }
case 1: { beforeTraverse << coordsToPixels(rectRight, rectBottom); afterTraverse << coordsToPixels(rectLeft, rectTop); break; }
case 4: { beforeTraverse << coordsToPixels(rectRight, rectBottom); break; }
}
break;
}
}
}
/*! \internal
Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a
pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in
\ref selectTest.
*/
double QCPCurve::pointDistance(const QPointF &pixelPoint) const
{
if (mData->isEmpty())
{
qDebug() << Q_FUNC_INFO << "requested point distance on curve" << mName << "without data";
return 500;
}
if (mData->size() == 1)
{
QPointF dataPoint = coordsToPixels(mData->constBegin().key(), mData->constBegin().value().value);
return QVector2D(dataPoint-pixelPoint).length();
}
// calculate minimum distance to line segments:
QVector<QPointF> *lineData = new QVector<QPointF>;
getCurveData(lineData);
double minDistSqr = std::numeric_limits<double>::max();
for (int i=0; i<lineData->size()-1; ++i)
{
double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint);
if (currentDistSqr < minDistSqr)
minDistSqr = currentDistSqr;
}
delete lineData;
return qSqrt(minDistSqr);
}
/* inherits documentation from base class */
QCPRange QCPCurve::getKeyRange(bool &foundRange, SignDomain inSignDomain) const
{
QCPRange range;
bool haveLower = false;
bool haveUpper = false;
double current;
QCPCurveDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
current = it.value().key;
if (!qIsNaN(current) && !qIsNaN(it.value().value))
{
if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0))
{
if (current < range.lower || !haveLower)
{
range.lower = current;
haveLower = true;
}
if (current > range.upper || !haveUpper)
{
range.upper = current;
haveUpper = true;
}
}
}
++it;
}
foundRange = haveLower && haveUpper;
return range;
}
/* inherits documentation from base class */
QCPRange QCPCurve::getValueRange(bool &foundRange, SignDomain inSignDomain) const
{
QCPRange range;
bool haveLower = false;
bool haveUpper = false;
double current;
QCPCurveDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
current = it.value().value;
if (!qIsNaN(current) && !qIsNaN(it.value().key))
{
if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0))
{
if (current < range.lower || !haveLower)
{
range.lower = current;
haveLower = true;
}
if (current > range.upper || !haveUpper)
{
range.upper = current;
haveUpper = true;
}
}
}
++it;
}
foundRange = haveLower && haveUpper;
return range;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPBarsGroup
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPBarsGroup
\brief Groups multiple QCPBars together so they appear side by side
\image html QCPBarsGroup.png
When showing multiple QCPBars in one plot which have bars at identical keys, it may be desirable
to have them appearing next to each other at each key. This is what adding the respective QCPBars
plottables to a QCPBarsGroup achieves. (An alternative approach is to stack them on top of each
other, see \ref QCPBars::moveAbove.)
\section qcpbarsgroup-usage Usage
To add a QCPBars plottable to the group, create a new group and then add the respective bars
intances:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpbarsgroup-creation
Alternatively to appending to the group like shown above, you can also set the group on the
QCPBars plottable via \ref QCPBars::setBarsGroup.
The spacing between the bars can be configured via \ref setSpacingType and \ref setSpacing. The
bars in this group appear in the plot in the order they were appended. To insert a bars plottable
at a certain index position, or to reposition a bars plottable which is already in the group, use
\ref insert.
To remove specific bars from the group, use either \ref remove or call \ref
QCPBars::setBarsGroup "QCPBars::setBarsGroup(0)" on the respective bars plottable.
To clear the entire group, call \ref clear, or simply delete the group.
\section qcpbarsgroup-example Example
The image above is generated with the following code:
\snippet documentation/doc-image-generator/mainwindow.cpp qcpbarsgroup-example
*/
/* start of documentation of inline functions */
/*! \fn QList<QCPBars*> QCPBarsGroup::bars() const
Returns all bars currently in this group.
\see bars(int index)
*/
/*! \fn int QCPBarsGroup::size() const
Returns the number of QCPBars plottables that are part of this group.
*/
/*! \fn bool QCPBarsGroup::isEmpty() const
Returns whether this bars group is empty.
\see size
*/
/*! \fn bool QCPBarsGroup::contains(QCPBars *bars)
Returns whether the specified \a bars plottable is part of this group.
*/
/* end of documentation of inline functions */
/*!
Constructs a new bars group for the specified QCustomPlot instance.
*/
QCPBarsGroup::QCPBarsGroup(QCustomPlot *parentPlot) :
QObject(parentPlot),
mParentPlot(parentPlot),
mSpacingType(stAbsolute),
mSpacing(4)
{
}
QCPBarsGroup::~QCPBarsGroup()
{
clear();
}
/*!
Sets how the spacing between adjacent bars is interpreted. See \ref SpacingType.
The actual spacing can then be specified with \ref setSpacing.
\see setSpacing
*/
void QCPBarsGroup::setSpacingType(SpacingType spacingType)
{
mSpacingType = spacingType;
}
/*!
Sets the spacing between adjacent bars. What the number passed as \a spacing actually means, is
defined by the current \ref SpacingType, which can be set with \ref setSpacingType.
\see setSpacingType
*/
void QCPBarsGroup::setSpacing(double spacing)
{
mSpacing = spacing;
}
/*!
Returns the QCPBars instance with the specified \a index in this group. If no such QCPBars
exists, returns 0.
\see bars(), size
*/
QCPBars *QCPBarsGroup::bars(int index) const
{
if (index >= 0 && index < mBars.size())
{
return mBars.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return 0;
}
}
/*!
Removes all QCPBars plottables from this group.
\see isEmpty
*/
void QCPBarsGroup::clear()
{
foreach (QCPBars *bars, mBars) // since foreach takes a copy, removing bars in the loop is okay
bars->setBarsGroup(0); // removes itself via removeBars
}
/*!
Adds the specified \a bars plottable to this group. Alternatively, you can also use \ref
QCPBars::setBarsGroup on the \a bars instance.
\see insert, remove
*/
void QCPBarsGroup::append(QCPBars *bars)
{
if (!bars)
{
qDebug() << Q_FUNC_INFO << "bars is 0";
return;
}
if (!mBars.contains(bars))
bars->setBarsGroup(this);
else
qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:" << reinterpret_cast<quintptr>(bars);
}
/*!
Inserts the specified \a bars plottable into this group at the specified index position \a i.
This gives you full control over the ordering of the bars.
\a bars may already be part of this group. In that case, \a bars is just moved to the new index
position.
\see append, remove
*/
void QCPBarsGroup::insert(int i, QCPBars *bars)
{
if (!bars)
{
qDebug() << Q_FUNC_INFO << "bars is 0";
return;
}
// first append to bars list normally:
if (!mBars.contains(bars))
bars->setBarsGroup(this);
// then move to according position:
mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size()-1));
}
/*!
Removes the specified \a bars plottable from this group.
\see contains, clear
*/
void QCPBarsGroup::remove(QCPBars *bars)
{
if (!bars)
{
qDebug() << Q_FUNC_INFO << "bars is 0";
return;
}
if (mBars.contains(bars))
bars->setBarsGroup(0);
else
qDebug() << Q_FUNC_INFO << "bars plottable is not in this bars group:" << reinterpret_cast<quintptr>(bars);
}
/*! \internal
Adds the specified \a bars to the internal mBars list of bars. This method does not change the
barsGroup property on \a bars.
\see unregisterBars
*/
void QCPBarsGroup::registerBars(QCPBars *bars)
{
if (!mBars.contains(bars))
mBars.append(bars);
}
/*! \internal
Removes the specified \a bars from the internal mBars list of bars. This method does not change
the barsGroup property on \a bars.
\see registerBars
*/
void QCPBarsGroup::unregisterBars(QCPBars *bars)
{
mBars.removeOne(bars);
}
/*! \internal
Returns the pixel offset in the key dimension the specified \a bars plottable should have at the
given key coordinate \a keyCoord. The offset is relative to the pixel position of the key
coordinate \a keyCoord.
*/
double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord)
{
// find list of all base bars in case some mBars are stacked:
QList<const QCPBars*> baseBars;
foreach (const QCPBars *b, mBars)
{
while (b->barBelow())
b = b->barBelow();
if (!baseBars.contains(b))
baseBars.append(b);
}
// find base bar this "bars" is stacked on:
const QCPBars *thisBase = bars;
while (thisBase->barBelow())
thisBase = thisBase->barBelow();
// determine key pixel offset of this base bars considering all other base bars in this barsgroup:
double result = 0;
int index = baseBars.indexOf(thisBase);
if (index >= 0)
{
int startIndex;
double lowerPixelWidth, upperPixelWidth;
if (baseBars.size() % 2 == 1 && index == (baseBars.size()-1)/2) // is center bar (int division on purpose)
{
return result;
} else if (index < (baseBars.size()-1)/2.0) // bar is to the left of center
{
if (baseBars.size() % 2 == 0) // even number of bars
{
startIndex = baseBars.size()/2-1;
result -= getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing
} else // uneven number of bars
{
startIndex = (baseBars.size()-1)/2-1;
baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
result -= qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar
result -= getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing
}
for (int i=startIndex; i>index; --i) // add widths and spacings of bars in between center and our bars
{
baseBars.at(i)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
result -= qAbs(upperPixelWidth-lowerPixelWidth);
result -= getPixelSpacing(baseBars.at(i), keyCoord);
}
// finally half of our bars width:
baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
result -= qAbs(upperPixelWidth-lowerPixelWidth)*0.5;
} else // bar is to the right of center
{
if (baseBars.size() % 2 == 0) // even number of bars
{
startIndex = baseBars.size()/2;
result += getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing
} else // uneven number of bars
{
startIndex = (baseBars.size()-1)/2+1;
baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar
result += getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing
}
for (int i=startIndex; i<index; ++i) // add widths and spacings of bars in between center and our bars
{
baseBars.at(i)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
result += qAbs(upperPixelWidth-lowerPixelWidth);
result += getPixelSpacing(baseBars.at(i), keyCoord);
}
// finally half of our bars width:
baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5;
}
}
return result;
}
/*! \internal
Returns the spacing in pixels which is between this \a bars and the following one, both at the
key coordinate \a keyCoord.
\note Typically the returned value doesn't depend on \a bars or \a keyCoord. \a bars is only
needed to get acces to the key axis transformation and axis rect for the modes \ref
stAxisRectRatio and \ref stPlotCoords. The \a keyCoord is only relevant for spacings given in
\ref stPlotCoords on a logarithmic axis.
*/
double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord)
{
switch (mSpacingType)
{
case stAbsolute:
{
return mSpacing;
}
case stAxisRectRatio:
{
if (bars->keyAxis()->orientation() == Qt::Horizontal)
return bars->keyAxis()->axisRect()->width()*mSpacing;
else
return bars->keyAxis()->axisRect()->height()*mSpacing;
}
case stPlotCoords:
{
double keyPixel = bars->keyAxis()->coordToPixel(keyCoord);
return bars->keyAxis()->coordToPixel(keyCoord+mSpacing)-keyPixel;
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPBarData
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPBarData
\brief Holds the data of one single data point (one bar) for QCPBars.
The container for storing multiple data points is \ref QCPBarDataMap.
The stored data is:
\li \a key: coordinate on the key axis of this bar
\li \a value: height coordinate on the value axis of this bar
\see QCPBarDataaMap
*/
/*!
Constructs a bar data point with key and value set to zero.
*/
QCPBarData::QCPBarData() :
key(0),
value(0)
{
}
/*!
Constructs a bar data point with the specified \a key and \a value.
*/
QCPBarData::QCPBarData(double key, double value) :
key(key),
value(value)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPBars
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPBars
\brief A plottable representing a bar chart in a plot.
\image html QCPBars.png
To plot data, assign it with the \ref setData or \ref addData functions.
\section appearance Changing the appearance
The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush).
The width of the individual bars can be controlled with \ref setWidthType and \ref setWidth.
Bar charts are stackable. This means, two QCPBars plottables can be placed on top of each other
(see \ref QCPBars::moveAbove). So when two bars are at the same key position, they will appear
stacked.
If you would like to group multiple QCPBars plottables together so they appear side by side as
shown below, use QCPBarsGroup.
\image html QCPBarsGroup.png
\section usage Usage
Like all data representing objects in QCustomPlot, the QCPBars is a plottable
(QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
(QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.)
Usually, you first create an instance:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-1
add it to the customPlot with QCustomPlot::addPlottable:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-2
and then modify the properties of the newly created plottable, e.g.:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-3
*/
/* start of documentation of inline functions */
/*! \fn QCPBars *QCPBars::barBelow() const
Returns the bars plottable that is directly below this bars plottable.
If there is no such plottable, returns 0.
\see barAbove, moveBelow, moveAbove
*/
/*! \fn QCPBars *QCPBars::barAbove() const
Returns the bars plottable that is directly above this bars plottable.
If there is no such plottable, returns 0.
\see barBelow, moveBelow, moveAbove
*/
/* end of documentation of inline functions */
/*!
Constructs a bar chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
the same orientation. If either of these restrictions is violated, a corresponding message is
printed to the debug output (qDebug), the construction is not aborted, though.
The constructed QCPBars can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
then takes ownership of the bar chart.
*/
QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPAbstractPlottable(keyAxis, valueAxis),
mData(new QCPBarDataMap),
mWidth(0.75),
mWidthType(wtPlotCoords),
mBarsGroup(0),
mBaseValue(0)
{
// modify inherited properties from abstract plottable:
mPen.setColor(Qt::blue);
mPen.setStyle(Qt::SolidLine);
mBrush.setColor(QColor(40, 50, 255, 30));
mBrush.setStyle(Qt::SolidPattern);
mSelectedPen = mPen;
mSelectedPen.setWidthF(2.5);
mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen
mSelectedBrush = mBrush;
}
QCPBars::~QCPBars()
{
setBarsGroup(0);
if (mBarBelow || mBarAbove)
connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking
delete mData;
}
/*!
Sets the width of the bars.
How the number passed as \a width is interpreted (e.g. screen pixels, plot coordinates,...),
depends on the currently set width type, see \ref setWidthType and \ref WidthType.
*/
void QCPBars::setWidth(double width)
{
mWidth = width;
}
/*!
Sets how the width of the bars is defined. See the documentation of \ref WidthType for an
explanation of the possible values for \a widthType.
The default value is \ref wtPlotCoords.
\see setWidth
*/
void QCPBars::setWidthType(QCPBars::WidthType widthType)
{
mWidthType = widthType;
}
/*!
Sets to which QCPBarsGroup this QCPBars instance belongs to. Alternatively, you can also use \ref
QCPBarsGroup::append.
To remove this QCPBars from any group, set \a barsGroup to 0.
*/
void QCPBars::setBarsGroup(QCPBarsGroup *barsGroup)
{
// deregister at old group:
if (mBarsGroup)
mBarsGroup->unregisterBars(this);
mBarsGroup = barsGroup;
// register at new group:
if (mBarsGroup)
mBarsGroup->registerBars(this);
}
/*!
Sets the base value of this bars plottable.
The base value defines where on the value coordinate the bars start. How far the bars extend from
the base value is given by their individual value data. For example, if the base value is set to
1, a bar with data value 2 will have its lowest point at value coordinate 1 and highest point at
3.
For stacked bars, only the base value of the bottom-most QCPBars has meaning.
The default base value is 0.
*/
void QCPBars::setBaseValue(double baseValue)
{
mBaseValue = baseValue;
}
/*!
Replaces the current data with the provided \a data.
If \a copy is set to true, data points in \a data will only be copied. if false, the plottable
takes ownership of the passed data and replaces the internal data pointer with it. This is
significantly faster than copying for large datasets.
*/
void QCPBars::setData(QCPBarDataMap *data, bool copy)
{
if (mData == data)
{
qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast<quintptr>(data);
return;
}
if (copy)
{
*mData = *data;
} else
{
delete mData;
mData = data;
}
}
/*! \overload
Replaces the current data with the provided points in \a key and \a value tuples. The
provided vectors should have equal length. Else, the number of added points will be the size of
the smallest vector.
*/
void QCPBars::setData(const QVector<double> &key, const QVector<double> &value)
{
mData->clear();
int n = key.size();
n = qMin(n, value.size());
QCPBarData newData;
for (int i=0; i<n; ++i)
{
newData.key = key[i];
newData.value = value[i];
mData->insertMulti(newData.key, newData);
}
}
/*!
Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear
below the bars of \a bars. The move target \a bars must use the same key and value axis as this
plottable.
Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
has a bars object below itself, this bars object is inserted between the two. If this bars object
is already between two other bars, the two other bars will be stacked on top of each other after
the operation.
To remove this bars plottable from any stacking, set \a bars to 0.
\see moveBelow, barAbove, barBelow
*/
void QCPBars::moveBelow(QCPBars *bars)
{
if (bars == this) return;
if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
{
qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
return;
}
// remove from stacking:
connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
// if new bar given, insert this bar below it:
if (bars)
{
if (bars->mBarBelow)
connectBars(bars->mBarBelow.data(), this);
connectBars(this, bars);
}
}
/*!
Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear
above the bars of \a bars. The move target \a bars must use the same key and value axis as this
plottable.
Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
has a bars object above itself, this bars object is inserted between the two. If this bars object
is already between two other bars, the two other bars will be stacked on top of each other after
the operation.
To remove this bars plottable from any stacking, set \a bars to 0.
\see moveBelow, barBelow, barAbove
*/
void QCPBars::moveAbove(QCPBars *bars)
{
if (bars == this) return;
if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
{
qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
return;
}
// remove from stacking:
connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
// if new bar given, insert this bar above it:
if (bars)
{
if (bars->mBarAbove)
connectBars(this, bars->mBarAbove.data());
connectBars(bars, this);
}
}
/*!
Adds the provided data points in \a dataMap to the current data.
\see removeData
*/
void QCPBars::addData(const QCPBarDataMap &dataMap)
{
mData->unite(dataMap);
}
/*! \overload
Adds the provided single data point in \a data to the current data.
\see removeData
*/
void QCPBars::addData(const QCPBarData &data)
{
mData->insertMulti(data.key, data);
}
/*! \overload
Adds the provided single data point as \a key and \a value tuple to the current data
\see removeData
*/
void QCPBars::addData(double key, double value)
{
QCPBarData newData;
newData.key = key;
newData.value = value;
mData->insertMulti(newData.key, newData);
}
/*! \overload
Adds the provided data points as \a key and \a value tuples to the current data.
\see removeData
*/
void QCPBars::addData(const QVector<double> &keys, const QVector<double> &values)
{
int n = keys.size();
n = qMin(n, values.size());
QCPBarData newData;
for (int i=0; i<n; ++i)
{
newData.key = keys[i];
newData.value = values[i];
mData->insertMulti(newData.key, newData);
}
}
/*!
Removes all data points with key smaller than \a key.
\see addData, clearData
*/
void QCPBars::removeDataBefore(double key)
{
QCPBarDataMap::iterator it = mData->begin();
while (it != mData->end() && it.key() < key)
it = mData->erase(it);
}
/*!
Removes all data points with key greater than \a key.
\see addData, clearData
*/
void QCPBars::removeDataAfter(double key)
{
if (mData->isEmpty()) return;
QCPBarDataMap::iterator it = mData->upperBound(key);
while (it != mData->end())
it = mData->erase(it);
}
/*!
Removes all data points with key between \a fromKey and \a toKey. if \a fromKey is
greater or equal to \a toKey, the function does nothing. To remove a single data point with known
key, use \ref removeData(double key).
\see addData, clearData
*/
void QCPBars::removeData(double fromKey, double toKey)
{
if (fromKey >= toKey || mData->isEmpty()) return;
QCPBarDataMap::iterator it = mData->upperBound(fromKey);
QCPBarDataMap::iterator itEnd = mData->upperBound(toKey);
while (it != itEnd)
it = mData->erase(it);
}
/*! \overload
Removes a single data point at \a key. If the position is not known with absolute precision,
consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval
around the suspected position, depeding on the precision with which the key is known.
\see addData, clearData
*/
void QCPBars::removeData(double key)
{
mData->remove(key);
}
/*!
Removes all data points.
\see removeData, removeDataAfter, removeDataBefore
*/
void QCPBars::clearData()
{
mData->clear();
}
/* inherits documentation from base class */
double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
{
QCPBarDataMap::ConstIterator it;
for (it = mData->constBegin(); it != mData->constEnd(); ++it)
{
if (getBarPolygon(it.value().key, it.value().value).boundingRect().contains(pos))
return mParentPlot->selectionTolerance()*0.99;
}
}
return -1;
}
/* inherits documentation from base class */
void QCPBars::draw(QCPPainter *painter)
{
if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (mData->isEmpty()) return;
QCPBarDataMap::const_iterator it, lower, upperEnd;
getVisibleDataBounds(lower, upperEnd);
for (it = lower; it != upperEnd; ++it)
{
// check data validity if flag set:
#ifdef QCUSTOMPLOT_CHECK_DATA
if (QCP::isInvalidData(it.value().key, it.value().value))
qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "of drawn range invalid." << "Plottable name:" << name();
#endif
QPolygonF barPolygon = getBarPolygon(it.key(), it.value().value);
// draw bar fill:
if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0)
{
applyFillAntialiasingHint(painter);
painter->setPen(Qt::NoPen);
painter->setBrush(mainBrush());
painter->drawPolygon(barPolygon);
}
// draw bar line:
if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)
{
applyDefaultAntialiasingHint(painter);
painter->setPen(mainPen());
painter->setBrush(Qt::NoBrush);
painter->drawPolyline(barPolygon);
}
}
}
/* inherits documentation from base class */
void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
{
// draw filled rect:
applyDefaultAntialiasingHint(painter);
painter->setBrush(mBrush);
painter->setPen(mPen);
QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
r.moveCenter(rect.center());
painter->drawRect(r);
}
/*! \internal
called by \ref draw to determine which data (key) range is visible at the current key axis range
setting, so only that needs to be processed. It also takes into account the bar width.
\a lower returns an iterator to the lowest data point that needs to be taken into account when
plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
lower may still be just outside the visible range.
\a upperEnd returns an iterator one higher than the highest visible data point. Same as before, \a
upperEnd may also lie just outside of the visible range.
if the bars plottable contains no data, both \a lower and \a upperEnd point to constEnd.
*/
void QCPBars::getVisibleDataBounds(QCPBarDataMap::const_iterator &lower, QCPBarDataMap::const_iterator &upperEnd) const
{
if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
if (mData->isEmpty())
{
lower = mData->constEnd();
upperEnd = mData->constEnd();
return;
}
// get visible data range as QMap iterators
lower = mData->lowerBound(mKeyAxis.data()->range().lower);
upperEnd = mData->upperBound(mKeyAxis.data()->range().upper);
double lowerPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().lower);
double upperPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().upper);
bool isVisible = false;
// walk left from lbound to find lower bar that actually is completely outside visible pixel range:
QCPBarDataMap::const_iterator it = lower;
while (it != mData->constBegin())
{
--it;
QRectF barBounds = getBarPolygon(it.value().key, it.value().value).boundingRect();
if (mKeyAxis.data()->orientation() == Qt::Horizontal)
isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.left() <= lowerPixelBound));
else // keyaxis is vertical
isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.bottom() >= lowerPixelBound));
if (isVisible)
lower = it;
else
break;
}
// walk right from ubound to find upper bar that actually is completely outside visible pixel range:
it = upperEnd;
while (it != mData->constEnd())
{
QRectF barBounds = getBarPolygon(upperEnd.value().key, upperEnd.value().value).boundingRect();
if (mKeyAxis.data()->orientation() == Qt::Horizontal)
isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.right() >= upperPixelBound));
else // keyaxis is vertical
isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.top() <= upperPixelBound));
if (isVisible)
upperEnd = it+1;
else
break;
++it;
}
}
/*! \internal
Returns the polygon of a single bar with \a key and \a value. The Polygon is open at the bottom
and shifted according to the bar stacking (see \ref moveAbove) and base value (see \ref
setBaseValue).
*/
QPolygonF QCPBars::getBarPolygon(double key, double value) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); }
QPolygonF result;
double lowerPixelWidth, upperPixelWidth;
getPixelWidth(key, lowerPixelWidth, upperPixelWidth);
double base = getStackedBaseValue(key, value >= 0);
double basePixel = valueAxis->coordToPixel(base);
double valuePixel = valueAxis->coordToPixel(base+value);
double keyPixel = keyAxis->coordToPixel(key);
if (mBarsGroup)
keyPixel += mBarsGroup->keyPixelOffset(this, key);
if (keyAxis->orientation() == Qt::Horizontal)
{
result << QPointF(keyPixel+lowerPixelWidth, basePixel);
result << QPointF(keyPixel+lowerPixelWidth, valuePixel);
result << QPointF(keyPixel+upperPixelWidth, valuePixel);
result << QPointF(keyPixel+upperPixelWidth, basePixel);
} else
{
result << QPointF(basePixel, keyPixel+lowerPixelWidth);
result << QPointF(valuePixel, keyPixel+lowerPixelWidth);
result << QPointF(valuePixel, keyPixel+upperPixelWidth);
result << QPointF(basePixel, keyPixel+upperPixelWidth);
}
return result;
}
/*! \internal
This function is used to determine the width of the bar at coordinate \a key, according to the
specified width (\ref setWidth) and width type (\ref setWidthType).
The output parameters \a lower and \a upper return the number of pixels the bar extends to lower
and higher keys, relative to the \a key coordinate (so with a non-reversed horizontal axis, \a
lower is negative and \a upper positive).
*/
void QCPBars::getPixelWidth(double key, double &lower, double &upper) const
{
switch (mWidthType)
{
case wtAbsolute:
{
upper = mWidth*0.5;
lower = -upper;
if (mKeyAxis && (mKeyAxis.data()->rangeReversed() ^ (mKeyAxis.data()->orientation() == Qt::Vertical)))
qSwap(lower, upper);
break;
}
case wtAxisRectRatio:
{
if (mKeyAxis && mKeyAxis.data()->axisRect())
{
if (mKeyAxis.data()->orientation() == Qt::Horizontal)
upper = mKeyAxis.data()->axisRect()->width()*mWidth*0.5;
else
upper = mKeyAxis.data()->axisRect()->height()*mWidth*0.5;
lower = -upper;
if (mKeyAxis && (mKeyAxis.data()->rangeReversed() ^ (mKeyAxis.data()->orientation() == Qt::Vertical)))
qSwap(lower, upper);
} else
qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined";
break;
}
case wtPlotCoords:
{
if (mKeyAxis)
{
double keyPixel = mKeyAxis.data()->coordToPixel(key);
upper = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel;
lower = mKeyAxis.data()->coordToPixel(key-mWidth*0.5)-keyPixel;
// no need to qSwap(lower, higher) when range reversed, because higher/lower are gained by
// coordinate transform which includes range direction
} else
qDebug() << Q_FUNC_INFO << "No key axis defined";
break;
}
}
}
/*! \internal
This function is called to find at which value to start drawing the base of a bar at \a key, when
it is stacked on top of another QCPBars (e.g. with \ref moveAbove).
positive and negative bars are separated per stack (positive are stacked above baseValue upwards,
negative are stacked below baseValue downwards). This can be indicated with \a positive. So if the
bar for which we need the base value is negative, set \a positive to false.
*/
double QCPBars::getStackedBaseValue(double key, bool positive) const
{
if (mBarBelow)
{
double max = 0; // don't use mBaseValue here because only base value of bottom-most bar has meaning in a bar stack
// find bars of mBarBelow that are approximately at key and find largest one:
double epsilon = qAbs(key)*1e-6; // should be safe even when changed to use float at some point
if (key == 0)
epsilon = 1e-6;
QCPBarDataMap::const_iterator it = mBarBelow.data()->mData->lowerBound(key-epsilon);
QCPBarDataMap::const_iterator itEnd = mBarBelow.data()->mData->upperBound(key+epsilon);
while (it != itEnd)
{
if ((positive && it.value().value > max) ||
(!positive && it.value().value < max))
max = it.value().value;
++it;
}
// recurse down the bar-stack to find the total height:
return max + mBarBelow.data()->getStackedBaseValue(key, positive);
} else
return mBaseValue;
}
/*! \internal
Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. The bar(s)
currently above lower and below upper will become disconnected to lower/upper.
If lower is zero, upper will be disconnected at the bottom.
If upper is zero, lower will be disconnected at the top.
*/
void QCPBars::connectBars(QCPBars *lower, QCPBars *upper)
{
if (!lower && !upper) return;
if (!lower) // disconnect upper at bottom
{
// disconnect old bar below upper:
if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
upper->mBarBelow.data()->mBarAbove = 0;
upper->mBarBelow = 0;
} else if (!upper) // disconnect lower at top
{
// disconnect old bar above lower:
if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
lower->mBarAbove.data()->mBarBelow = 0;
lower->mBarAbove = 0;
} else // connect lower and upper
{
// disconnect old bar above lower:
if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
lower->mBarAbove.data()->mBarBelow = 0;
// disconnect old bar below upper:
if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
upper->mBarBelow.data()->mBarAbove = 0;
lower->mBarAbove = upper;
upper->mBarBelow = lower;
}
}
/* inherits documentation from base class */
QCPRange QCPBars::getKeyRange(bool &foundRange, SignDomain inSignDomain) const
{
QCPRange range;
bool haveLower = false;
bool haveUpper = false;
double current;
QCPBarDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
current = it.value().key;
if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0))
{
if (current < range.lower || !haveLower)
{
range.lower = current;
haveLower = true;
}
if (current > range.upper || !haveUpper)
{
range.upper = current;
haveUpper = true;
}
}
++it;
}
// determine exact range of bars by including bar width and barsgroup offset:
if (haveLower && mKeyAxis)
{
double lowerPixelWidth, upperPixelWidth, keyPixel;
getPixelWidth(range.lower, lowerPixelWidth, upperPixelWidth);
keyPixel = mKeyAxis.data()->coordToPixel(range.lower) + lowerPixelWidth;
if (mBarsGroup)
keyPixel += mBarsGroup->keyPixelOffset(this, range.lower);
range.lower = mKeyAxis.data()->pixelToCoord(keyPixel);
}
if (haveUpper && mKeyAxis)
{
double lowerPixelWidth, upperPixelWidth, keyPixel;
getPixelWidth(range.upper, lowerPixelWidth, upperPixelWidth);
keyPixel = mKeyAxis.data()->coordToPixel(range.upper) + upperPixelWidth;
if (mBarsGroup)
keyPixel += mBarsGroup->keyPixelOffset(this, range.upper);
range.upper = mKeyAxis.data()->pixelToCoord(keyPixel);
}
foundRange = haveLower && haveUpper;
return range;
}
/* inherits documentation from base class */
QCPRange QCPBars::getValueRange(bool &foundRange, SignDomain inSignDomain) const
{
QCPRange range;
range.lower = mBaseValue;
range.upper = mBaseValue;
bool haveLower = true; // set to true, because baseValue should always be visible in bar charts
bool haveUpper = true; // set to true, because baseValue should always be visible in bar charts
double current;
QCPBarDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
current = it.value().value + getStackedBaseValue(it.value().key, it.value().value >= 0);
if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0))
{
if (current < range.lower || !haveLower)
{
range.lower = current;
haveLower = true;
}
if (current > range.upper || !haveUpper)
{
range.upper = current;
haveUpper = true;
}
}
++it;
}
foundRange = true; // return true because bar charts always have the 0-line visible
return range;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPStatisticalBox
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPStatisticalBox
\brief A plottable representing a single statistical box in a plot.
\image html QCPStatisticalBox.png
To plot data, assign it with the individual parameter functions or use \ref setData to set all
parameters at once. The individual functions are:
\li \ref setMinimum
\li \ref setLowerQuartile
\li \ref setMedian
\li \ref setUpperQuartile
\li \ref setMaximum
Additionally you can define a list of outliers, drawn as scatter datapoints:
\li \ref setOutliers
\section appearance Changing the appearance
The appearance of the box itself is controlled via \ref setPen and \ref setBrush. You may change
the width of the box with \ref setWidth in plot coordinates (not pixels).
Analog functions exist for the minimum/maximum-whiskers: \ref setWhiskerPen, \ref
setWhiskerBarPen, \ref setWhiskerWidth. The whisker width is the width of the bar at the top
(maximum) and bottom (minimum).
The median indicator line has its own pen, \ref setMedianPen.
If the whisker backbone pen is changed, make sure to set the capStyle to Qt::FlatCap. Else, the
backbone line might exceed the whisker bars by a few pixels due to the pen cap being not
perfectly flat.
The Outlier data points are drawn as normal scatter points. Their look can be controlled with
\ref setOutlierStyle
\section usage Usage
Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable.
Usually, you first create an instance and add it to the customPlot:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-1
and then modify the properties of the newly created plottable, e.g.:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-2
*/
/*!
Constructs a statistical box which uses \a keyAxis as its key axis ("x") and \a valueAxis as its
value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and
not have the same orientation. If either of these restrictions is violated, a corresponding
message is printed to the debug output (qDebug), the construction is not aborted, though.
The constructed statistical box can be added to the plot with QCustomPlot::addPlottable,
QCustomPlot then takes ownership of the statistical box.
*/
QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPAbstractPlottable(keyAxis, valueAxis),
mKey(0),
mMinimum(0),
mLowerQuartile(0),
mMedian(0),
mUpperQuartile(0),
mMaximum(0)
{
setOutlierStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, 6));
setWhiskerWidth(0.2);
setWidth(0.5);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue, 2.5));
setMedianPen(QPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap));
setWhiskerPen(QPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap));
setWhiskerBarPen(QPen(Qt::black));
setBrush(Qt::NoBrush);
setSelectedBrush(Qt::NoBrush);
}
/*!
Sets the key coordinate of the statistical box.
*/
void QCPStatisticalBox::setKey(double key)
{
mKey = key;
}
/*!
Sets the parameter "minimum" of the statistical box plot. This is the position of the lower
whisker, typically the minimum measurement of the sample that's not considered an outlier.
\see setMaximum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth
*/
void QCPStatisticalBox::setMinimum(double value)
{
mMinimum = value;
}
/*!
Sets the parameter "lower Quartile" of the statistical box plot. This is the lower end of the
box. The lower and the upper quartiles are the two statistical quartiles around the median of the
sample, they contain 50% of the sample data.
\see setUpperQuartile, setPen, setBrush, setWidth
*/
void QCPStatisticalBox::setLowerQuartile(double value)
{
mLowerQuartile = value;
}
/*!
Sets the parameter "median" of the statistical box plot. This is the value of the median mark
inside the quartile box. The median separates the sample data in half (50% of the sample data is
below/above the median).
\see setMedianPen
*/
void QCPStatisticalBox::setMedian(double value)
{
mMedian = value;
}
/*!
Sets the parameter "upper Quartile" of the statistical box plot. This is the upper end of the
box. The lower and the upper quartiles are the two statistical quartiles around the median of the
sample, they contain 50% of the sample data.
\see setLowerQuartile, setPen, setBrush, setWidth
*/
void QCPStatisticalBox::setUpperQuartile(double value)
{
mUpperQuartile = value;
}
/*!
Sets the parameter "maximum" of the statistical box plot. This is the position of the upper
whisker, typically the maximum measurement of the sample that's not considered an outlier.
\see setMinimum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth
*/
void QCPStatisticalBox::setMaximum(double value)
{
mMaximum = value;
}
/*!
Sets a vector of outlier values that will be drawn as scatters. Any data points in the sample
that are not within the whiskers (\ref setMinimum, \ref setMaximum) should be considered outliers
and displayed as such.
\see setOutlierStyle
*/
void QCPStatisticalBox::setOutliers(const QVector<double> &values)
{
mOutliers = values;
}
/*!
Sets all parameters of the statistical box plot at once.
\see setKey, setMinimum, setLowerQuartile, setMedian, setUpperQuartile, setMaximum
*/
void QCPStatisticalBox::setData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum)
{
setKey(key);
setMinimum(minimum);
setLowerQuartile(lowerQuartile);
setMedian(median);
setUpperQuartile(upperQuartile);
setMaximum(maximum);
}
/*!
Sets the width of the box in key coordinates.
\see setWhiskerWidth
*/
void QCPStatisticalBox::setWidth(double width)
{
mWidth = width;
}
/*!
Sets the width of the whiskers (\ref setMinimum, \ref setMaximum) in key coordinates.
\see setWidth
*/
void QCPStatisticalBox::setWhiskerWidth(double width)
{
mWhiskerWidth = width;
}
/*!
Sets the pen used for drawing the whisker backbone (That's the line parallel to the value axis).
Make sure to set the \a pen capStyle to Qt::FlatCap to prevent the whisker backbone from reaching
a few pixels past the whisker bars, when using a non-zero pen width.
\see setWhiskerBarPen
*/
void QCPStatisticalBox::setWhiskerPen(const QPen &pen)
{
mWhiskerPen = pen;
}
/*!
Sets the pen used for drawing the whisker bars (Those are the lines parallel to the key axis at
each end of the whisker backbone).
\see setWhiskerPen
*/
void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen)
{
mWhiskerBarPen = pen;
}
/*!
Sets the pen used for drawing the median indicator line inside the statistical box.
*/
void QCPStatisticalBox::setMedianPen(const QPen &pen)
{
mMedianPen = pen;
}
/*!
Sets the appearance of the outlier data points.
\see setOutliers
*/
void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style)
{
mOutlierStyle = style;
}
/* inherits documentation from base class */
void QCPStatisticalBox::clearData()
{
setOutliers(QVector<double>());
setKey(0);
setMinimum(0);
setLowerQuartile(0);
setMedian(0);
setUpperQuartile(0);
setMaximum(0);
}
/* inherits documentation from base class */
double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
{
double posKey, posValue;
pixelsToCoords(pos, posKey, posValue);
// quartile box:
QCPRange keyRange(mKey-mWidth*0.5, mKey+mWidth*0.5);
QCPRange valueRange(mLowerQuartile, mUpperQuartile);
if (keyRange.contains(posKey) && valueRange.contains(posValue))
return mParentPlot->selectionTolerance()*0.99;
// min/max whiskers:
if (QCPRange(mMinimum, mMaximum).contains(posValue))
return qAbs(mKeyAxis.data()->coordToPixel(mKey)-mKeyAxis.data()->coordToPixel(posKey));
}
return -1;
}
/* inherits documentation from base class */
void QCPStatisticalBox::draw(QCPPainter *painter)
{
if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
// check data validity if flag set:
#ifdef QCUSTOMPLOT_CHECK_DATA
if (QCP::isInvalidData(mKey, mMedian) ||
QCP::isInvalidData(mLowerQuartile, mUpperQuartile) ||
QCP::isInvalidData(mMinimum, mMaximum))
qDebug() << Q_FUNC_INFO << "Data point at" << mKey << "of drawn range has invalid data." << "Plottable name:" << name();
for (int i=0; i<mOutliers.size(); ++i)
if (QCP::isInvalidData(mOutliers.at(i)))
qDebug() << Q_FUNC_INFO << "Data point outlier at" << mKey << "of drawn range invalid." << "Plottable name:" << name();
#endif
QRectF quartileBox;
drawQuartileBox(painter, &quartileBox);
painter->save();
painter->setClipRect(quartileBox, Qt::IntersectClip);
drawMedian(painter);
painter->restore();
drawWhiskers(painter);
drawOutliers(painter);
}
/* inherits documentation from base class */
void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
{
// draw filled rect:
applyDefaultAntialiasingHint(painter);
painter->setPen(mPen);
painter->setBrush(mBrush);
QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
r.moveCenter(rect.center());
painter->drawRect(r);
}
/*! \internal
Draws the quartile box. \a box is an output parameter that returns the quartile box (in pixel
coordinates) which is used to set the clip rect of the painter before calling \ref drawMedian (so
the median doesn't draw outside the quartile box).
*/
void QCPStatisticalBox::drawQuartileBox(QCPPainter *painter, QRectF *quartileBox) const
{
QRectF box;
box.setTopLeft(coordsToPixels(mKey-mWidth*0.5, mUpperQuartile));
box.setBottomRight(coordsToPixels(mKey+mWidth*0.5, mLowerQuartile));
applyDefaultAntialiasingHint(painter);
painter->setPen(mainPen());
painter->setBrush(mainBrush());
painter->drawRect(box);
if (quartileBox)
*quartileBox = box;
}
/*! \internal
Draws the median line inside the quartile box.
*/
void QCPStatisticalBox::drawMedian(QCPPainter *painter) const
{
QLineF medianLine;
medianLine.setP1(coordsToPixels(mKey-mWidth*0.5, mMedian));
medianLine.setP2(coordsToPixels(mKey+mWidth*0.5, mMedian));
applyDefaultAntialiasingHint(painter);
painter->setPen(mMedianPen);
painter->drawLine(medianLine);
}
/*! \internal
Draws both whisker backbones and bars.
*/
void QCPStatisticalBox::drawWhiskers(QCPPainter *painter) const
{
QLineF backboneMin, backboneMax, barMin, barMax;
backboneMax.setPoints(coordsToPixels(mKey, mUpperQuartile), coordsToPixels(mKey, mMaximum));
backboneMin.setPoints(coordsToPixels(mKey, mLowerQuartile), coordsToPixels(mKey, mMinimum));
barMax.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMaximum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMaximum));
barMin.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMinimum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMinimum));
applyErrorBarsAntialiasingHint(painter);
painter->setPen(mWhiskerPen);
painter->drawLine(backboneMin);
painter->drawLine(backboneMax);
painter->setPen(mWhiskerBarPen);
painter->drawLine(barMin);
painter->drawLine(barMax);
}
/*! \internal
Draws the outlier scatter points.
*/
void QCPStatisticalBox::drawOutliers(QCPPainter *painter) const
{
applyScattersAntialiasingHint(painter);
mOutlierStyle.applyTo(painter, mPen);
for (int i=0; i<mOutliers.size(); ++i)
mOutlierStyle.drawShape(painter, coordsToPixels(mKey, mOutliers.at(i)));
}
/* inherits documentation from base class */
QCPRange QCPStatisticalBox::getKeyRange(bool &foundRange, SignDomain inSignDomain) const
{
foundRange = true;
if (inSignDomain == sdBoth)
{
return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5);
} else if (inSignDomain == sdNegative)
{
if (mKey+mWidth*0.5 < 0)
return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5);
else if (mKey < 0)
return QCPRange(mKey-mWidth*0.5, mKey);
else
{
foundRange = false;
return QCPRange();
}
} else if (inSignDomain == sdPositive)
{
if (mKey-mWidth*0.5 > 0)
return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5);
else if (mKey > 0)
return QCPRange(mKey, mKey+mWidth*0.5);
else
{
foundRange = false;
return QCPRange();
}
}
foundRange = false;
return QCPRange();
}
/* inherits documentation from base class */
QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, SignDomain inSignDomain) const
{
QVector<double> values; // values that must be considered (i.e. all outliers and the five box-parameters)
values.reserve(mOutliers.size() + 5);
values << mMaximum << mUpperQuartile << mMedian << mLowerQuartile << mMinimum;
values << mOutliers;
// go through values and find the ones in legal range:
bool haveUpper = false;
bool haveLower = false;
double upper = 0;
double lower = 0;
for (int i=0; i<values.size(); ++i)
{
if ((inSignDomain == sdNegative && values.at(i) < 0) ||
(inSignDomain == sdPositive && values.at(i) > 0) ||
(inSignDomain == sdBoth))
{
if (values.at(i) > upper || !haveUpper)
{
upper = values.at(i);
haveUpper = true;
}
if (values.at(i) < lower || !haveLower)
{
lower = values.at(i);
haveLower = true;
}
}
}
// return the bounds if we found some sensible values:
if (haveLower && haveUpper)
{
foundRange = true;
return QCPRange(lower, upper);
} else // might happen if all values are in other sign domain
{
foundRange = false;
return QCPRange();
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPColorMapData
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPColorMapData
\brief Holds the two-dimensional data of a QCPColorMap plottable.
This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref
QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a
color, depending on the value.
The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize).
Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref
setKeyRange, \ref setValueRange).
The data cells can be accessed in two ways: They can be directly addressed by an integer index
with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot
coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are
provided by the functions \ref coordToCell and \ref cellToCoord.
This class also buffers the minimum and maximum values that are in the data set, to provide
QCPColorMap::rescaleDataRange with the necessary information quickly. Setting a cell to a value
that is greater than the current maximum increases this maximum to the new value. However,
setting the cell that currently holds the maximum value to a smaller value doesn't decrease the
maximum again, because finding the true new maximum would require going through the entire data
array, which might be time consuming. The same holds for the data minimum. This functionality is
given by \ref recalculateDataBounds, such that you can decide when it is sensible to find the
true current minimum and maximum. The method QCPColorMap::rescaleDataRange offers a convenience
parameter \a recalculateDataBounds which may be set to true to automatically call \ref
recalculateDataBounds internally.
*/
/* start of documentation of inline functions */
/*! \fn bool QCPColorMapData::isEmpty() const
Returns whether this instance carries no data. This is equivalent to having a size where at least
one of the dimensions is 0 (see \ref setSize).
*/
/* end of documentation of inline functions */
/*!
Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction
and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap
at the coordinates \a keyRange and \a valueRange.
\see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange
*/
QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) :
mKeySize(0),
mValueSize(0),
mKeyRange(keyRange),
mValueRange(valueRange),
mIsEmpty(true),
mData(0),
mDataModified(true)
{
setSize(keySize, valueSize);
fill(0);
}
QCPColorMapData::~QCPColorMapData()
{
if (mData)
delete[] mData;
}
/*!
Constructs a new QCPColorMapData instance copying the data and range of \a other.
*/
QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) :
mKeySize(0),
mValueSize(0),
mIsEmpty(true),
mData(0),
mDataModified(true)
{
*this = other;
}
/*!
Overwrites this color map data instance with the data stored in \a other.
*/
QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other)
{
if (&other != this)
{
const int keySize = other.keySize();
const int valueSize = other.valueSize();
setSize(keySize, valueSize);
setRange(other.keyRange(), other.valueRange());
if (!mIsEmpty)
memcpy(mData, other.mData, sizeof(mData[0])*keySize*valueSize);
mDataBounds = other.mDataBounds;
mDataModified = true;
}
return *this;
}
/* undocumented getter */
double QCPColorMapData::data(double key, double value)
{
int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5;
int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5;
if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
return mData[valueCell*mKeySize + keyCell];
else
return 0;
}
/* undocumented getter */
double QCPColorMapData::cell(int keyIndex, int valueIndex)
{
if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
return mData[valueIndex*mKeySize + keyIndex];
else
return 0;
}
/*!
Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in
the value dimension.
The current data is discarded and the map cells are set to 0, unless the map had already the
requested size.
Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref
isEmpty returns true.
\see setRange, setKeySize, setValueSize
*/
void QCPColorMapData::setSize(int keySize, int valueSize)
{
if (keySize != mKeySize || valueSize != mValueSize)
{
mKeySize = keySize;
mValueSize = valueSize;
if (mData)
delete[] mData;
mIsEmpty = mKeySize == 0 || mValueSize == 0;
if (!mIsEmpty)
{
#ifdef __EXCEPTIONS
try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message
#endif
mData = new double[mKeySize*mValueSize];
#ifdef __EXCEPTIONS
} catch (...) { mData = 0; }
#endif
if (mData)
fill(0);
else
qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize;
} else
mData = 0;
mDataModified = true;
}
}
/*!
Resizes the data array to have \a keySize cells in the key dimension.
The current data is discarded and the map cells are set to 0, unless the map had already the
requested size.
Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true.
\see setKeyRange, setSize, setValueSize
*/
void QCPColorMapData::setKeySize(int keySize)
{
setSize(keySize, mValueSize);
}
/*!
Resizes the data array to have \a valueSize cells in the value dimension.
The current data is discarded and the map cells are set to 0, unless the map had already the
requested size.
Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true.
\see setValueRange, setSize, setKeySize
*/
void QCPColorMapData::setValueSize(int valueSize)
{
setSize(mKeySize, valueSize);
}
/*!
Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area
covered by the color map in plot coordinates.
The outer cells will be centered on the range boundaries given to this function. For example, if
the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
be cells centered on the key coordinates 2, 2.5 and 3.
\see setSize
*/
void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange)
{
setKeyRange(keyRange);
setValueRange(valueRange);
}
/*!
Sets the coordinate range the data shall be distributed over in the key dimension. Together with
the value range, This defines the rectangular area covered by the color map in plot coordinates.
The outer cells will be centered on the range boundaries given to this function. For example, if
the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
be cells centered on the key coordinates 2, 2.5 and 3.
\see setRange, setValueRange, setSize
*/
void QCPColorMapData::setKeyRange(const QCPRange &keyRange)
{
mKeyRange = keyRange;
}
/*!
Sets the coordinate range the data shall be distributed over in the value dimension. Together with
the key range, This defines the rectangular area covered by the color map in plot coordinates.
The outer cells will be centered on the range boundaries given to this function. For example, if
the value size (\ref setValueSize) is 3 and \a valueRange is set to <tt>QCPRange(2, 3)</tt> there
will be cells centered on the value coordinates 2, 2.5 and 3.
\see setRange, setKeyRange, setSize
*/
void QCPColorMapData::setValueRange(const QCPRange &valueRange)
{
mValueRange = valueRange;
}
/*!
Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a
z.
\note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
determine the cell index. Rather directly access the cell index with \ref
QCPColorMapData::setCell.
\see setCell, setRange
*/
void QCPColorMapData::setData(double key, double value, double z)
{
int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5;
int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5;
if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
{
mData[valueCell*mKeySize + keyCell] = z;
if (z < mDataBounds.lower)
mDataBounds.lower = z;
if (z > mDataBounds.upper)
mDataBounds.upper = z;
mDataModified = true;
}
}
/*!
Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices
enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see
\ref setSize).
In the standard plot configuration (horizontal key axis and vertical value axis, both not
range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with
indices (keySize-1, valueSize-1) is in the top right corner of the color map.
\see setData, setSize
*/
void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z)
{
if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
{
mData[valueIndex*mKeySize + keyIndex] = z;
if (z < mDataBounds.lower)
mDataBounds.lower = z;
if (z > mDataBounds.upper)
mDataBounds.upper = z;
mDataModified = true;
}
}
/*!
Goes through the data and updates the buffered minimum and maximum data values.
Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange
and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten
with a smaller or larger value respectively, since the buffered maximum/minimum values have been
updated the last time. Why this is the case is explained in the class description (\ref
QCPColorMapData).
Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a
recalculateDataBounds for convenience. Setting this to true will call this method for you, before
doing the rescale.
*/
void QCPColorMapData::recalculateDataBounds()
{
if (mKeySize > 0 && mValueSize > 0)
{
double minHeight = mData[0];
double maxHeight = mData[0];
const int dataCount = mValueSize*mKeySize;
for (int i=0; i<dataCount; ++i)
{
if (mData[i] > maxHeight)
maxHeight = mData[i];
if (mData[i] < minHeight)
minHeight = mData[i];
}
mDataBounds.lower = minHeight;
mDataBounds.upper = maxHeight;
}
}
/*!
Frees the internal data memory.
This is equivalent to calling \ref setSize "setSize(0, 0)".
*/
void QCPColorMapData::clear()
{
setSize(0, 0);
}
/*!
Sets all cells to the value \a z.
*/
void QCPColorMapData::fill(double z)
{
const int dataCount = mValueSize*mKeySize;
for (int i=0; i<dataCount; ++i)
mData[i] = z;
mDataBounds = QCPRange(z, z);
mDataModified = true;
}
/*!
Transforms plot coordinates given by \a key and \a value to cell indices of this QCPColorMapData
instance. The resulting cell indices are returned via the output parameters \a keyIndex and \a
valueIndex.
The retrieved key/value cell indices can then be used for example with \ref setCell.
If you are only interested in a key or value index, you may pass 0 as \a valueIndex or \a
keyIndex.
\note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
you shouldn't use the \ref QCPColorMapData::coordToCell method as it uses a linear transformation to
determine the cell index.
\see cellToCoord, QCPAxis::coordToPixel
*/
void QCPColorMapData::coordToCell(double key, double value, int *keyIndex, int *valueIndex) const
{
if (keyIndex)
*keyIndex = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5;
if (valueIndex)
*valueIndex = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5;
}
/*!
Transforms cell indices given by \a keyIndex and \a valueIndex to cell indices of this QCPColorMapData
instance. The resulting coordinates are returned via the output parameters \a key and \a
value.
If you are only interested in a key or value coordinate, you may pass 0 as \a key or \a
value.
\note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
you shouldn't use the \ref QCPColorMapData::cellToCoord method as it uses a linear transformation to
determine the cell index.
\see coordToCell, QCPAxis::pixelToCoord
*/
void QCPColorMapData::cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const
{
if (key)
*key = keyIndex/(double)(mKeySize-1)*(mKeyRange.upper-mKeyRange.lower)+mKeyRange.lower;
if (value)
*value = valueIndex/(double)(mValueSize-1)*(mValueRange.upper-mValueRange.lower)+mValueRange.lower;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPColorMap
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPColorMap
\brief A plottable representing a two-dimensional color map in a plot.
\image html QCPColorMap.png
The data is stored in the class \ref QCPColorMapData, which can be accessed via the data()
method.
A color map has three dimensions to represent a data point: The \a key dimension, the \a value
dimension and the \a data dimension. As with other plottables such as graphs, \a key and \a value
correspond to two orthogonal axes on the QCustomPlot surface that you specify in the QCPColorMap
constructor. The \a data dimension however is encoded as the color of the point at (\a key, \a
value).
Set the number of points (or \a cells) in the key/value dimension via \ref
QCPColorMapData::setSize. The plot coordinate range over which these points will be displayed is
specified via \ref QCPColorMapData::setRange. The first cell will be centered on the lower range
boundary and the last cell will be centered on the upper range boundary. The data can be set by
either accessing the cells directly with QCPColorMapData::setCell or by addressing the cells via
their plot coordinates with \ref QCPColorMapData::setData. If possible, you should prefer
setCell, since it doesn't need to do any coordinate transformation and thus performs a bit
better.
The cell with index (0, 0) is at the bottom left, if the color map uses normal (i.e. not reversed)
key and value axes.
To show the user which colors correspond to which \a data values, a \ref QCPColorScale is
typically placed to the right of the axis rect. See the documentation there for details on how to
add and use a color scale.
\section appearance Changing the appearance
The central part of the appearance is the color gradient, which can be specified via \ref
setGradient. See the documentation of \ref QCPColorGradient for details on configuring a color
gradient.
The \a data range that is mapped to the colors of the gradient can be specified with \ref
setDataRange. To make the data range encompass the whole data set minimum to maximum, call \ref
rescaleDataRange.
\section usage Usage
Like all data representing objects in QCustomPlot, the QCPColorMap is a plottable
(QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
(QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.)
Usually, you first create an instance and add it to the customPlot:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-1
and then modify the properties of the newly created color map, e.g.:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-2
\note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
determine the cell index. Rather directly access the cell index with \ref
QCPColorMapData::setCell.
*/
/* start documentation of inline functions */
/*! \fn QCPColorMapData *QCPColorMap::data() const
Returns a pointer to the internal data storage of type \ref QCPColorMapData. Access this to
modify data points (cells) and the color map key/value range.
\see setData
*/
/* end documentation of inline functions */
/* start documentation of signals */
/*! \fn void QCPColorMap::dataRangeChanged(QCPRange newRange);
This signal is emitted when the data range changes.
\see setDataRange
*/
/*! \fn void QCPColorMap::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
This signal is emitted when the data scale type changes.
\see setDataScaleType
*/
/*! \fn void QCPColorMap::gradientChanged(QCPColorGradient newGradient);
This signal is emitted when the gradient changes.
\see setGradient
*/
/* end documentation of signals */
/*!
Constructs a color map with the specified \a keyAxis and \a valueAxis.
The constructed QCPColorMap can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
then takes ownership of the color map.
*/
QCPColorMap::QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPAbstractPlottable(keyAxis, valueAxis),
mDataScaleType(QCPAxis::stLinear),
mMapData(new QCPColorMapData(10, 10, QCPRange(0, 5), QCPRange(0, 5))),
mInterpolate(true),
mTightBoundary(false),
mMapImageInvalidated(true)
{
}
QCPColorMap::~QCPColorMap()
{
delete mMapData;
}
/*!
Replaces the current \ref data with the provided \a data.
If \a copy is set to true, the \a data object will only be copied. if false, the color map
takes ownership of the passed data and replaces the internal data pointer with it. This is
significantly faster than copying for large datasets.
*/
void QCPColorMap::setData(QCPColorMapData *data, bool copy)
{
if (mMapData == data)
{
qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast<quintptr>(data);
return;
}
if (copy)
{
*mMapData = *data;
} else
{
delete mMapData;
mMapData = data;
}
mMapImageInvalidated = true;
}
/*!
Sets the data range of this color map to \a dataRange. The data range defines which data values
are mapped to the color gradient.
To make the data range span the full range of the data set, use \ref rescaleDataRange.
\see QCPColorScale::setDataRange
*/
void QCPColorMap::setDataRange(const QCPRange &dataRange)
{
if (!QCPRange::validRange(dataRange)) return;
if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper)
{
if (mDataScaleType == QCPAxis::stLogarithmic)
mDataRange = dataRange.sanitizedForLogScale();
else
mDataRange = dataRange.sanitizedForLinScale();
mMapImageInvalidated = true;
emit dataRangeChanged(mDataRange);
}
}
/*!
Sets whether the data is correlated with the color gradient linearly or logarithmically.
\see QCPColorScale::setDataScaleType
*/
void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType)
{
if (mDataScaleType != scaleType)
{
mDataScaleType = scaleType;
mMapImageInvalidated = true;
emit dataScaleTypeChanged(mDataScaleType);
if (mDataScaleType == QCPAxis::stLogarithmic)
setDataRange(mDataRange.sanitizedForLogScale());
}
}
/*!
Sets the color gradient that is used to represent the data. For more details on how to create an
own gradient or use one of the preset gradients, see \ref QCPColorGradient.
The colors defined by the gradient will be used to represent data values in the currently set
data range, see \ref setDataRange. Data points that are outside this data range will either be
colored uniformly with the respective gradient boundary color, or the gradient will repeat,
depending on \ref QCPColorGradient::setPeriodic.
\see QCPColorScale::setGradient
*/
void QCPColorMap::setGradient(const QCPColorGradient &gradient)
{
if (mGradient != gradient)
{
mGradient = gradient;
mMapImageInvalidated = true;
emit gradientChanged(mGradient);
}
}
/*!
Sets whether the color map image shall use bicubic interpolation when displaying the color map
shrinked or expanded, and not at a 1:1 pixel-to-data scale.
\image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled"
*/
void QCPColorMap::setInterpolate(bool enabled)
{
mInterpolate = enabled;
mMapImageInvalidated = true; // because oversampling factors might need to change
}
/*!
Sets whether the outer most data rows and columns are clipped to the specified key and value
range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange).
if \a enabled is set to false, the data points at the border of the color map are drawn with the
same width and height as all other data points. Since the data points are represented by
rectangles of one color centered on the data coordinate, this means that the shown color map
extends by half a data point over the specified key/value range in each direction.
\image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled"
*/
void QCPColorMap::setTightBoundary(bool enabled)
{
mTightBoundary = enabled;
}
/*!
Associates the color scale \a colorScale with this color map.
This means that both the color scale and the color map synchronize their gradient, data range and
data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps
can be associated with one single color scale. This causes the color maps to also synchronize
those properties, via the mutual color scale.
This function causes the color map to adopt the current color gradient, data range and data scale
type of \a colorScale. After this call, you may change these properties at either the color map
or the color scale, and the setting will be applied to both.
Pass 0 as \a colorScale to disconnect the color scale from this color map again.
*/
void QCPColorMap::setColorScale(QCPColorScale *colorScale)
{
if (mColorScale) // unconnect signals from old color scale
{
disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
}
mColorScale = colorScale;
if (mColorScale) // connect signals to new color scale
{
setGradient(mColorScale.data()->gradient());
setDataRange(mColorScale.data()->dataRange());
setDataScaleType(mColorScale.data()->dataScaleType());
connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
}
}
/*!
Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the
current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods,
only for the third data dimension of the color map.
The minimum and maximum values of the data set are buffered in the internal QCPColorMapData
instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref
QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For
performance reasons, however, they are only updated in an expanding fashion. So the buffered
maximum can only increase and the buffered minimum can only decrease. In consequence, changes to
the data that actually lower the maximum of the data set (by overwriting the cell holding the
current maximum with a smaller value), aren't recognized and the buffered maximum overestimates
the true maximum of the data set. The same happens for the buffered minimum. To recalculate the
true minimum and maximum by explicitly looking at each cell, the method
QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a
recalculateDataBounds calls this method before setting the data range to the buffered minimum and
maximum.
\see setDataRange
*/
void QCPColorMap::rescaleDataRange(bool recalculateDataBounds)
{
if (recalculateDataBounds)
mMapData->recalculateDataBounds();
setDataRange(mMapData->dataBounds());
}
/*!
Takes the current appearance of the color map and updates the legend icon, which is used to
represent this color map in the legend (see \ref QCPLegend).
The \a transformMode specifies whether the rescaling is done by a faster, low quality image
scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm
(Qt::SmoothTransformation).
The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to
the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured
legend icon size, the thumb will be rescaled during drawing of the legend item.
\see setDataRange
*/
void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize)
{
if (mMapImage.isNull() && !data()->isEmpty())
updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet)
if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again
{
bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode);
}
}
/*!
Clears the colormap data by calling \ref QCPColorMapData::clear() on the internal data. This also
resizes the map to 0x0 cells.
*/
void QCPColorMap::clearData()
{
mMapData->clear();
}
/* inherits documentation from base class */
double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
{
double posKey, posValue;
pixelsToCoords(pos, posKey, posValue);
if (mMapData->keyRange().contains(posKey) && mMapData->valueRange().contains(posValue))
return mParentPlot->selectionTolerance()*0.99;
}
return -1;
}
/*! \internal
Updates the internal map image buffer by going through the internal \ref QCPColorMapData and
turning the data values into color pixels with \ref QCPColorGradient::colorize.
This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image
has been invalidated for a different reason (e.g. a change of the data range with \ref
setDataRange).
If the map cell count is low, the image created will be oversampled in order to avoid a
QPainter::drawImage bug which makes inner pixel boundaries jitter when stretch-drawing images
without smooth transform enabled. Accordingly, oversampling isn't performed if \ref
setInterpolate is true.
*/
void QCPColorMap::updateMapImage()
{
QCPAxis *keyAxis = mKeyAxis.data();
if (!keyAxis) return;
if (mMapData->isEmpty()) return;
const int keySize = mMapData->keySize();
const int valueSize = mMapData->valueSize();
int keyOversamplingFactor = mInterpolate ? 1 : (int)(1.0+100.0/(double)keySize); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on
int valueOversamplingFactor = mInterpolate ? 1 : (int)(1.0+100.0/(double)valueSize); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on
// resize mMapImage to correct dimensions including possible oversampling factors, according to key/value axes orientation:
if (keyAxis->orientation() == Qt::Horizontal && (mMapImage.width() != keySize*keyOversamplingFactor || mMapImage.height() != valueSize*valueOversamplingFactor))
mMapImage = QImage(QSize(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor), QImage::Format_RGB32);
else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.width() != valueSize*valueOversamplingFactor || mMapImage.height() != keySize*keyOversamplingFactor))
mMapImage = QImage(QSize(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor), QImage::Format_RGB32);
QImage *localMapImage = &mMapImage; // this is the image on which the colorization operates. Either the final mMapImage, or if we need oversampling, mUndersampledMapImage
if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1)
{
// resize undersampled map image to actual key/value cell sizes:
if (keyAxis->orientation() == Qt::Horizontal && (mUndersampledMapImage.width() != keySize || mUndersampledMapImage.height() != valueSize))
mUndersampledMapImage = QImage(QSize(keySize, valueSize), QImage::Format_RGB32);
else if (keyAxis->orientation() == Qt::Vertical && (mUndersampledMapImage.width() != valueSize || mUndersampledMapImage.height() != keySize))
mUndersampledMapImage = QImage(QSize(valueSize, keySize), QImage::Format_RGB32);
localMapImage = &mUndersampledMapImage; // make the colorization run on the undersampled image
} else if (!mUndersampledMapImage.isNull())
mUndersampledMapImage = QImage(); // don't need oversampling mechanism anymore (map size has changed) but mUndersampledMapImage still has nonzero size, free it
const double *rawData = mMapData->mData;
if (keyAxis->orientation() == Qt::Horizontal)
{
const int lineCount = valueSize;
const int rowCount = keySize;
for (int line=0; line<lineCount; ++line)
{
QRgb* pixels = reinterpret_cast<QRgb*>(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system)
mGradient.colorize(rawData+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic);
}
} else // keyAxis->orientation() == Qt::Vertical
{
const int lineCount = keySize;
const int rowCount = valueSize;
for (int line=0; line<lineCount; ++line)
{
QRgb* pixels = reinterpret_cast<QRgb*>(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system)
mGradient.colorize(rawData+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic);
}
}
if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1)
{
if (keyAxis->orientation() == Qt::Horizontal)
mMapImage = mUndersampledMapImage.scaled(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation);
else
mMapImage = mUndersampledMapImage.scaled(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation);
}
mMapData->mDataModified = false;
mMapImageInvalidated = false;
}
/* inherits documentation from base class */
void QCPColorMap::draw(QCPPainter *painter)
{
if (mMapData->isEmpty()) return;
if (!mKeyAxis || !mValueAxis) return;
applyDefaultAntialiasingHint(painter);
if (mMapData->mDataModified || mMapImageInvalidated)
updateMapImage();
// use buffer if painting vectorized (PDF):
bool useBuffer = painter->modes().testFlag(QCPPainter::pmVectorized);
QCPPainter *localPainter = painter; // will be redirected to paint on mapBuffer if painting vectorized
QRectF mapBufferTarget; // the rect in absolute widget coordinates where the visible map portion/buffer will end up in
QPixmap mapBuffer;
double mapBufferPixelRatio = 3; // factor by which DPI is increased in embedded bitmaps
if (useBuffer)
{
mapBufferTarget = painter->clipRegion().boundingRect();
mapBuffer = QPixmap((mapBufferTarget.size()*mapBufferPixelRatio).toSize());
mapBuffer.fill(Qt::transparent);
localPainter = new QCPPainter(&mapBuffer);
localPainter->scale(mapBufferPixelRatio, mapBufferPixelRatio);
localPainter->translate(-mapBufferTarget.topLeft());
}
QRectF imageRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized();
// extend imageRect to contain outer halves/quarters of bordering/cornering pixels (cells are centered on map range boundary):
double halfCellWidth = 0; // in pixels
double halfCellHeight = 0; // in pixels
if (keyAxis()->orientation() == Qt::Horizontal)
{
if (mMapData->keySize() > 1)
halfCellWidth = 0.5*imageRect.width()/(double)(mMapData->keySize()-1);
if (mMapData->valueSize() > 1)
halfCellHeight = 0.5*imageRect.height()/(double)(mMapData->valueSize()-1);
} else // keyAxis orientation is Qt::Vertical
{
if (mMapData->keySize() > 1)
halfCellHeight = 0.5*imageRect.height()/(double)(mMapData->keySize()-1);
if (mMapData->valueSize() > 1)
halfCellWidth = 0.5*imageRect.width()/(double)(mMapData->valueSize()-1);
}
imageRect.adjust(-halfCellWidth, -halfCellHeight, halfCellWidth, halfCellHeight);
bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
bool smoothBackup = localPainter->renderHints().testFlag(QPainter::SmoothPixmapTransform);
localPainter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate);
QRegion clipBackup;
if (mTightBoundary)
{
clipBackup = localPainter->clipRegion();
QRectF tightClipRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized();
localPainter->setClipRect(tightClipRect, Qt::IntersectClip);
}
localPainter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY));
if (mTightBoundary)
localPainter->setClipRegion(clipBackup);
localPainter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup);
if (useBuffer) // localPainter painted to mapBuffer, so now draw buffer with original painter
{
delete localPainter;
painter->drawPixmap(mapBufferTarget.toRect(), mapBuffer);
}
}
/* inherits documentation from base class */
void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
{
applyDefaultAntialiasingHint(painter);
// draw map thumbnail:
if (!mLegendIcon.isNull())
{
QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation);
QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height());
iconRect.moveCenter(rect.center());
painter->drawPixmap(iconRect.topLeft(), scaledIcon);
}
/*
// draw frame:
painter->setBrush(Qt::NoBrush);
painter->setPen(Qt::black);
painter->drawRect(rect.adjusted(1, 1, 0, 0));
*/
}
/* inherits documentation from base class */
QCPRange QCPColorMap::getKeyRange(bool &foundRange, SignDomain inSignDomain) const
{
foundRange = true;
QCPRange result = mMapData->keyRange();
result.normalize();
if (inSignDomain == QCPAbstractPlottable::sdPositive)
{
if (result.lower <= 0 && result.upper > 0)
result.lower = result.upper*1e-3;
else if (result.lower <= 0 && result.upper <= 0)
foundRange = false;
} else if (inSignDomain == QCPAbstractPlottable::sdNegative)
{
if (result.upper >= 0 && result.lower < 0)
result.upper = result.lower*1e-3;
else if (result.upper >= 0 && result.lower >= 0)
foundRange = false;
}
return result;
}
/* inherits documentation from base class */
QCPRange QCPColorMap::getValueRange(bool &foundRange, SignDomain inSignDomain) const
{
foundRange = true;
QCPRange result = mMapData->valueRange();
result.normalize();
if (inSignDomain == QCPAbstractPlottable::sdPositive)
{
if (result.lower <= 0 && result.upper > 0)
result.lower = result.upper*1e-3;
else if (result.lower <= 0 && result.upper <= 0)
foundRange = false;
} else if (inSignDomain == QCPAbstractPlottable::sdNegative)
{
if (result.upper >= 0 && result.lower < 0)
result.upper = result.lower*1e-3;
else if (result.upper >= 0 && result.lower >= 0)
foundRange = false;
}
return result;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPFinancialData
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPFinancialData
\brief Holds the data of one single data point for QCPFinancial.
The container for storing multiple data points is \ref QCPFinancialDataMap.
The stored data is:
\li \a key: coordinate on the key axis of this data point
\li \a open: The opening value at the data point
\li \a high: The high/maximum value at the data point
\li \a low: The low/minimum value at the data point
\li \a close: The closing value at the data point
\see QCPFinancialDataMap
*/
/*!
Constructs a data point with key and all values set to zero.
*/
QCPFinancialData::QCPFinancialData() :
key(0),
open(0),
high(0),
low(0),
close(0)
{
}
/*!
Constructs a data point with the specified \a key and OHLC values.
*/
QCPFinancialData::QCPFinancialData(double key, double open, double high, double low, double close) :
key(key),
open(open),
high(high),
low(low),
close(close)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPFinancial
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPFinancial
\brief A plottable representing a financial stock chart
\image html QCPFinancial.png
This plottable represents time series data binned to certain intervals, mainly used for stock
charts. The two common representations OHLC (Open-High-Low-Close) bars and Candlesticks can be
set via \ref setChartStyle.
The data is passed via \ref setData as a set of open/high/low/close values at certain keys
(typically times). This means the data must be already binned appropriately. If data is only
available as a series of values (e.g. \a price against \a time), you can use the static
convenience function \ref timeSeriesToOhlc to generate binned OHLC-data which can then be passed
to \ref setData.
The width of the OHLC bars/candlesticks can be controlled with \ref setWidth and is given in plot
key coordinates. A typical choice is to set it to (or slightly less than) one bin interval width.
\section appearance Changing the appearance
Charts can be either single- or two-colored (\ref setTwoColored). If set to be single-colored,
lines are drawn with the plottable's pen (\ref setPen) and fills with the brush (\ref setBrush).
If set to two-colored, positive changes of the value during an interval (\a close >= \a open) are
represented with a different pen and brush than negative changes (\a close < \a open). These can
be configured with \ref setPenPositive, \ref setPenNegative, \ref setBrushPositive, and \ref
setBrushNegative. In two-colored mode, the normal plottable pen/brush is ignored. Upon selection
however, the normal selected pen/brush (\ref setSelectedPen, \ref setSelectedBrush) is used,
irrespective of whether the chart is single- or two-colored.
*/
/* start of documentation of inline functions */
/*! \fn QCPFinancialDataMap *QCPFinancial::data() const
Returns a pointer to the internal data storage of type \ref QCPFinancialDataMap. You may use it to
directly manipulate the data, which may be more convenient and faster than using the regular \ref
setData or \ref addData methods, in certain situations.
*/
/* end of documentation of inline functions */
/*!
Constructs a financial chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
the same orientation. If either of these restrictions is violated, a corresponding message is
printed to the debug output (qDebug), the construction is not aborted, though.
The constructed QCPFinancial can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
then takes ownership of the financial chart.
*/
QCPFinancial::QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPAbstractPlottable(keyAxis, valueAxis),
mData(0),
mChartStyle(csOhlc),
mWidth(0.5),
mTwoColored(false),
mBrushPositive(QBrush(QColor(210, 210, 255))),
mBrushNegative(QBrush(QColor(255, 210, 210))),
mPenPositive(QPen(QColor(10, 40, 180))),
mPenNegative(QPen(QColor(180, 40, 10)))
{
mData = new QCPFinancialDataMap;
setSelectedPen(QPen(QColor(80, 80, 255), 2.5));
setSelectedBrush(QBrush(QColor(80, 80, 255)));
}
QCPFinancial::~QCPFinancial()
{
delete mData;
}
/*!
Replaces the current data with the provided \a data.
If \a copy is set to true, data points in \a data will only be copied. if false, the plottable
takes ownership of the passed data and replaces the internal data pointer with it. This is
significantly faster than copying for large datasets.
Alternatively, you can also access and modify the plottable's data via the \ref data method, which
returns a pointer to the internal \ref QCPFinancialDataMap.
\see timeSeriesToOhlc
*/
void QCPFinancial::setData(QCPFinancialDataMap *data, bool copy)
{
if (mData == data)
{
qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast<quintptr>(data);
return;
}
if (copy)
{
*mData = *data;
} else
{
delete mData;
mData = data;
}
}
/*! \overload
Replaces the current data with the provided open/high/low/close data. The provided vectors should
have equal length. Else, the number of added points will be the size of the smallest vector.
\see timeSeriesToOhlc
*/
void QCPFinancial::setData(const QVector<double> &key, const QVector<double> &open, const QVector<double> &high, const QVector<double> &low, const QVector<double> &close)
{
mData->clear();
int n = key.size();
n = qMin(n, open.size());
n = qMin(n, high.size());
n = qMin(n, low.size());
n = qMin(n, close.size());
for (int i=0; i<n; ++i)
{
mData->insertMulti(key[i], QCPFinancialData(key[i], open[i], high[i], low[i], close[i]));
}
}
/*!
Sets which representation style shall be used to display the OHLC data.
*/
void QCPFinancial::setChartStyle(QCPFinancial::ChartStyle style)
{
mChartStyle = style;
}
/*!
Sets the width of the individual bars/candlesticks to \a width in plot key coordinates.
A typical choice is to set it to (or slightly less than) one bin interval width.
*/
void QCPFinancial::setWidth(double width)
{
mWidth = width;
}
/*!
Sets whether this chart shall contrast positive from negative trends per data point by using two
separate colors to draw the respective bars/candlesticks.
If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
setBrush).
\see setPenPositive, setPenNegative, setBrushPositive, setBrushNegative
*/
void QCPFinancial::setTwoColored(bool twoColored)
{
mTwoColored = twoColored;
}
/*!
If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills
of data points with a positive trend (i.e. bars/candlesticks with close >= open).
If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
setBrush).
\see setBrushNegative, setPenPositive, setPenNegative
*/
void QCPFinancial::setBrushPositive(const QBrush &brush)
{
mBrushPositive = brush;
}
/*!
If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills
of data points with a negative trend (i.e. bars/candlesticks with close < open).
If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
setBrush).
\see setBrushPositive, setPenNegative, setPenPositive
*/
void QCPFinancial::setBrushNegative(const QBrush &brush)
{
mBrushNegative = brush;
}
/*!
If \ref setTwoColored is set to true, this function controls the pen that is used to draw
outlines of data points with a positive trend (i.e. bars/candlesticks with close >= open).
If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
setBrush).
\see setPenNegative, setBrushPositive, setBrushNegative
*/
void QCPFinancial::setPenPositive(const QPen &pen)
{
mPenPositive = pen;
}
/*!
If \ref setTwoColored is set to true, this function controls the pen that is used to draw
outlines of data points with a negative trend (i.e. bars/candlesticks with close < open).
If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
setBrush).
\see setPenPositive, setBrushNegative, setBrushPositive
*/
void QCPFinancial::setPenNegative(const QPen &pen)
{
mPenNegative = pen;
}
/*!
Adds the provided data points in \a dataMap to the current data.
Alternatively, you can also access and modify the data via the \ref data method, which returns a
pointer to the internal \ref QCPFinancialDataMap.
\see removeData
*/
void QCPFinancial::addData(const QCPFinancialDataMap &dataMap)
{
mData->unite(dataMap);
}
/*! \overload
Adds the provided single data point in \a data to the current data.
Alternatively, you can also access and modify the data via the \ref data method, which returns a
pointer to the internal \ref QCPFinancialData.
\see removeData
*/
void QCPFinancial::addData(const QCPFinancialData &data)
{
mData->insertMulti(data.key, data);
}
/*! \overload
Adds the provided single data point given by \a key, \a open, \a high, \a low, and \a close to
the current data.
Alternatively, you can also access and modify the data via the \ref data method, which returns a
pointer to the internal \ref QCPFinancialData.
\see removeData
*/
void QCPFinancial::addData(double key, double open, double high, double low, double close)
{
mData->insertMulti(key, QCPFinancialData(key, open, high, low, close));
}
/*! \overload
Adds the provided open/high/low/close data to the current data.
Alternatively, you can also access and modify the data via the \ref data method, which returns a
pointer to the internal \ref QCPFinancialData.
\see removeData
*/
void QCPFinancial::addData(const QVector<double> &key, const QVector<double> &open, const QVector<double> &high, const QVector<double> &low, const QVector<double> &close)
{
int n = key.size();
n = qMin(n, open.size());
n = qMin(n, high.size());
n = qMin(n, low.size());
n = qMin(n, close.size());
for (int i=0; i<n; ++i)
{
mData->insertMulti(key[i], QCPFinancialData(key[i], open[i], high[i], low[i], close[i]));
}
}
/*!
Removes all data points with keys smaller than \a key.
\see addData, clearData
*/
void QCPFinancial::removeDataBefore(double key)
{
QCPFinancialDataMap::iterator it = mData->begin();
while (it != mData->end() && it.key() < key)
it = mData->erase(it);
}
/*!
Removes all data points with keys greater than \a key.
\see addData, clearData
*/
void QCPFinancial::removeDataAfter(double key)
{
if (mData->isEmpty()) return;
QCPFinancialDataMap::iterator it = mData->upperBound(key);
while (it != mData->end())
it = mData->erase(it);
}
/*!
Removes all data points with keys between \a fromKey and \a toKey. if \a fromKey is greater or
equal to \a toKey, the function does nothing. To remove a single data point with known key, use
\ref removeData(double key).
\see addData, clearData
*/
void QCPFinancial::removeData(double fromKey, double toKey)
{
if (fromKey >= toKey || mData->isEmpty()) return;
QCPFinancialDataMap::iterator it = mData->upperBound(fromKey);
QCPFinancialDataMap::iterator itEnd = mData->upperBound(toKey);
while (it != itEnd)
it = mData->erase(it);
}
/*! \overload
Removes a single data point at \a key. If the position is not known with absolute precision,
consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval
around the suspected position, depeding on the precision with which the key is known.
\see addData, clearData
*/
void QCPFinancial::removeData(double key)
{
mData->remove(key);
}
/*!
Removes all data points.
\see removeData, removeDataAfter, removeDataBefore
*/
void QCPFinancial::clearData()
{
mData->clear();
}
/* inherits documentation from base class */
double QCPFinancial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
{
// get visible data range:
QCPFinancialDataMap::const_iterator lower, upper; // note that upper is the actual upper point, and not 1 step after the upper point
getVisibleDataBounds(lower, upper);
if (lower == mData->constEnd() || upper == mData->constEnd())
return -1;
// perform select test according to configured style:
switch (mChartStyle)
{
case QCPFinancial::csOhlc:
return ohlcSelectTest(pos, lower, upper+1); break;
case QCPFinancial::csCandlestick:
return candlestickSelectTest(pos, lower, upper+1); break;
}
}
return -1;
}
/*!
A convenience function that converts time series data (\a value against \a time) to OHLC binned
data points. The return value can then be passed on to \ref setData.
The size of the bins can be controlled with \a timeBinSize in the same units as \a time is given.
For example, if the unit of \a time is seconds and single OHLC/Candlesticks should span an hour
each, set \a timeBinSize to 3600.
\a timeBinOffset allows to control precisely at what \a time coordinate a bin should start. The
value passed as \a timeBinOffset doesn't need to be in the range encompassed by the \a time keys.
It merely defines the mathematical offset/phase of the bins that will be used to process the
data.
*/
QCPFinancialDataMap QCPFinancial::timeSeriesToOhlc(const QVector<double> &time, const QVector<double> &value, double timeBinSize, double timeBinOffset)
{
QCPFinancialDataMap map;
int count = qMin(time.size(), value.size());
if (count == 0)
return QCPFinancialDataMap();
QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first());
int currentBinIndex = qFloor((time.first()-timeBinOffset)/timeBinSize+0.5);
for (int i=0; i<count; ++i)
{
int index = qFloor((time.at(i)-timeBinOffset)/timeBinSize+0.5);
if (currentBinIndex == index) // data point still in current bin, extend high/low:
{
if (value.at(i) < currentBinData.low) currentBinData.low = value.at(i);
if (value.at(i) > currentBinData.high) currentBinData.high = value.at(i);
if (i == count-1) // last data point is in current bin, finalize bin:
{
currentBinData.close = value.at(i);
currentBinData.key = timeBinOffset+(index)*timeBinSize;
map.insert(currentBinData.key, currentBinData);
}
} else // data point not anymore in current bin, set close of old and open of new bin, and add old to map:
{
// finalize current bin:
currentBinData.close = value.at(i-1);
currentBinData.key = timeBinOffset+(index-1)*timeBinSize;
map.insert(currentBinData.key, currentBinData);
// start next bin:
currentBinIndex = index;
currentBinData.open = value.at(i);
currentBinData.high = value.at(i);
currentBinData.low = value.at(i);
}
}
return map;
}
/* inherits documentation from base class */
void QCPFinancial::draw(QCPPainter *painter)
{
// get visible data range:
QCPFinancialDataMap::const_iterator lower, upper; // note that upper is the actual upper point, and not 1 step after the upper point
getVisibleDataBounds(lower, upper);
if (lower == mData->constEnd() || upper == mData->constEnd())
return;
// draw visible data range according to configured style:
switch (mChartStyle)
{
case QCPFinancial::csOhlc:
drawOhlcPlot(painter, lower, upper+1); break;
case QCPFinancial::csCandlestick:
drawCandlestickPlot(painter, lower, upper+1); break;
}
}
/* inherits documentation from base class */
void QCPFinancial::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
{
painter->setAntialiasing(false); // legend icon especially of csCandlestick looks better without antialiasing
if (mChartStyle == csOhlc)
{
if (mTwoColored)
{
// draw upper left half icon with positive color:
painter->setBrush(mBrushPositive);
painter->setPen(mPenPositive);
painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint()));
painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
// draw bottom right hald icon with negative color:
painter->setBrush(mBrushNegative);
painter->setPen(mPenNegative);
painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint()));
painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
} else
{
painter->setBrush(mBrush);
painter->setPen(mPen);
painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
}
} else if (mChartStyle == csCandlestick)
{
if (mTwoColored)
{
// draw upper left half icon with positive color:
painter->setBrush(mBrushPositive);
painter->setPen(mPenPositive);
painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint()));
painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
// draw bottom right hald icon with negative color:
painter->setBrush(mBrushNegative);
painter->setPen(mPenNegative);
painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint()));
painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
} else
{
painter->setBrush(mBrush);
painter->setPen(mPen);
painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
}
}
}
/* inherits documentation from base class */
QCPRange QCPFinancial::getKeyRange(bool &foundRange, QCPAbstractPlottable::SignDomain inSignDomain) const
{
QCPRange range;
bool haveLower = false;
bool haveUpper = false;
double current;
QCPFinancialDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
current = it.value().key;
if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0))
{
if (current < range.lower || !haveLower)
{
range.lower = current;
haveLower = true;
}
if (current > range.upper || !haveUpper)
{
range.upper = current;
haveUpper = true;
}
}
++it;
}
// determine exact range by including width of bars/flags:
if (haveLower && mKeyAxis)
range.lower = range.lower-mWidth*0.5;
if (haveUpper && mKeyAxis)
range.upper = range.upper+mWidth*0.5;
foundRange = haveLower && haveUpper;
return range;
}
/* inherits documentation from base class */
QCPRange QCPFinancial::getValueRange(bool &foundRange, QCPAbstractPlottable::SignDomain inSignDomain) const
{
QCPRange range;
bool haveLower = false;
bool haveUpper = false;
QCPFinancialDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
// high:
if (inSignDomain == sdBoth || (inSignDomain == sdNegative && it.value().high < 0) || (inSignDomain == sdPositive && it.value().high > 0))
{
if (it.value().high < range.lower || !haveLower)
{
range.lower = it.value().high;
haveLower = true;
}
if (it.value().high > range.upper || !haveUpper)
{
range.upper = it.value().high;
haveUpper = true;
}
}
// low:
if (inSignDomain == sdBoth || (inSignDomain == sdNegative && it.value().low < 0) || (inSignDomain == sdPositive && it.value().low > 0))
{
if (it.value().low < range.lower || !haveLower)
{
range.lower = it.value().low;
haveLower = true;
}
if (it.value().low > range.upper || !haveUpper)
{
range.upper = it.value().low;
haveUpper = true;
}
}
++it;
}
foundRange = haveLower && haveUpper;
return range;
}
/*! \internal
Draws the data from \a begin to \a end as OHLC bars with the provided \a painter.
This method is a helper function for \ref draw. It is used when the chart style is \ref csOhlc.
*/
void QCPFinancial::drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end)
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
QPen linePen;
if (keyAxis->orientation() == Qt::Horizontal)
{
for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it)
{
if (mSelected)
linePen = mSelectedPen;
else if (mTwoColored)
linePen = it.value().close >= it.value().open ? mPenPositive : mPenNegative;
else
linePen = mPen;
painter->setPen(linePen);
double keyPixel = keyAxis->coordToPixel(it.value().key);
double openPixel = valueAxis->coordToPixel(it.value().open);
double closePixel = valueAxis->coordToPixel(it.value().close);
// draw backbone:
painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)));
// draw open:
double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); // sign of this makes sure open/close are on correct sides
painter->drawLine(QPointF(keyPixel-keyWidthPixels, openPixel), QPointF(keyPixel, openPixel));
// draw close:
painter->drawLine(QPointF(keyPixel, closePixel), QPointF(keyPixel+keyWidthPixels, closePixel));
}
} else
{
for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it)
{
if (mSelected)
linePen = mSelectedPen;
else if (mTwoColored)
linePen = it.value().close >= it.value().open ? mPenPositive : mPenNegative;
else
linePen = mPen;
painter->setPen(linePen);
double keyPixel = keyAxis->coordToPixel(it.value().key);
double openPixel = valueAxis->coordToPixel(it.value().open);
double closePixel = valueAxis->coordToPixel(it.value().close);
// draw backbone:
painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(it.value().low), keyPixel));
// draw open:
double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); // sign of this makes sure open/close are on correct sides
painter->drawLine(QPointF(openPixel, keyPixel-keyWidthPixels), QPointF(openPixel, keyPixel));
// draw close:
painter->drawLine(QPointF(closePixel, keyPixel), QPointF(closePixel, keyPixel+keyWidthPixels));
}
}
}
/*! \internal
Draws the data from \a begin to \a end as Candlesticks with the provided \a painter.
This method is a helper function for \ref draw. It is used when the chart style is \ref csCandlestick.
*/
void QCPFinancial::drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end)
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
QPen linePen;
QBrush boxBrush;
if (keyAxis->orientation() == Qt::Horizontal)
{
for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it)
{
if (mSelected)
{
linePen = mSelectedPen;
boxBrush = mSelectedBrush;
} else if (mTwoColored)
{
if (it.value().close >= it.value().open)
{
linePen = mPenPositive;
boxBrush = mBrushPositive;
} else
{
linePen = mPenNegative;
boxBrush = mBrushNegative;
}
} else
{
linePen = mPen;
boxBrush = mBrush;
}
painter->setPen(linePen);
painter->setBrush(boxBrush);
double keyPixel = keyAxis->coordToPixel(it.value().key);
double openPixel = valueAxis->coordToPixel(it.value().open);
double closePixel = valueAxis->coordToPixel(it.value().close);
// draw high:
painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it.value().open, it.value().close))));
// draw low:
painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it.value().open, it.value().close))));
// draw open-close box:
double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5);
painter->drawRect(QRectF(QPointF(keyPixel-keyWidthPixels, closePixel), QPointF(keyPixel+keyWidthPixels, openPixel)));
}
} else // keyAxis->orientation() == Qt::Vertical
{
for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it)
{
if (mSelected)
{
linePen = mSelectedPen;
boxBrush = mSelectedBrush;
} else if (mTwoColored)
{
if (it.value().close >= it.value().open)
{
linePen = mPenPositive;
boxBrush = mBrushPositive;
} else
{
linePen = mPenNegative;
boxBrush = mBrushNegative;
}
} else
{
linePen = mPen;
boxBrush = mBrush;
}
painter->setPen(linePen);
painter->setBrush(boxBrush);
double keyPixel = keyAxis->coordToPixel(it.value().key);
double openPixel = valueAxis->coordToPixel(it.value().open);
double closePixel = valueAxis->coordToPixel(it.value().close);
// draw high:
painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it.value().open, it.value().close)), keyPixel));
// draw low:
painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it.value().open, it.value().close)), keyPixel));
// draw open-close box:
double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5);
painter->drawRect(QRectF(QPointF(closePixel, keyPixel-keyWidthPixels), QPointF(openPixel, keyPixel+keyWidthPixels)));
}
}
}
/*! \internal
This method is a helper function for \ref selectTest. It is used to test for selection when the
chart style is \ref csOhlc. It only tests against the data points between \a begin and \a end.
*/
double QCPFinancial::ohlcSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
double minDistSqr = std::numeric_limits<double>::max();
QCPFinancialDataMap::const_iterator it;
if (keyAxis->orientation() == Qt::Horizontal)
{
for (it = begin; it != end; ++it)
{
double keyPixel = keyAxis->coordToPixel(it.value().key);
// calculate distance to backbone:
double currentDistSqr = distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), pos);
if (currentDistSqr < minDistSqr)
minDistSqr = currentDistSqr;
}
} else // keyAxis->orientation() == Qt::Vertical
{
for (it = begin; it != end; ++it)
{
double keyPixel = keyAxis->coordToPixel(it.value().key);
// calculate distance to backbone:
double currentDistSqr = distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), pos);
if (currentDistSqr < minDistSqr)
minDistSqr = currentDistSqr;
}
}
return qSqrt(minDistSqr);
}
/*! \internal
This method is a helper function for \ref selectTest. It is used to test for selection when the
chart style is \ref csCandlestick. It only tests against the data points between \a begin and \a
end.
*/
double QCPFinancial::candlestickSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
double minDistSqr = std::numeric_limits<double>::max();
QCPFinancialDataMap::const_iterator it;
if (keyAxis->orientation() == Qt::Horizontal)
{
for (it = begin; it != end; ++it)
{
double currentDistSqr;
// determine whether pos is in open-close-box:
QCPRange boxKeyRange(it.value().key-mWidth*0.5, it.value().key+mWidth*0.5);
QCPRange boxValueRange(it.value().close, it.value().open);
double posKey, posValue;
pixelsToCoords(pos, posKey, posValue);
if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box
{
currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
} else
{
// calculate distance to high/low lines:
double keyPixel = keyAxis->coordToPixel(it.value().key);
double highLineDistSqr = distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it.value().open, it.value().close))), pos);
double lowLineDistSqr = distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it.value().open, it.value().close))), pos);
currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr);
}
if (currentDistSqr < minDistSqr)
minDistSqr = currentDistSqr;
}
} else // keyAxis->orientation() == Qt::Vertical
{
for (it = begin; it != end; ++it)
{
double currentDistSqr;
// determine whether pos is in open-close-box:
QCPRange boxKeyRange(it.value().key-mWidth*0.5, it.value().key+mWidth*0.5);
QCPRange boxValueRange(it.value().close, it.value().open);
double posKey, posValue;
pixelsToCoords(pos, posKey, posValue);
if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box
{
currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
} else
{
// calculate distance to high/low lines:
double keyPixel = keyAxis->coordToPixel(it.value().key);
double highLineDistSqr = distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it.value().open, it.value().close)), keyPixel), pos);
double lowLineDistSqr = distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it.value().open, it.value().close)), keyPixel), pos);
currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr);
}
if (currentDistSqr < minDistSqr)
minDistSqr = currentDistSqr;
}
}
return qSqrt(minDistSqr);
}
/*! \internal
called by the drawing methods to determine which data (key) range is visible at the current key
axis range setting, so only that needs to be processed.
\a lower returns an iterator to the lowest data point that needs to be taken into account when
plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
lower may still be just outside the visible range.
\a upper returns an iterator to the highest data point. Same as before, \a upper may also lie
just outside of the visible range.
if the plottable contains no data, both \a lower and \a upper point to constEnd.
\see QCPGraph::getVisibleDataBounds
*/
void QCPFinancial::getVisibleDataBounds(QCPFinancialDataMap::const_iterator &lower, QCPFinancialDataMap::const_iterator &upper) const
{
if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
if (mData->isEmpty())
{
lower = mData->constEnd();
upper = mData->constEnd();
return;
}
// get visible data range as QMap iterators
QCPFinancialDataMap::const_iterator lbound = mData->lowerBound(mKeyAxis.data()->range().lower);
QCPFinancialDataMap::const_iterator ubound = mData->upperBound(mKeyAxis.data()->range().upper);
bool lowoutlier = lbound != mData->constBegin(); // indicates whether there exist points below axis range
bool highoutlier = ubound != mData->constEnd(); // indicates whether there exist points above axis range
lower = (lowoutlier ? lbound-1 : lbound); // data point range that will be actually drawn
upper = (highoutlier ? ubound : ubound-1); // data point range that will be actually drawn
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemStraightLine
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemStraightLine
\brief A straight line that spans infinitely in both directions
\image html QCPItemStraightLine.png "Straight line example. Blue dotted circles are anchors, solid blue discs are positions."
It has two positions, \a point1 and \a point2, which define the straight line.
*/
/*!
Creates a straight line item and sets default values.
The constructed item can be added to the plot with QCustomPlot::addItem.
*/
QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
point1(createPosition(QLatin1String("point1"))),
point2(createPosition(QLatin1String("point2")))
{
point1->setCoords(0, 0);
point2->setCoords(1, 1);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue,2));
}
QCPItemStraightLine::~QCPItemStraightLine()
{
}
/*!
Sets the pen that will be used to draw the line
\see setSelectedPen
*/
void QCPItemStraightLine::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the line when selected
\see setPen, setSelected
*/
void QCPItemStraightLine::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/* inherits documentation from base class */
double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
return distToStraightLine(QVector2D(point1->pixelPoint()), QVector2D(point2->pixelPoint()-point1->pixelPoint()), QVector2D(pos));
}
/* inherits documentation from base class */
void QCPItemStraightLine::draw(QCPPainter *painter)
{
QVector2D start(point1->pixelPoint());
QVector2D end(point2->pixelPoint());
// get visible segment of straight line inside clipRect:
double clipPad = mainPen().widthF();
QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
// paint visible segment, if existent:
if (!line.isNull())
{
painter->setPen(mainPen());
painter->drawLine(line);
}
}
/*! \internal
finds the shortest distance of \a point to the straight line defined by the base point \a
base and the direction vector \a vec.
This is a helper function for \ref selectTest.
*/
double QCPItemStraightLine::distToStraightLine(const QVector2D &base, const QVector2D &vec, const QVector2D &point) const
{
return qAbs((base.y()-point.y())*vec.x()-(base.x()-point.x())*vec.y())/vec.length();
}
/*! \internal
Returns the section of the straight line defined by \a base and direction vector \a
vec, that is visible in the specified \a rect.
This is a helper function for \ref draw.
*/
QLineF QCPItemStraightLine::getRectClippedStraightLine(const QVector2D &base, const QVector2D &vec, const QRect &rect) const
{
double bx, by;
double gamma;
QLineF result;
if (vec.x() == 0 && vec.y() == 0)
return result;
if (qFuzzyIsNull(vec.x())) // line is vertical
{
// check top of rect:
bx = rect.left();
by = rect.top();
gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
if (gamma >= 0 && gamma <= rect.width())
result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical
} else if (qFuzzyIsNull(vec.y())) // line is horizontal
{
// check left of rect:
bx = rect.left();
by = rect.top();
gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
if (gamma >= 0 && gamma <= rect.height())
result.setLine(rect.left(), by+gamma, rect.right(), by+gamma); // no need to check right because we know line is horizontal
} else // line is skewed
{
QList<QVector2D> pointVectors;
// check top of rect:
bx = rect.left();
by = rect.top();
gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
if (gamma >= 0 && gamma <= rect.width())
pointVectors.append(QVector2D(bx+gamma, by));
// check bottom of rect:
bx = rect.left();
by = rect.bottom();
gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
if (gamma >= 0 && gamma <= rect.width())
pointVectors.append(QVector2D(bx+gamma, by));
// check left of rect:
bx = rect.left();
by = rect.top();
gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
if (gamma >= 0 && gamma <= rect.height())
pointVectors.append(QVector2D(bx, by+gamma));
// check right of rect:
bx = rect.right();
by = rect.top();
gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
if (gamma >= 0 && gamma <= rect.height())
pointVectors.append(QVector2D(bx, by+gamma));
// evaluate points:
if (pointVectors.size() == 2)
{
result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
} else if (pointVectors.size() > 2)
{
// line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
double distSqrMax = 0;
QVector2D pv1, pv2;
for (int i=0; i<pointVectors.size()-1; ++i)
{
for (int k=i+1; k<pointVectors.size(); ++k)
{
double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
if (distSqr > distSqrMax)
{
pv1 = pointVectors.at(i);
pv2 = pointVectors.at(k);
distSqrMax = distSqr;
}
}
}
result.setPoints(pv1.toPointF(), pv2.toPointF());
}
}
return result;
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the
item is not selected and mSelectedPen when it is.
*/
QPen QCPItemStraightLine::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemLine
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemLine
\brief A line from one point to another
\image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions."
It has two positions, \a start and \a end, which define the end points of the line.
With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow.
*/
/*!
Creates a line item and sets default values.
The constructed item can be added to the plot with QCustomPlot::addItem.
*/
QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
start(createPosition(QLatin1String("start"))),
end(createPosition(QLatin1String("end")))
{
start->setCoords(0, 0);
end->setCoords(1, 1);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue,2));
}
QCPItemLine::~QCPItemLine()
{
}
/*!
Sets the pen that will be used to draw the line
\see setSelectedPen
*/
void QCPItemLine::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the line when selected
\see setPen, setSelected
*/
void QCPItemLine::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the line ending style of the head. The head corresponds to the \a end position.
Note that due to the overloaded QCPLineEnding constructor, you may directly specify
a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
\see setTail
*/
void QCPItemLine::setHead(const QCPLineEnding &head)
{
mHead = head;
}
/*!
Sets the line ending style of the tail. The tail corresponds to the \a start position.
Note that due to the overloaded QCPLineEnding constructor, you may directly specify
a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
\see setHead
*/
void QCPItemLine::setTail(const QCPLineEnding &tail)
{
mTail = tail;
}
/* inherits documentation from base class */
double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
return qSqrt(distSqrToLine(start->pixelPoint(), end->pixelPoint(), pos));
}
/* inherits documentation from base class */
void QCPItemLine::draw(QCPPainter *painter)
{
QVector2D startVec(start->pixelPoint());
QVector2D endVec(end->pixelPoint());
if (startVec.toPoint() == endVec.toPoint())
return;
// get visible segment of straight line inside clipRect:
double clipPad = qMax(mHead.boundingDistance(), mTail.boundingDistance());
clipPad = qMax(clipPad, (double)mainPen().widthF());
QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
// paint visible segment, if existent:
if (!line.isNull())
{
painter->setPen(mainPen());
painter->drawLine(line);
painter->setBrush(Qt::SolidPattern);
if (mTail.style() != QCPLineEnding::esNone)
mTail.draw(painter, startVec, startVec-endVec);
if (mHead.style() != QCPLineEnding::esNone)
mHead.draw(painter, endVec, endVec-startVec);
}
}
/*! \internal
Returns the section of the line defined by \a start and \a end, that is visible in the specified
\a rect.
This is a helper function for \ref draw.
*/
QLineF QCPItemLine::getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const
{
bool containsStart = rect.contains(start.x(), start.y());
bool containsEnd = rect.contains(end.x(), end.y());
if (containsStart && containsEnd)
return QLineF(start.toPointF(), end.toPointF());
QVector2D base = start;
QVector2D vec = end-start;
double bx, by;
double gamma, mu;
QLineF result;
QList<QVector2D> pointVectors;
if (!qFuzzyIsNull(vec.y())) // line is not horizontal
{
// check top of rect:
bx = rect.left();
by = rect.top();
mu = (by-base.y())/vec.y();
if (mu >= 0 && mu <= 1)
{
gamma = base.x()-bx + mu*vec.x();
if (gamma >= 0 && gamma <= rect.width())
pointVectors.append(QVector2D(bx+gamma, by));
}
// check bottom of rect:
bx = rect.left();
by = rect.bottom();
mu = (by-base.y())/vec.y();
if (mu >= 0 && mu <= 1)
{
gamma = base.x()-bx + mu*vec.x();
if (gamma >= 0 && gamma <= rect.width())
pointVectors.append(QVector2D(bx+gamma, by));
}
}
if (!qFuzzyIsNull(vec.x())) // line is not vertical
{
// check left of rect:
bx = rect.left();
by = rect.top();
mu = (bx-base.x())/vec.x();
if (mu >= 0 && mu <= 1)
{
gamma = base.y()-by + mu*vec.y();
if (gamma >= 0 && gamma <= rect.height())
pointVectors.append(QVector2D(bx, by+gamma));
}
// check right of rect:
bx = rect.right();
by = rect.top();
mu = (bx-base.x())/vec.x();
if (mu >= 0 && mu <= 1)
{
gamma = base.y()-by + mu*vec.y();
if (gamma >= 0 && gamma <= rect.height())
pointVectors.append(QVector2D(bx, by+gamma));
}
}
if (containsStart)
pointVectors.append(start);
if (containsEnd)
pointVectors.append(end);
// evaluate points:
if (pointVectors.size() == 2)
{
result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
} else if (pointVectors.size() > 2)
{
// line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
double distSqrMax = 0;
QVector2D pv1, pv2;
for (int i=0; i<pointVectors.size()-1; ++i)
{
for (int k=i+1; k<pointVectors.size(); ++k)
{
double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
if (distSqr > distSqrMax)
{
pv1 = pointVectors.at(i);
pv2 = pointVectors.at(k);
distSqrMax = distSqr;
}
}
}
result.setPoints(pv1.toPointF(), pv2.toPointF());
}
return result;
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the
item is not selected and mSelectedPen when it is.
*/
QPen QCPItemLine::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemCurve
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemCurve
\brief A curved line from one point to another
\image html QCPItemCurve.png "Curve example. Blue dotted circles are anchors, solid blue discs are positions."
It has four positions, \a start and \a end, which define the end points of the line, and two
control points which define the direction the line exits from the start and the direction from
which it approaches the end: \a startDir and \a endDir.
With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an
arrow.
Often it is desirable for the control points to stay at fixed relative positions to the start/end
point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start,
and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir.
*/
/*!
Creates a curve item and sets default values.
The constructed item can be added to the plot with QCustomPlot::addItem.
*/
QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
start(createPosition(QLatin1String("start"))),
startDir(createPosition(QLatin1String("startDir"))),
endDir(createPosition(QLatin1String("endDir"))),
end(createPosition(QLatin1String("end")))
{
start->setCoords(0, 0);
startDir->setCoords(0.5, 0);
endDir->setCoords(0, 0.5);
end->setCoords(1, 1);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue,2));
}
QCPItemCurve::~QCPItemCurve()
{
}
/*!
Sets the pen that will be used to draw the line
\see setSelectedPen
*/
void QCPItemCurve::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the line when selected
\see setPen, setSelected
*/
void QCPItemCurve::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the line ending style of the head. The head corresponds to the \a end position.
Note that due to the overloaded QCPLineEnding constructor, you may directly specify
a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
\see setTail
*/
void QCPItemCurve::setHead(const QCPLineEnding &head)
{
mHead = head;
}
/*!
Sets the line ending style of the tail. The tail corresponds to the \a start position.
Note that due to the overloaded QCPLineEnding constructor, you may directly specify
a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
\see setHead
*/
void QCPItemCurve::setTail(const QCPLineEnding &tail)
{
mTail = tail;
}
/* inherits documentation from base class */
double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
QPointF startVec(start->pixelPoint());
QPointF startDirVec(startDir->pixelPoint());
QPointF endDirVec(endDir->pixelPoint());
QPointF endVec(end->pixelPoint());
QPainterPath cubicPath(startVec);
cubicPath.cubicTo(startDirVec, endDirVec, endVec);
QPolygonF polygon = cubicPath.toSubpathPolygons().first();
double minDistSqr = std::numeric_limits<double>::max();
for (int i=1; i<polygon.size(); ++i)
{
double distSqr = distSqrToLine(polygon.at(i-1), polygon.at(i), pos);
if (distSqr < minDistSqr)
minDistSqr = distSqr;
}
return qSqrt(minDistSqr);
}
/* inherits documentation from base class */
void QCPItemCurve::draw(QCPPainter *painter)
{
QPointF startVec(start->pixelPoint());
QPointF startDirVec(startDir->pixelPoint());
QPointF endDirVec(endDir->pixelPoint());
QPointF endVec(end->pixelPoint());
if (QVector2D(endVec-startVec).length() > 1e10f) // too large curves cause crash
return;
QPainterPath cubicPath(startVec);
cubicPath.cubicTo(startDirVec, endDirVec, endVec);
// paint visible segment, if existent:
QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
QRect cubicRect = cubicPath.controlPointRect().toRect();
if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position
cubicRect.adjust(0, 0, 1, 1);
if (clip.intersects(cubicRect))
{
painter->setPen(mainPen());
painter->drawPath(cubicPath);
painter->setBrush(Qt::SolidPattern);
if (mTail.style() != QCPLineEnding::esNone)
mTail.draw(painter, QVector2D(startVec), M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI);
if (mHead.style() != QCPLineEnding::esNone)
mHead.draw(painter, QVector2D(endVec), -cubicPath.angleAtPercent(1)/180.0*M_PI);
}
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the
item is not selected and mSelectedPen when it is.
*/
QPen QCPItemCurve::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemRect
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemRect
\brief A rectangle
\image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs are positions."
It has two positions, \a topLeft and \a bottomRight, which define the rectangle.
*/
/*!
Creates a rectangle item and sets default values.
The constructed item can be added to the plot with QCustomPlot::addItem.
*/
QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
topLeft(createPosition(QLatin1String("topLeft"))),
bottomRight(createPosition(QLatin1String("bottomRight"))),
top(createAnchor(QLatin1String("top"), aiTop)),
topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
right(createAnchor(QLatin1String("right"), aiRight)),
bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
left(createAnchor(QLatin1String("left"), aiLeft))
{
topLeft->setCoords(0, 1);
bottomRight->setCoords(1, 0);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue,2));
setBrush(Qt::NoBrush);
setSelectedBrush(Qt::NoBrush);
}
QCPItemRect::~QCPItemRect()
{
}
/*!
Sets the pen that will be used to draw the line of the rectangle
\see setSelectedPen, setBrush
*/
void QCPItemRect::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the line of the rectangle when selected
\see setPen, setSelected
*/
void QCPItemRect::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to
Qt::NoBrush.
\see setSelectedBrush, setPen
*/
void QCPItemRect::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a
brush to Qt::NoBrush.
\see setBrush
*/
void QCPItemRect::setSelectedBrush(const QBrush &brush)
{
mSelectedBrush = brush;
}
/* inherits documentation from base class */
double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()).normalized();
bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
return rectSelectTest(rect, pos, filledRect);
}
/* inherits documentation from base class */
void QCPItemRect::draw(QCPPainter *painter)
{
QPointF p1 = topLeft->pixelPoint();
QPointF p2 = bottomRight->pixelPoint();
if (p1.toPoint() == p2.toPoint())
return;
QRectF rect = QRectF(p1, p2).normalized();
double clipPad = mainPen().widthF();
QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect
{
painter->setPen(mainPen());
painter->setBrush(mainBrush());
painter->drawRect(rect);
}
}
/* inherits documentation from base class */
QPointF QCPItemRect::anchorPixelPoint(int anchorId) const
{
QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint());
switch (anchorId)
{
case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
case aiTopRight: return rect.topRight();
case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
case aiBottomLeft: return rect.bottomLeft();
case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
}
qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
return QPointF();
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
and mSelectedPen when it is.
*/
QPen QCPItemRect::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
/*! \internal
Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
is not selected and mSelectedBrush when it is.
*/
QBrush QCPItemRect::mainBrush() const
{
return mSelected ? mSelectedBrush : mBrush;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemText
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemText
\brief A text label
\image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are positions."
Its position is defined by the member \a position and the setting of \ref setPositionAlignment.
The latter controls which part of the text rect shall be aligned with \a position.
The text alignment itself (i.e. left, center, right) can be controlled with \ref
setTextAlignment.
The text may be rotated around the \a position point with \ref setRotation.
*/
/*!
Creates a text item and sets default values.
The constructed item can be added to the plot with QCustomPlot::addItem.
*/
QCPItemText::QCPItemText(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
position(createPosition(QLatin1String("position"))),
topLeft(createAnchor(QLatin1String("topLeft"), aiTopLeft)),
top(createAnchor(QLatin1String("top"), aiTop)),
topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
right(createAnchor(QLatin1String("right"), aiRight)),
bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight)),
bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
left(createAnchor(QLatin1String("left"), aiLeft))
{
position->setCoords(0, 0);
setRotation(0);
setTextAlignment(Qt::AlignTop|Qt::AlignHCenter);
setPositionAlignment(Qt::AlignCenter);
setText(QLatin1String("text"));
setPen(Qt::NoPen);
setSelectedPen(Qt::NoPen);
setBrush(Qt::NoBrush);
setSelectedBrush(Qt::NoBrush);
setColor(Qt::black);
setSelectedColor(Qt::blue);
}
QCPItemText::~QCPItemText()
{
}
/*!
Sets the color of the text.
*/
void QCPItemText::setColor(const QColor &color)
{
mColor = color;
}
/*!
Sets the color of the text that will be used when the item is selected.
*/
void QCPItemText::setSelectedColor(const QColor &color)
{
mSelectedColor = color;
}
/*!
Sets the pen that will be used do draw a rectangular border around the text. To disable the
border, set \a pen to Qt::NoPen.
\see setSelectedPen, setBrush, setPadding
*/
void QCPItemText::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used do draw a rectangular border around the text, when the item is
selected. To disable the border, set \a pen to Qt::NoPen.
\see setPen
*/
void QCPItemText::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the brush that will be used do fill the background of the text. To disable the
background, set \a brush to Qt::NoBrush.
\see setSelectedBrush, setPen, setPadding
*/
void QCPItemText::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the
background, set \a brush to Qt::NoBrush.
\see setBrush
*/
void QCPItemText::setSelectedBrush(const QBrush &brush)
{
mSelectedBrush = brush;
}
/*!
Sets the font of the text.
\see setSelectedFont, setColor
*/
void QCPItemText::setFont(const QFont &font)
{
mFont = font;
}
/*!
Sets the font of the text that will be used when the item is selected.
\see setFont
*/
void QCPItemText::setSelectedFont(const QFont &font)
{
mSelectedFont = font;
}
/*!
Sets the text that will be displayed. Multi-line texts are supported by inserting a line break
character, e.g. '\n'.
\see setFont, setColor, setTextAlignment
*/
void QCPItemText::setText(const QString &text)
{
mText = text;
}
/*!
Sets which point of the text rect shall be aligned with \a position.
Examples:
\li If \a alignment is <tt>Qt::AlignHCenter | Qt::AlignTop</tt>, the text will be positioned such
that the top of the text rect will be horizontally centered on \a position.
\li If \a alignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt>, \a position will indicate the
bottom left corner of the text rect.
If you want to control the alignment of (multi-lined) text within the text rect, use \ref
setTextAlignment.
*/
void QCPItemText::setPositionAlignment(Qt::Alignment alignment)
{
mPositionAlignment = alignment;
}
/*!
Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft, Qt::AlignCenter or Qt::AlignRight).
*/
void QCPItemText::setTextAlignment(Qt::Alignment alignment)
{
mTextAlignment = alignment;
}
/*!
Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated
around \a position.
*/
void QCPItemText::setRotation(double degrees)
{
mRotation = degrees;
}
/*!
Sets the distance between the border of the text rectangle and the text. The appearance (and
visibility) of the text rectangle can be controlled with \ref setPen and \ref setBrush.
*/
void QCPItemText::setPadding(const QMargins &padding)
{
mPadding = padding;
}
/* inherits documentation from base class */
double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
// The rect may be rotated, so we transform the actual clicked pos to the rotated
// coordinate system, so we can use the normal rectSelectTest function for non-rotated rects:
QPointF positionPixels(position->pixelPoint());
QTransform inputTransform;
inputTransform.translate(positionPixels.x(), positionPixels.y());
inputTransform.rotate(-mRotation);
inputTransform.translate(-positionPixels.x(), -positionPixels.y());
QPointF rotatedPos = inputTransform.map(pos);
QFontMetrics fontMetrics(mFont);
QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment);
textBoxRect.moveTopLeft(textPos.toPoint());
return rectSelectTest(textBoxRect, rotatedPos, true);
}
/* inherits documentation from base class */
void QCPItemText::draw(QCPPainter *painter)
{
QPointF pos(position->pixelPoint());
QTransform transform = painter->transform();
transform.translate(pos.x(), pos.y());
if (!qFuzzyIsNull(mRotation))
transform.rotate(mRotation);
painter->setFont(mainFont());
QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top()));
textBoxRect.moveTopLeft(textPos.toPoint());
double clipPad = mainPen().widthF();
QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect())))
{
painter->setTransform(transform);
if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) ||
(mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0))
{
painter->setPen(mainPen());
painter->setBrush(mainBrush());
painter->drawRect(textBoxRect);
}
painter->setBrush(Qt::NoBrush);
painter->setPen(QPen(mainColor()));
painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText);
}
}
/* inherits documentation from base class */
QPointF QCPItemText::anchorPixelPoint(int anchorId) const
{
// get actual rect points (pretty much copied from draw function):
QPointF pos(position->pixelPoint());
QTransform transform;
transform.translate(pos.x(), pos.y());
if (!qFuzzyIsNull(mRotation))
transform.rotate(mRotation);
QFontMetrics fontMetrics(mainFont());
QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
textBoxRect.moveTopLeft(textPos.toPoint());
QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect));
switch (anchorId)
{
case aiTopLeft: return rectPoly.at(0);
case aiTop: return (rectPoly.at(0)+rectPoly.at(1))*0.5;
case aiTopRight: return rectPoly.at(1);
case aiRight: return (rectPoly.at(1)+rectPoly.at(2))*0.5;
case aiBottomRight: return rectPoly.at(2);
case aiBottom: return (rectPoly.at(2)+rectPoly.at(3))*0.5;
case aiBottomLeft: return rectPoly.at(3);
case aiLeft: return (rectPoly.at(3)+rectPoly.at(0))*0.5;
}
qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
return QPointF();
}
/*! \internal
Returns the point that must be given to the QPainter::drawText function (which expects the top
left point of the text rect), according to the position \a pos, the text bounding box \a rect and
the requested \a positionAlignment.
For example, if \a positionAlignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt> the returned point
will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally
drawn at that point, the lower left corner of the resulting text rect is at \a pos.
*/
QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const
{
if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop))
return pos;
QPointF result = pos; // start at top left
if (positionAlignment.testFlag(Qt::AlignHCenter))
result.rx() -= rect.width()/2.0;
else if (positionAlignment.testFlag(Qt::AlignRight))
result.rx() -= rect.width();
if (positionAlignment.testFlag(Qt::AlignVCenter))
result.ry() -= rect.height()/2.0;
else if (positionAlignment.testFlag(Qt::AlignBottom))
result.ry() -= rect.height();
return result;
}
/*! \internal
Returns the font that should be used for drawing text. Returns mFont when the item is not selected
and mSelectedFont when it is.
*/
QFont QCPItemText::mainFont() const
{
return mSelected ? mSelectedFont : mFont;
}
/*! \internal
Returns the color that should be used for drawing text. Returns mColor when the item is not
selected and mSelectedColor when it is.
*/
QColor QCPItemText::mainColor() const
{
return mSelected ? mSelectedColor : mColor;
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
and mSelectedPen when it is.
*/
QPen QCPItemText::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
/*! \internal
Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
is not selected and mSelectedBrush when it is.
*/
QBrush QCPItemText::mainBrush() const
{
return mSelected ? mSelectedBrush : mBrush;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemEllipse
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemEllipse
\brief An ellipse
\image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs are positions."
It has two positions, \a topLeft and \a bottomRight, which define the rect the ellipse will be drawn in.
*/
/*!
Creates an ellipse item and sets default values.
The constructed item can be added to the plot with QCustomPlot::addItem.
*/
QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
topLeft(createPosition(QLatin1String("topLeft"))),
bottomRight(createPosition(QLatin1String("bottomRight"))),
topLeftRim(createAnchor(QLatin1String("topLeftRim"), aiTopLeftRim)),
top(createAnchor(QLatin1String("top"), aiTop)),
topRightRim(createAnchor(QLatin1String("topRightRim"), aiTopRightRim)),
right(createAnchor(QLatin1String("right"), aiRight)),
bottomRightRim(createAnchor(QLatin1String("bottomRightRim"), aiBottomRightRim)),
bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
bottomLeftRim(createAnchor(QLatin1String("bottomLeftRim"), aiBottomLeftRim)),
left(createAnchor(QLatin1String("left"), aiLeft)),
center(createAnchor(QLatin1String("center"), aiCenter))
{
topLeft->setCoords(0, 1);
bottomRight->setCoords(1, 0);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue, 2));
setBrush(Qt::NoBrush);
setSelectedBrush(Qt::NoBrush);
}
QCPItemEllipse::~QCPItemEllipse()
{
}
/*!
Sets the pen that will be used to draw the line of the ellipse
\see setSelectedPen, setBrush
*/
void QCPItemEllipse::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the line of the ellipse when selected
\see setPen, setSelected
*/
void QCPItemEllipse::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to
Qt::NoBrush.
\see setSelectedBrush, setPen
*/
void QCPItemEllipse::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a
brush to Qt::NoBrush.
\see setBrush
*/
void QCPItemEllipse::setSelectedBrush(const QBrush &brush)
{
mSelectedBrush = brush;
}
/* inherits documentation from base class */
double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
double result = -1;
QPointF p1 = topLeft->pixelPoint();
QPointF p2 = bottomRight->pixelPoint();
QPointF center((p1+p2)/2.0);
double a = qAbs(p1.x()-p2.x())/2.0;
double b = qAbs(p1.y()-p2.y())/2.0;
double x = pos.x()-center.x();
double y = pos.y()-center.y();
// distance to border:
double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b));
result = qAbs(c-1)*qSqrt(x*x+y*y);
// filled ellipse, allow click inside to count as hit:
if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
{
if (x*x/(a*a) + y*y/(b*b) <= 1)
result = mParentPlot->selectionTolerance()*0.99;
}
return result;
}
/* inherits documentation from base class */
void QCPItemEllipse::draw(QCPPainter *painter)
{
QPointF p1 = topLeft->pixelPoint();
QPointF p2 = bottomRight->pixelPoint();
if (p1.toPoint() == p2.toPoint())
return;
QRectF ellipseRect = QRectF(p1, p2).normalized();
QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect
{
painter->setPen(mainPen());
painter->setBrush(mainBrush());
#ifdef __EXCEPTIONS
try // drawEllipse sometimes throws exceptions if ellipse is too big
{
#endif
painter->drawEllipse(ellipseRect);
#ifdef __EXCEPTIONS
} catch (...)
{
qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible";
setVisible(false);
}
#endif
}
}
/* inherits documentation from base class */
QPointF QCPItemEllipse::anchorPixelPoint(int anchorId) const
{
QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint());
switch (anchorId)
{
case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2);
case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
case aiTopRightRim: return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2);
case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2);
case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
case aiBottomLeftRim: return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2);
case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
case aiCenter: return (rect.topLeft()+rect.bottomRight())*0.5;
}
qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
return QPointF();
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
and mSelectedPen when it is.
*/
QPen QCPItemEllipse::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
/*! \internal
Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
is not selected and mSelectedBrush when it is.
*/
QBrush QCPItemEllipse::mainBrush() const
{
return mSelected ? mSelectedBrush : mBrush;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemPixmap
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemPixmap
\brief An arbitrary pixmap
\image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs are positions."
It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will
be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to
fit the rectangle or be drawn aligned to the topLeft position.
If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown
on the right side of the example image), the pixmap will be flipped in the respective
orientations.
*/
/*!
Creates a rectangle item and sets default values.
The constructed item can be added to the plot with QCustomPlot::addItem.
*/
QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
topLeft(createPosition(QLatin1String("topLeft"))),
bottomRight(createPosition(QLatin1String("bottomRight"))),
top(createAnchor(QLatin1String("top"), aiTop)),
topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
right(createAnchor(QLatin1String("right"), aiRight)),
bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
left(createAnchor(QLatin1String("left"), aiLeft)),
mScaledPixmapInvalidated(true)
{
topLeft->setCoords(0, 1);
bottomRight->setCoords(1, 0);
setPen(Qt::NoPen);
setSelectedPen(QPen(Qt::blue));
setScaled(false, Qt::KeepAspectRatio, Qt::SmoothTransformation);
}
QCPItemPixmap::~QCPItemPixmap()
{
}
/*!
Sets the pixmap that will be displayed.
*/
void QCPItemPixmap::setPixmap(const QPixmap &pixmap)
{
mPixmap = pixmap;
mScaledPixmapInvalidated = true;
if (mPixmap.isNull())
qDebug() << Q_FUNC_INFO << "pixmap is null";
}
/*!
Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a
bottomRight positions.
*/
void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformationMode)
{
mScaled = scaled;
mAspectRatioMode = aspectRatioMode;
mTransformationMode = transformationMode;
mScaledPixmapInvalidated = true;
}
/*!
Sets the pen that will be used to draw a border around the pixmap.
\see setSelectedPen, setBrush
*/
void QCPItemPixmap::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw a border around the pixmap when selected
\see setPen, setSelected
*/
void QCPItemPixmap::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/* inherits documentation from base class */
double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
return rectSelectTest(getFinalRect(), pos, true);
}
/* inherits documentation from base class */
void QCPItemPixmap::draw(QCPPainter *painter)
{
bool flipHorz = false;
bool flipVert = false;
QRect rect = getFinalRect(&flipHorz, &flipVert);
double clipPad = mainPen().style() == Qt::NoPen ? 0 : mainPen().widthF();
QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
if (boundingRect.intersects(clipRect()))
{
updateScaledPixmap(rect, flipHorz, flipVert);
painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap);
QPen pen = mainPen();
if (pen.style() != Qt::NoPen)
{
painter->setPen(pen);
painter->setBrush(Qt::NoBrush);
painter->drawRect(rect);
}
}
}
/* inherits documentation from base class */
QPointF QCPItemPixmap::anchorPixelPoint(int anchorId) const
{
bool flipHorz;
bool flipVert;
QRect rect = getFinalRect(&flipHorz, &flipVert);
// we actually want denormal rects (negative width/height) here, so restore
// the flipped state:
if (flipHorz)
rect.adjust(rect.width(), 0, -rect.width(), 0);
if (flipVert)
rect.adjust(0, rect.height(), 0, -rect.height());
switch (anchorId)
{
case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
case aiTopRight: return rect.topRight();
case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
case aiBottomLeft: return rect.bottomLeft();
case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;;
}
qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
return QPointF();
}
/*! \internal
Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The
parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped
horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a
bottomRight.)
This function only creates the scaled pixmap when the buffered pixmap has a different size than
the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does
not cause expensive rescaling every time.
If scaling is disabled, sets mScaledPixmap to a null QPixmap.
*/
void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert)
{
if (mPixmap.isNull())
return;
if (mScaled)
{
if (finalRect.isNull())
finalRect = getFinalRect(&flipHorz, &flipVert);
if (mScaledPixmapInvalidated || finalRect.size() != mScaledPixmap.size())
{
mScaledPixmap = mPixmap.scaled(finalRect.size(), mAspectRatioMode, mTransformationMode);
if (flipHorz || flipVert)
mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert));
}
} else if (!mScaledPixmap.isNull())
mScaledPixmap = QPixmap();
mScaledPixmapInvalidated = false;
}
/*! \internal
Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions
and scaling settings.
The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn
flipped horizontally or vertically in the returned rect. (The returned rect itself is always
normalized, i.e. the top left corner of the rect is actually further to the top/left than the
bottom right corner). This is the case when the item position \a topLeft is further to the
bottom/right than \a bottomRight.
If scaling is disabled, returns a rect with size of the original pixmap and the top left corner
aligned with the item position \a topLeft. The position \a bottomRight is ignored.
*/
QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const
{
QRect result;
bool flipHorz = false;
bool flipVert = false;
QPoint p1 = topLeft->pixelPoint().toPoint();
QPoint p2 = bottomRight->pixelPoint().toPoint();
if (p1 == p2)
return QRect(p1, QSize(0, 0));
if (mScaled)
{
QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y());
QPoint topLeft = p1;
if (newSize.width() < 0)
{
flipHorz = true;
newSize.rwidth() *= -1;
topLeft.setX(p2.x());
}
if (newSize.height() < 0)
{
flipVert = true;
newSize.rheight() *= -1;
topLeft.setY(p2.y());
}
QSize scaledSize = mPixmap.size();
scaledSize.scale(newSize, mAspectRatioMode);
result = QRect(topLeft, scaledSize);
} else
{
result = QRect(p1, mPixmap.size());
}
if (flippedHorz)
*flippedHorz = flipHorz;
if (flippedVert)
*flippedVert = flipVert;
return result;
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
and mSelectedPen when it is.
*/
QPen QCPItemPixmap::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemTracer
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemTracer
\brief Item that sticks to QCPGraph data points
\image html QCPItemTracer.png "Tracer example. Blue dotted circles are anchors, solid blue discs are positions."
The tracer can be connected with a QCPGraph via \ref setGraph. Then it will automatically adopt
the coordinate axes of the graph and update its \a position to be on the graph's data. This means
the key stays controllable via \ref setGraphKey, but the value will follow the graph data. If a
QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a
position will have no effect because they will be overriden in the next redraw (this is when the
coordinate update happens).
If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will
stay at the corresponding end of the graph.
With \ref setInterpolating you may specify whether the tracer may only stay exactly on data
points or whether it interpolates data points linearly, if given a key that lies between two data
points of the graph.
The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer
have no own visual appearance (set the style to \ref tsNone), and just connect other item
positions to the tracer \a position (used as an anchor) via \ref
QCPItemPosition::setParentAnchor.
\note The tracer position is only automatically updated upon redraws. So when the data of the
graph changes and immediately afterwards (without a redraw) the a position coordinates of the
tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref
updatePosition must be called manually, prior to reading the tracer coordinates.
*/
/*!
Creates a tracer item and sets default values.
The constructed item can be added to the plot with QCustomPlot::addItem.
*/
QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
position(createPosition(QLatin1String("position"))),
mGraph(0)
{
position->setCoords(0, 0);
setBrush(Qt::NoBrush);
setSelectedBrush(Qt::NoBrush);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue, 2));
setStyle(tsCrosshair);
setSize(6);
setInterpolating(false);
setGraphKey(0);
}
QCPItemTracer::~QCPItemTracer()
{
}
/*!
Sets the pen that will be used to draw the line of the tracer
\see setSelectedPen, setBrush
*/
void QCPItemTracer::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the line of the tracer when selected
\see setPen, setSelected
*/
void QCPItemTracer::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the brush that will be used to draw any fills of the tracer
\see setSelectedBrush, setPen
*/
void QCPItemTracer::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
Sets the brush that will be used to draw any fills of the tracer, when selected.
\see setBrush, setSelected
*/
void QCPItemTracer::setSelectedBrush(const QBrush &brush)
{
mSelectedBrush = brush;
}
/*!
Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare
does, \ref tsCrosshair does not).
*/
void QCPItemTracer::setSize(double size)
{
mSize = size;
}
/*!
Sets the style/visual appearance of the tracer.
If you only want to use the tracer \a position as an anchor for other items, set \a style to
\ref tsNone.
*/
void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style)
{
mStyle = style;
}
/*!
Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type
QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph.
To free the tracer from any graph, set \a graph to 0. The tracer \a position can then be placed
freely like any other item position. This is the state the tracer will assume when its graph gets
deleted while still attached to it.
\see setGraphKey
*/
void QCPItemTracer::setGraph(QCPGraph *graph)
{
if (graph)
{
if (graph->parentPlot() == mParentPlot)
{
position->setType(QCPItemPosition::ptPlotCoords);
position->setAxes(graph->keyAxis(), graph->valueAxis());
mGraph = graph;
updatePosition();
} else
qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item";
} else
{
mGraph = 0;
}
}
/*!
Sets the key of the graph's data point the tracer will be positioned at. This is the only free
coordinate of a tracer when attached to a graph.
Depending on \ref setInterpolating, the tracer will be either positioned on the data point
closest to \a key, or will stay exactly at \a key and interpolate the value linearly.
\see setGraph, setInterpolating
*/
void QCPItemTracer::setGraphKey(double key)
{
mGraphKey = key;
}
/*!
Sets whether the value of the graph's data points shall be interpolated, when positioning the
tracer.
If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on
the data point of the graph which is closest to the key, but which is not necessarily exactly
there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and
the appropriate value will be interpolated from the graph's data points linearly.
\see setGraph, setGraphKey
*/
void QCPItemTracer::setInterpolating(bool enabled)
{
mInterpolating = enabled;
}
/* inherits documentation from base class */
double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
QPointF center(position->pixelPoint());
double w = mSize/2.0;
QRect clip = clipRect();
switch (mStyle)
{
case tsNone: return -1;
case tsPlus:
{
if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
return qSqrt(qMin(distSqrToLine(center+QPointF(-w, 0), center+QPointF(w, 0), pos),
distSqrToLine(center+QPointF(0, -w), center+QPointF(0, w), pos)));
break;
}
case tsCrosshair:
{
return qSqrt(qMin(distSqrToLine(QPointF(clip.left(), center.y()), QPointF(clip.right(), center.y()), pos),
distSqrToLine(QPointF(center.x(), clip.top()), QPointF(center.x(), clip.bottom()), pos)));
}
case tsCircle:
{
if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
{
// distance to border:
double centerDist = QVector2D(center-pos).length();
double circleLine = w;
double result = qAbs(centerDist-circleLine);
// filled ellipse, allow click inside to count as hit:
if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
{
if (centerDist <= circleLine)
result = mParentPlot->selectionTolerance()*0.99;
}
return result;
}
break;
}
case tsSquare:
{
if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
{
QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w));
bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
return rectSelectTest(rect, pos, filledRect);
}
break;
}
}
return -1;
}
/* inherits documentation from base class */
void QCPItemTracer::draw(QCPPainter *painter)
{
updatePosition();
if (mStyle == tsNone)
return;
painter->setPen(mainPen());
painter->setBrush(mainBrush());
QPointF center(position->pixelPoint());
double w = mSize/2.0;
QRect clip = clipRect();
switch (mStyle)
{
case tsNone: return;
case tsPlus:
{
if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
{
painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0)));
painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w)));
}
break;
}
case tsCrosshair:
{
if (center.y() > clip.top() && center.y() < clip.bottom())
painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y()));
if (center.x() > clip.left() && center.x() < clip.right())
painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom()));
break;
}
case tsCircle:
{
if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
painter->drawEllipse(center, w, w);
break;
}
case tsSquare:
{
if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w)));
break;
}
}
}
/*!
If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a
position to reside on the graph data, depending on the configured key (\ref setGraphKey).
It is called automatically on every redraw and normally doesn't need to be called manually. One
exception is when you want to read the tracer coordinates via \a position and are not sure that
the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw.
In that situation, call this function before accessing \a position, to make sure you don't get
out-of-date coordinates.
If there is no graph set on this tracer, this function does nothing.
*/
void QCPItemTracer::updatePosition()
{
if (mGraph)
{
if (mParentPlot->hasPlottable(mGraph))
{
if (mGraph->data()->size() > 1)
{
QCPDataMap::const_iterator first = mGraph->data()->constBegin();
QCPDataMap::const_iterator last = mGraph->data()->constEnd()-1;
if (mGraphKey < first.key())
position->setCoords(first.key(), first.value().value);
else if (mGraphKey > last.key())
position->setCoords(last.key(), last.value().value);
else
{
QCPDataMap::const_iterator it = mGraph->data()->lowerBound(mGraphKey);
if (it != first) // mGraphKey is somewhere between iterators
{
QCPDataMap::const_iterator prevIt = it-1;
if (mInterpolating)
{
// interpolate between iterators around mGraphKey:
double slope = 0;
if (!qFuzzyCompare((double)it.key(), (double)prevIt.key()))
slope = (it.value().value-prevIt.value().value)/(it.key()-prevIt.key());
position->setCoords(mGraphKey, (mGraphKey-prevIt.key())*slope+prevIt.value().value);
} else
{
// find iterator with key closest to mGraphKey:
if (mGraphKey < (prevIt.key()+it.key())*0.5)
it = prevIt;
position->setCoords(it.key(), it.value().value);
}
} else // mGraphKey is exactly on first iterator
position->setCoords(it.key(), it.value().value);
}
} else if (mGraph->data()->size() == 1)
{
QCPDataMap::const_iterator it = mGraph->data()->constBegin();
position->setCoords(it.key(), it.value().value);
} else
qDebug() << Q_FUNC_INFO << "graph has no data";
} else
qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)";
}
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
and mSelectedPen when it is.
*/
QPen QCPItemTracer::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
/*! \internal
Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
is not selected and mSelectedBrush when it is.
*/
QBrush QCPItemTracer::mainBrush() const
{
return mSelected ? mSelectedBrush : mBrush;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemBracket
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemBracket
\brief A bracket for referencing/highlighting certain parts in the plot.
\image html QCPItemBracket.png "Bracket example. Blue dotted circles are anchors, solid blue discs are positions."
It has two positions, \a left and \a right, which define the span of the bracket. If \a left is
actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the
example image.
The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket
stretches away from the embraced span, can be controlled with \ref setLength.
\image html QCPItemBracket-length.png
<center>Demonstrating the effect of different values for \ref setLength, for styles \ref
bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine
or QCPItemCurve) or a text label (QCPItemText), to the bracket.
*/
/*!
Creates a bracket item and sets default values.
The constructed item can be added to the plot with QCustomPlot::addItem.
*/
QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
left(createPosition(QLatin1String("left"))),
right(createPosition(QLatin1String("right"))),
center(createAnchor(QLatin1String("center"), aiCenter))
{
left->setCoords(0, 0);
right->setCoords(1, 1);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue, 2));
setLength(8);
setStyle(bsCalligraphic);
}
QCPItemBracket::~QCPItemBracket()
{
}
/*!
Sets the pen that will be used to draw the bracket.
Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the
stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use
\ref setLength, which has a similar effect.
\see setSelectedPen
*/
void QCPItemBracket::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the bracket when selected
\see setPen, setSelected
*/
void QCPItemBracket::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the \a length in pixels how far the bracket extends in the direction towards the embraced
span of the bracket (i.e. perpendicular to the <i>left</i>-<i>right</i>-direction)
\image html QCPItemBracket-length.png
<center>Demonstrating the effect of different values for \ref setLength, for styles \ref
bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
*/
void QCPItemBracket::setLength(double length)
{
mLength = length;
}
/*!
Sets the style of the bracket, i.e. the shape/visual appearance.
\see setPen
*/
void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style)
{
mStyle = style;
}
/* inherits documentation from base class */
double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
QVector2D leftVec(left->pixelPoint());
QVector2D rightVec(right->pixelPoint());
if (leftVec.toPoint() == rightVec.toPoint())
return -1;
QVector2D widthVec = (rightVec-leftVec)*0.5f;
QVector2D lengthVec(-widthVec.y(), widthVec.x());
lengthVec = lengthVec.normalized()*mLength;
QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec;
switch (mStyle)
{
case QCPItemBracket::bsSquare:
case QCPItemBracket::bsRound:
{
double a = distSqrToLine((centerVec-widthVec).toPointF(), (centerVec+widthVec).toPointF(), pos);
double b = distSqrToLine((centerVec-widthVec+lengthVec).toPointF(), (centerVec-widthVec).toPointF(), pos);
double c = distSqrToLine((centerVec+widthVec+lengthVec).toPointF(), (centerVec+widthVec).toPointF(), pos);
return qSqrt(qMin(qMin(a, b), c));
}
case QCPItemBracket::bsCurly:
case QCPItemBracket::bsCalligraphic:
{
double a = distSqrToLine((centerVec-widthVec*0.75f+lengthVec*0.15f).toPointF(), (centerVec+lengthVec*0.3f).toPointF(), pos);
double b = distSqrToLine((centerVec-widthVec+lengthVec*0.7f).toPointF(), (centerVec-widthVec*0.75f+lengthVec*0.15f).toPointF(), pos);
double c = distSqrToLine((centerVec+widthVec*0.75f+lengthVec*0.15f).toPointF(), (centerVec+lengthVec*0.3f).toPointF(), pos);
double d = distSqrToLine((centerVec+widthVec+lengthVec*0.7f).toPointF(), (centerVec+widthVec*0.75f+lengthVec*0.15f).toPointF(), pos);
return qSqrt(qMin(qMin(a, b), qMin(c, d)));
}
}
return -1;
}
/* inherits documentation from base class */
void QCPItemBracket::draw(QCPPainter *painter)
{
QVector2D leftVec(left->pixelPoint());
QVector2D rightVec(right->pixelPoint());
if (leftVec.toPoint() == rightVec.toPoint())
return;
QVector2D widthVec = (rightVec-leftVec)*0.5f;
QVector2D lengthVec(-widthVec.y(), widthVec.x());
lengthVec = lengthVec.normalized()*mLength;
QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec;
QPolygon boundingPoly;
boundingPoly << leftVec.toPoint() << rightVec.toPoint()
<< (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint();
QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
if (clip.intersects(boundingPoly.boundingRect()))
{
painter->setPen(mainPen());
switch (mStyle)
{
case bsSquare:
{
painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF());
painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
break;
}
case bsRound:
{
painter->setBrush(Qt::NoBrush);
QPainterPath path;
path.moveTo((centerVec+widthVec+lengthVec).toPointF());
path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF());
path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
painter->drawPath(path);
break;
}
case bsCurly:
{
painter->setBrush(Qt::NoBrush);
QPainterPath path;
path.moveTo((centerVec+widthVec+lengthVec).toPointF());
path.cubicTo((centerVec+widthVec-lengthVec*0.8f).toPointF(), (centerVec+0.4f*widthVec+lengthVec).toPointF(), centerVec.toPointF());
path.cubicTo((centerVec-0.4f*widthVec+lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8f).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
painter->drawPath(path);
break;
}
case bsCalligraphic:
{
painter->setPen(Qt::NoPen);
painter->setBrush(QBrush(mainPen().color()));
QPainterPath path;
path.moveTo((centerVec+widthVec+lengthVec).toPointF());
path.cubicTo((centerVec+widthVec-lengthVec*0.8f).toPointF(), (centerVec+0.4f*widthVec+0.8f*lengthVec).toPointF(), centerVec.toPointF());
path.cubicTo((centerVec-0.4f*widthVec+0.8f*lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8f).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
path.cubicTo((centerVec-widthVec-lengthVec*0.5f).toPointF(), (centerVec-0.2f*widthVec+1.2f*lengthVec).toPointF(), (centerVec+lengthVec*0.2f).toPointF());
path.cubicTo((centerVec+0.2f*widthVec+1.2f*lengthVec).toPointF(), (centerVec+widthVec-lengthVec*0.5f).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
painter->drawPath(path);
break;
}
}
}
}
/* inherits documentation from base class */
QPointF QCPItemBracket::anchorPixelPoint(int anchorId) const
{
QVector2D leftVec(left->pixelPoint());
QVector2D rightVec(right->pixelPoint());
if (leftVec.toPoint() == rightVec.toPoint())
return leftVec.toPointF();
QVector2D widthVec = (rightVec-leftVec)*0.5f;
QVector2D lengthVec(-widthVec.y(), widthVec.x());
lengthVec = lengthVec.normalized()*mLength;
QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec;
switch (anchorId)
{
case aiCenter:
return centerVec.toPointF();
}
qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
return QPointF();
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the
item is not selected and mSelectedPen when it is.
*/
QPen QCPItemBracket::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
| 851,667 | C++ | 35.158105 | 243 | 0.697473 |
adegirmenci/HBL-ICEbot/main.cpp | #include "icebot_gui.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ICEbot_GUI w;
w.show();
return a.exec();
}
| 172 | C++ | 13.416666 | 32 | 0.610465 |
adegirmenci/HBL-ICEbot/README.md | # HBL-ICEbot
Codebase for the robotic ultrasound catheter system developed at the Harvard Biorobotics Laboratory. See [project page](http://biorobotics.harvard.edu/ICEbot_.html) for description and list of publications.
## Prerequisites
You will need the following libraries and drivers installed on your system:
* OpenCV (2.4.1x)
* Eigen
* Boost
* Maxon EPOS Drivers
* OpenHaptics
* LabJack
* Ascension TrakStar Drivers
* StarTech UBS3HDCAP Drivers
## Built With
* Qt 5.7
* MSVC 2012
## Authors
* **Alperen Degirmenci** - *Lead developer* - [Harvard Biorobotics Lab](https://scholar.harvard.edu/adegirmenci/)
* **Paul M. Loschak** - *Contributions to the controller*
## License
This project is licensed under the MIT License.
## Acknowledgments
* This work was supported by the Harvard University John A. Paulson School of Engineering and Applied Sciences, American Heart Association Grant #15PRE22710043, the National Institutes of Health Grant #1R21EB018938, and the NVIDIA Academic Hardware Grant Program.
| 1,020 | Markdown | 29.939393 | 263 | 0.77451 |
adegirmenci/HBL-ICEbot/ControllerWidget/filtfilt.h | #ifndef FILTFILT_H
#define FILTFILT_H
#include <vector>
#include <algorithm>
#include <iostream>
#include <numeric>
#include <Eigen/Dense>
#include <Eigen/StdVector>
#include <memory>
#include <QElapsedTimer>
#include <boost/math/special_functions/sinc.hpp>
#include "kinematics_4dof.h" // for pi
#include "../icebot_definitions.h"
//#include <spuce/filters/design_window.h>
//#include <spuce/filters/design_fir.h>
//#include <spuce/typedefs.h>
//#include <spuce/filters/fir_coeff.h>
//#include <spuce/filters/window.h>
//#include <spuce/filters/fir.h>
//#include <FIR.h>
// Adapted from:
// http://stackoverflow.com/questions/17675053/matlabs-filtfilt-algorithm/27270420#27270420
// Mainly for CycleModel
//typedef Eigen::Matrix< double, Eigen::Dynamic , 1> EigenVectorFiltered;
//typedef Eigen::Matrix< double, Eigen::Dynamic , 7> EigenMatrixFiltered;
typedef Eigen::VectorXd EigenVectorFiltered;
typedef Eigen::MatrixXd EigenMatrixFiltered;
typedef Eigen::Matrix< double, N_POLAR , 1> EigenVectorPolar;
typedef Eigen::Matrix< double, N_POLAR , 7> EigenMatrixPolar;
typedef Eigen::Matrix< double, N_RECT , 1> EigenVectorRectangular;
typedef Eigen::Matrix< double, N_RECT , 7> EigenMatrixRectangular;
// Affine Transform
typedef Eigen::Transform<double,3,Eigen::Affine> EigenAffineTransform3d;
typedef Eigen::Matrix<double, 7 , 1> EigenVector7d;
// in order to use vector with Eigen Transform, we need this typedef
typedef std::vector< EigenAffineTransform3d, Eigen::aligned_allocator<EigenAffineTransform3d> > EigenStdVecAffineTform3d;
typedef std::vector< EigenVector7d, Eigen::aligned_allocator<EigenVector7d> > EigenStdVecVector7d;
// most efficient would be to use shared_ptr
typedef std::vector< std::shared_ptr<EigenVector7d> > EigenStdVecSharedPtrVector7d;
class filtfilt
{
public:
filtfilt();
~filtfilt();
// X is the original data, Y is the output
void run(const std::vector<double> &X, std::vector<double> &Y);
void run(const std::vector<double> &X, EigenVectorFiltered &Y);
void run(const EigenStdVecVector7d &X, EigenStdVecVector7d &Y);
void run(const EigenStdVecVector7d &X, EigenMatrixFiltered &Y);
// TODO : add function to change the heartrate, sampling freq, and maybe filter order
void setFilterCoefficients(const std::vector<double> &B, const std::vector<double> &A);
private:
void updateFilterParameters();
// helper functions
void filter(const std::vector<double> &X, std::vector<double> &Y, std::vector<double> &Zi);
void filter(const EigenStdVecVector7d &X, EigenStdVecVector7d &Y, EigenStdVecVector7d &Zi);
void add_index_range(std::vector<int> &indices, int beg, int end, int inc = 1);
void add_index_const(std::vector<int> &indices, int value, size_t numel);
void append_vector(std::vector<double> &vec, const std::vector<double> &tail);
void append_vector(EigenStdVecVector7d &vec, const EigenStdVecVector7d &tail);
std::vector<double> subvector_reverse(const std::vector<double> &vec, int idx_end, int idx_start);
EigenStdVecVector7d subvector_reverseEig(const EigenStdVecVector7d &vec, int idx_end, int idx_start);
void subvector_reverseEig(const std::vector<double> &vec, int idx_end, int idx_start, EigenVectorFiltered &Y);
void subvector_reverseEig(const EigenStdVecVector7d &vec, int idx_end, int idx_start, EigenMatrixFiltered &Y);
inline int max_val(const std::vector<int>& vec)
{
return std::max_element(vec.begin(), vec.end())[0];
}
std::vector<double> FIR_LPF_LeastSquares(size_t L, const double deltaT);
std::vector<double> genHammingWindow(const size_t L);
std::vector<double> calcWindow(size_t m, size_t n);
// data members
std::vector<double> m_A, m_B; // filter coefficients
int m_na;
int m_nb;
int m_nfilt;
int m_nfact;
std::vector<int> m_rows, m_cols;
std::vector<double> m_data;
std::shared_ptr<Eigen::MatrixXd> m_zzi;
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
#endif // FILTFILT_H
| 4,049 | C | 35.160714 | 121 | 0.721907 |
adegirmenci/HBL-ICEbot/ControllerWidget/gainswidget.h | #ifndef GAINSWIDGET_H
#define GAINSWIDGET_H
#include <QWidget>
#include <QCloseEvent>
#include <QVector>
struct GainsPYRT
{
double kPitchMin;
double kPitch;
double kPitchMax;
double kYawMin;
double kYaw;
double kYawMax;
double kRollMin;
double kRoll;
double kRollMax;
double kTransMin;
double kTrans;
double kTransMax;
};
struct ConvergenceLimits
{
double posMin;
double posMax;
double angleMin;
double angleMax;
};
Q_DECLARE_METATYPE(GainsPYRT)
Q_DECLARE_METATYPE(ConvergenceLimits)
namespace Ui {
class gainsWidget;
}
class gainsWidget : public QWidget
{
Q_OBJECT
public:
explicit gainsWidget(QWidget *parent = 0);
~gainsWidget();
signals:
void closeGainsWindow();
void setGains(GainsPYRT gains);
void setLimits(ConvergenceLimits limits);
public slots:
void on_setGainsButton_clicked();
void on_setLimitsButton_clicked();
private slots:
void on_closeButton_clicked();
private:
Ui::gainsWidget *ui;
void closeEvent(QCloseEvent *event);
};
#endif // GAINSWIDGET_H
| 1,087 | C | 15 | 46 | 0.701012 |
adegirmenci/HBL-ICEbot/ControllerWidget/respmodelwidget.cpp | #include "respmodelwidget.h"
#include "ui_respmodelwidget.h"
respModelWidget::respModelWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::respModelWidget)
{
ui->setupUi(this);
this->setWindowTitle("Respiration Modeling");
// QCustomPlot
// include this section to fully disable antialiasing for higher performance:
ui->plotWidget->setNotAntialiasedElements(QCP::aeAll);
QFont font;
font.setStyleStrategy(QFont::NoAntialias);
ui->plotWidget->xAxis->setTickLabelFont(font);
ui->plotWidget->yAxis->setTickLabelFont(font);
ui->plotWidget->legend->setFont(font);
ui->plotWidget->addGraph(); // blue line
ui->plotWidget->graph(0)->setPen(QPen(Qt::blue));
//ui->plotWidget->graph(0)->setBrush(QBrush(QColor(240, 255, 200)));
ui->plotWidget->graph(0)->setAntialiasedFill(false);
ui->plotWidget->addGraph(); // red line
ui->plotWidget->graph(1)->setPen(QPen(Qt::red));
ui->plotWidget->graph(1)->setAntialiasedFill(false);
ui->plotWidget->addGraph(); // black line
ui->plotWidget->graph(2)->setPen(QPen(Qt::black));
ui->plotWidget->graph(2)->setAntialiasedFill(false);
ui->plotWidget->xAxis->setTickLabelType(QCPAxis::ltDateTime);
ui->plotWidget->xAxis->setDateTimeFormat("hh:mm:ss");
ui->plotWidget->xAxis->setAutoTickStep(false);
ui->plotWidget->xAxis->setTickStep(2);
ui->plotWidget->axisRect()->setupFullAxesBox();
// make left and bottom axes transfer their ranges to right and top axes:
connect(ui->plotWidget->xAxis, SIGNAL(rangeChanged(QCPRange)), ui->plotWidget->xAxis2, SLOT(setRange(QCPRange)));
connect(ui->plotWidget->yAxis, SIGNAL(rangeChanged(QCPRange)), ui->plotWidget->yAxis2, SLOT(setRange(QCPRange)));
m_lastPlotKey = 0.0;
}
respModelWidget::~respModelWidget()
{
delete ui;
}
void respModelWidget::on_closeButton_clicked()
{
emit closeRespModelWindow();
}
void respModelWidget::on_initializeButton_clicked()
{
ui->initializeButton->setEnabled(false);
ui->reInitButton->setEnabled(false);
ui->stopButton->setEnabled(true);
emit initializeRespModel();
}
void respModelWidget::on_reInitButton_clicked()
{
ui->initializeButton->setEnabled(false);
ui->reInitButton->setEnabled(false);
ui->stopButton->setEnabled(true);
emit re_initializeRespModel();
}
void respModelWidget::on_stopButton_clicked()
{
ui->initializeButton->setEnabled(false);
ui->reInitButton->setEnabled(true);
ui->stopButton->setEnabled(false);
emit stopRespModel();
}
void respModelWidget::receiveDataFromRespModel(int numSamples,
bool isTrained,
bool inVivoMode,
double omega0)//,
//EigenVectorFiltered Bird4_filtered,
//EigenVectorFiltered Bird4_filtered_new,
//EigenVectorFiltered breathSignalFromModel)
{
// update things
ui->samplesCollectedSpinBox->setValue(numSamples);
ui->periodSpinBox->setValue(2.0*pi/omega0);
if(inVivoMode)
ui->inVivoModeLabel->setStyleSheet("QLabel { background-color : green;}");
else
ui->inVivoModeLabel->setStyleSheet("QLabel { background-color : red;}");
if(isTrained)
ui->modelIsTrainedLabel->setStyleSheet("QLabel { background-color : green;}");
else
ui->modelIsTrainedLabel->setStyleSheet("QLabel { background-color : red;}");
// // plotting
// double key = numSamples/150.0;
// static double lastPointKey = 0;
// if( (key - lastPointKey) > 0.01) // at most add point every 10 ms
// {
// if( (numSamples > 2*N_SAMPLES) && isTrained )
// {
// ui->plotWidget->graph(1)->addData(key, Bird4_filtered_new(N_SAMPLES-1));
// ui->plotWidget->graph(2)->addData(key, breathSignalFromModel(N_SAMPLES-1));
// }
// else
// {
// if( (numSamples > N_SAMPLES) && isTrained )
// {
// ui->plotWidget->graph(1)->addData(key, Bird4_filtered_new(numSamples-N_SAMPLES-1));
// ui->plotWidget->graph(2)->addData(key, breathSignalFromModel(numSamples-N_SAMPLES-1));
// }
// else
// {
// ui->plotWidget->graph(0)->addData(key, Bird4_filtered(numSamples-1));
// }
// }
// // remove data of lines that's outside visible range:
// ui->plotWidget->graph(1)->removeDataBefore(key-8);
// ui->plotWidget->graph(2)->removeDataBefore(key-8);
// // rescale value (vertical) axis to fit the current data:
// ui->plotWidget->graph(1)->rescaleValueAxis();
// lastPointKey = key;
// }
// // make key axis range scroll with the data (at a constant range size of 8):
// //ui->plotWidget->xAxis->setRange(key+0.25, 8, Qt::AlignRight);
// ui->plotWidget->replot();
}
void respModelWidget::plotBird4(unsigned int plotID, double time, double value)
{
// printf(">>> plotBird4 Received\n");
ui->plotWidget->graph(plotID)->addData(time, value);
if(plotID == 0)
{
if( (time - m_lastPlotKey) > 0.030) // plot every 30ms
{
// make key axis range scroll with the data (at a constant range size of 8):
ui->plotWidget->xAxis->setRange(time, 15.0, Qt::AlignRight);
// remove data of lines that's outside visible range:
ui->plotWidget->graph(0)->removeDataBefore(time-15.0);
ui->plotWidget->graph(1)->removeDataBefore(time-15.0);
ui->plotWidget->graph(2)->removeDataBefore(time-15.0);
//ui->plotWidget->graph(0)->rescaleValueAxis();
ui->plotWidget->yAxis->rescale();
ui->plotWidget->replot();
m_lastPlotKey = time;
}
}
}
void respModelWidget::closeEvent(QCloseEvent *event)
{
emit closeRespModelWindow();
event->accept();
}
void respModelWidget::on_futureSamplesSpinBox_valueChanged(int arg1)
{
emit newFutureSamplesValue(arg1);
}
void respModelWidget::on_bird4RadioButton_clicked()
{
emit changePlotFocus(RESP_MODEL_PLOT_BIRD4);
}
void respModelWidget::on_CTradioButton_clicked()
{
emit changePlotFocus(RESP_MODEL_PLOT_CT);
}
| 6,365 | C++ | 33.597826 | 117 | 0.625452 |
adegirmenci/HBL-ICEbot/ControllerWidget/controllerwidget.h | #ifndef CONTROLLERWIDGET_H
#define CONTROLLERWIDGET_H
#include <QWidget>
#include <QThread>
#include <QFileDialog>
#include <QTextStream>
#include <QString>
#include <QStringList>
#include <QTimer>
#include "controllerthread.h"
#include "gainswidget.h"
#include "respmodelwidget.h"
namespace Ui {
class ControllerWidget;
}
class ControllerWidget : public QWidget
{
Q_OBJECT
public:
explicit ControllerWidget(QWidget *parent = 0);
~ControllerWidget();
ControllerThread *m_worker;
signals:
void tellWorkerToPrintThreadID();
void updateJointSpaceCommand(double pitch, double yaw, double roll, double trans);
void updateConfigSpaceCommand(double alpha, double theta, double gamma, double d);
void updateTaskSpaceCommand(double x, double y, double z, double delPsi, bool isAbsolute);
void tellWorkerToResetBB();
void startControlCycle(); // start control loop in worker
void stopControlCycle(); // stop control loop in worker
void updateModeFlags(ModeFlags flags);
void updateUSangle(double usAngle);
void workerStartSweep(unsigned int nSteps_,
double stepAngle_,
double convLimit_,
qint64 imgDuration_);
void workerAbortSweep();
private slots:
void workerStatusChanged(int status);
void receiveMsgFromWorker(QString msg, int destination);
void on_testButton_clicked();
void on_taskSpaceGroupBox_toggled(bool arg1);
void on_configSpaceGroupBox_toggled(bool arg1);
void on_jointSpaceGroupBox_toggled(bool arg1);
void on_updateJointSpaceButton_clicked();
void on_updateConfigSpaceButton_clicked();
void on_updateTaskSpaceButton_clicked();
void on_controllerToggleButton_clicked();
void on_resetBB_Button_clicked();
void on_adjustGainsButton_clicked();
void on_relativeRadiobutton_clicked();
void on_absoluteRadiobutton_clicked();
void on_updateFlagsButton_clicked();
void on_setUSangleButton_clicked();
void on_respModelButton_clicked();
void on_trajOpenFileButton_clicked();
void on_trajDriveButton_clicked();
void receiveCurrentXYZPSI(XYZPSI currXYZPSI);
void driveTrajectory();
void on_sweepButton_clicked();
void on_abortSweepButton_clicked();
private:
Ui::ControllerWidget *ui;
gainsWidget *gainWidget;
respModelWidget *m_respModelWidget;
QThread m_thread; // Controller Thread will live in here
XYZPSI m_currXYZPSI;
unsigned int m_ctr;
// trajectory
std::vector<XYZPSI> m_XYZPSIs;
bool m_keepDriving;
size_t m_currTrajIdx;
QTimer *m_trajTimer;
};
#endif // CONTROLLERWIDGET_H
| 2,686 | C | 22.778761 | 94 | 0.710722 |
adegirmenci/HBL-ICEbot/ControllerWidget/controllerthread.cpp | #include "controllerthread.h"
ControllerThread::ControllerThread(QObject *parent) :
QObject(parent)
{
qRegisterMetaType<ModeFlags>("ModeFlags");
qRegisterMetaType<EigenVectorFiltered>("EigenVectorFiltered");
qRegisterMetaType<XYZPSI>("XYZPSI");
m_isEpochSet = false;
m_isReady = false;
m_keepControlling = false;
m_abort = false;
m_latestReading.resize(4);
m_respModelInitializing = false;
m_numCycles = 0;
m_cathKin = Kinematics_4DOF(0.05*1000.0, 0.00135*1000.0, 0.90*0.0254*1000.0);
// m_respModel = CyclicModel();
loadConstants();
// zero initialize
m_targetPos = m_targetPos.Identity();
m_deltaXYZPsiToTarget << 0.0, 0.0, 0.0, 0.0;
m_input_AbsXYZ << 0.0, 0.0, 0.0;
m_input_RelXYZ << 0.0, 0.0, 0.0;
m_input_delPsi = 0.0;
m_dXYZPsi << 0.0, 0.0, 0.0, 0.0;
// FOR IN VIVO EXP 6!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
setUSangle(0.0); // 75 deg for Exp 5, used 108 for ablation tracking at one point
m_modeFlags.inVivoMode = IN_VIVO_OFF;
// MATLAB
#ifdef SVM_ON
SVMregression_initialize();
#endif
m_mutex = new QMutex(QMutex::NonRecursive);
m_isReady = true;
emit statusChanged(CONTROLLER_INITIALIZED);
}
ControllerThread::~ControllerThread()
{
// std::cout << "FwdKin\n" << m_cathKin.forwardKinematics(1,0.1,0.1,0).matrix() << std::endl;
// std::cout << "Jacobian\n" << m_cathKin.JacobianNumeric(1,0.1,0.1,0).matrix() << std::endl;
// std::cout << "InvKin3D\n" << m_cathKin.inverseKinematics3D(5,5,12,0.1) << std::endl;
// Eigen::Transform<double, 3, Eigen::Affine> T_in(Eigen::Matrix<double, 4, 4>::Identity());
// std::cout << "T_in\n" << T_in.matrix() << std::endl;
// Eigen::Vector4d configIn(0.0010, 0.0001, 0.0001, 0);
// std::cout << "control_icra2016\n" << m_cathKin.control_icra2016(T_in, configIn, 0.0) << std::endl;
qDebug() << "Ending ControllerThread - ID: " << reinterpret_cast<int>(QThread::currentThreadId()) << ".";
// stop controller
stopControlCycle();
m_mutex->lock();
m_abort = true;
m_mutex->unlock();
delete m_mutex;
// MATLAB
#ifdef SVM_ON
SVMregression_terminate();
#endif
emit finished();
}
// ------------------------------
// SLOTS IMPLEMENTATION
// ------------------------------
void ControllerThread::setEpoch(const QDateTime &epoch)
{
QMutexLocker locker(m_mutex);
if(!m_keepControlling)
{
m_epoch = epoch;
m_isEpochSet = true;
emit logEventWithMessage(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_EPOCH_SET,
m_epoch.toString("dd/MM/yyyy - hh:mm:ss.zzz"));
}
else
emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_EPOCH_SET_FAILED);
}
void ControllerThread::printThreadID()
{
qDebug() << QTime::currentTime() << "Worker Thread ID: " << reinterpret_cast<int>(QThread::currentThreadId());
m_respModel.testLPF();
}
// THIS FUNCTION SHOULD NOT BE USED AT ALL
void ControllerThread::receiveEMdata(QTime timeStamp, int sensorID, DOUBLE_POSITION_MATRIX_TIME_Q_RECORD data)
{
// Data Format
// | Sensor ID | Time Stamp | x | y | z | q1 | q2 | q3 | q4 |
// | int | double | ... double ... |
QMutexLocker locker(m_mutex);
m_prevReading[sensorID] = m_latestReading[sensorID];
m_latestReading[sensorID] = data;
QElapsedTimer elTimer;
elTimer.start();
// TODO: emit signal to log receiveEMdata event
//emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_EM_RECEIVED);
switch(sensorID)
{
case EM_SENSOR_BB:
Transform_From_EMreading(data, m_basTipPos_mobile);
m_Box_BBmobile = m_basTipPos_mobile * m_BB_SBm.inverse();
m_BBfixed_BBmobile = m_BB_Box * m_Box_BBmobile;
m_BBmobile_CT = m_Box_BBmobile.inverse()*m_curTipPos*m_STm_BT*m_BT_CT;
break;
case EM_SENSOR_BT:
// process CT point
Transform_From_EMreading(data, m_curTipPos);
m_BB_CT_curTipPos = m_BB_Box*m_curTipPos*m_STm_BT*m_BT_CT; // convert to CT in terms of BBfixed
break;
case EM_SENSOR_INST:
Transform_From_EMreading(data, m_targetPos);
m_targetPos = m_targetPos * m_ISm_INSTR;
m_BB_targetPos = m_BB_Box * m_targetPos;
break;
case EM_SENSOR_CHEST:
Transform_From_EMreading(data, m_currChest);
break;
default:
qDebug() << "SensorID not recognized!";
break;
}
qint64 elNsec = elTimer.nsecsElapsed();
qDebug() << "Nsec elapsed:" << elNsec;
}
void ControllerThread::receiveLatestEMreading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> readings)
{
QMutexLocker locker(m_mutex);
QElapsedTimer elTimer;
elTimer.start();
Q_ASSERT(4 == readings.size());
m_prevReading = m_latestReading;
m_latestReading = readings;
// EM_SENSOR_BB:
Transform_From_EMreading(readings[EM_SENSOR_BB], m_Box_SBm);
// EM_SENSOR_BT
Transform_From_EMreading(readings[EM_SENSOR_BT], m_curTipPos);
// EM_SENSOR_INST:
Transform_From_EMreading(readings[EM_SENSOR_INST], m_targetPos);
// EM_SENSOR_CHEST:
Transform_From_EMreading(readings[EM_SENSOR_CHEST], m_currChest);
// Calculate T_BBmobile_CT
m_basTipPos_mobile = m_Box_SBm;
m_Box_BBmobile = m_Box_SBm * m_BB_SBm.inverse();
m_BBfixed_BBmobile = m_BB_Box * m_Box_BBmobile;
// this is from MATLAB >>> Get BT w.r.t. mobile BB, rather than fixed BB
// this is from MATLAB >>> m_BBmobile_BT = m_BBfixed_BBmobile.inverse() * m_BB_CT_curTipPos * m_BT_CT.inverse();
m_BBmobile_BT = m_Box_BBmobile.inverse() * m_curTipPos * m_STm_BT;
// this is the original C++ >>> m_BBmobile_CT = m_Box_BBmobile.inverse() * m_curTipPos * m_STm_BT * m_BT_CT;
m_BBmobile_CT = m_BBmobile_BT * m_BT_CT;
//Calculate T_BB_CT_curTipPos:
// process CT point
m_BB_CT_curTipPos = m_BB_Box * m_curTipPos * m_STm_BT * m_BT_CT; // convert to CT in terms of BBfixed
//Calculate T_BB_targetPos
m_targetPos = m_targetPos * m_ISm_INSTR; // the tip of the instrument in EM coord
m_BB_targetPos = m_BB_Box * m_targetPos; // the tip of the instr in BBfixed coord
std::vector<double> T_BB_CT_curTipPos(m_BB_CT_curTipPos.matrix().data(), m_BB_CT_curTipPos.matrix().data() + m_BB_CT_curTipPos.matrix().size());
if(T_BB_CT_curTipPos.size() == 16)
{
QDateTime t; t.setMSecsSinceEpoch(readings[EM_SENSOR_BT].time*1000.0);
emit logData(t.time(), m_numCycles, CONTROLLER_T_BB_CT_curTipPos, T_BB_CT_curTipPos);
emit send_CT_toFrameClient(T_BB_CT_curTipPos, readings[EM_SENSOR_BT].time);
}
if(m_respModelInitializing)
{
// send training data
//const EigenAffineTransform3d &T_BB_CT_curTipPos,
//const EigenAffineTransform3d &T_BB_targetPos,
//const EigenAffineTransform3d &T_Box_BBmobile,
//const EigenAffineTransform3d &T_BB_Box,
//const EigenAffineTransform3d &T_Bird4,
m_respModel.addTrainingObservation(m_BB_CT_curTipPos, m_BB_targetPos, m_Box_BBmobile, m_BB_Box, m_currChest, readings[EM_SENSOR_CHEST].time);
// check how many samples were sent and turn off flag if trained
if(m_respModel.getNumSamples() == N_SAMPLES)
{
std::cout << "Train model.\n" << std::endl;
m_respModel.trainModel();
if(m_respModel.isTrained())
{
m_respModelInitializing = false;
std::cout << "Model trained.\n" << std::endl;
emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_RESP_MODEL_INITIALIZED);
}
else
{
// ERROR!
std::cout << "Error in training resp model!" << std::endl;
emit logEvent(SRC_CONTROLLER, LOG_ERROR, QTime::currentTime(), CONTROLLER_RESP_MODEL_INIT_FAILED);
}
}
}
else if(m_respModel.isTrained())
{
// send current data
m_respModel.addObservation(m_currChest, readings[EM_SENSOR_CHEST].time);
std::vector<double> omega = {m_respModel.getOmega()};
emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_PERIOD, omega);
}
if(!m_respModelInitializing)
{
controlCycle();
}
// TODO : send data to resp model widget
// size_t numSamples,
// bool isTrained,
// bool inVivoMode,
// double omega0,
// EigenVectorFiltered Bird4_filtered,
// EigenVectorFiltered Bird4_filtered_new,
// EigenVectorFiltered breathSignalFromModel);
emit sendDataToRespModelWidget(m_respModel.getNumSamples(),
m_respModel.isTrained(),
m_respModel.isInVivoMode(),
m_respModel.getOmega());//,
// m_respModel.get_Bird4_filtered(),
// m_respModel.get_Bird4_filtered_new(),
// m_respModel.get_breathSignalFromModel());
qint64 elNsec = elTimer.nsecsElapsed();
std::cout << "EM receive Nsec elapsed: " << elNsec << std::endl;
//std::cout << m_BB_CT_curTipPos.matrix() << std::endl;
// display in GUI
QString msg = QString("T_BBfixed_CT:\n");
msg += QString::number(m_BB_CT_curTipPos(0,0), 'f', 3) + " "
+ QString::number(m_BB_CT_curTipPos(0,1), 'f', 3) + " "
+ QString::number(m_BB_CT_curTipPos(0,2), 'f', 3) + " "
+ QString::number(m_BB_CT_curTipPos(0,3), 'f', 2) + "\n"
+ QString::number(m_BB_CT_curTipPos(1,0), 'f', 3) + " "
+ QString::number(m_BB_CT_curTipPos(1,1), 'f', 3) + " "
+ QString::number(m_BB_CT_curTipPos(1,2), 'f', 3) + " "
+ QString::number(m_BB_CT_curTipPos(1,3), 'f', 2) + "\n"
+ QString::number(m_BB_CT_curTipPos(2,0), 'f', 3) + " "
+ QString::number(m_BB_CT_curTipPos(2,1), 'f', 3) + " "
+ QString::number(m_BB_CT_curTipPos(2,2), 'f', 3) + " "
+ QString::number(m_BB_CT_curTipPos(2,3), 'f', 2) + "\n"
+ QString::number(m_BB_CT_curTipPos(3,0), 'f', 3) + " "
+ QString::number(m_BB_CT_curTipPos(3,1), 'f', 3) + " "
+ QString::number(m_BB_CT_curTipPos(3,2), 'f', 3) + " "
+ QString::number(m_BB_CT_curTipPos(3,3), 'f', 2) + "\n";
msg += QString("\nT_BBmobile_CT:\n")
+ QString::number(m_BBmobile_CT(0,0), 'f', 3) + " "
+ QString::number(m_BBmobile_CT(0,1), 'f', 3) + " "
+ QString::number(m_BBmobile_CT(0,2), 'f', 3) + " "
+ QString::number(m_BBmobile_CT(0,3), 'f', 2) + "\n"
+ QString::number(m_BBmobile_CT(1,0), 'f', 3) + " "
+ QString::number(m_BBmobile_CT(1,1), 'f', 3) + " "
+ QString::number(m_BBmobile_CT(1,2), 'f', 3) + " "
+ QString::number(m_BBmobile_CT(1,3), 'f', 2) + "\n"
+ QString::number(m_BBmobile_CT(2,0), 'f', 3) + " "
+ QString::number(m_BBmobile_CT(2,1), 'f', 3) + " "
+ QString::number(m_BBmobile_CT(2,2), 'f', 3) + " "
+ QString::number(m_BBmobile_CT(2,3), 'f', 2) + "\n"
+ QString::number(m_BBmobile_CT(3,0), 'f', 3) + " "
+ QString::number(m_BBmobile_CT(3,1), 'f', 3) + " "
+ QString::number(m_BBmobile_CT(3,2), 'f', 3) + " "
+ QString::number(m_BBmobile_CT(3,3), 'f', 2) + "\n";
msg += QString("\nT_BBfixed_Instr:\n")
+ QString::number(m_BB_targetPos(0,0), 'f', 3) + " "
+ QString::number(m_BB_targetPos(0,1), 'f', 3) + " "
+ QString::number(m_BB_targetPos(0,2), 'f', 3) + " "
+ QString::number(m_BB_targetPos(0,3), 'f', 2) + "\n"
+ QString::number(m_BB_targetPos(1,0), 'f', 3) + " "
+ QString::number(m_BB_targetPos(1,1), 'f', 3) + " "
+ QString::number(m_BB_targetPos(1,2), 'f', 3) + " "
+ QString::number(m_BB_targetPos(1,3), 'f', 2) + "\n"
+ QString::number(m_BB_targetPos(2,0), 'f', 3) + " "
+ QString::number(m_BB_targetPos(2,1), 'f', 3) + " "
+ QString::number(m_BB_targetPos(2,2), 'f', 3) + " "
+ QString::number(m_BB_targetPos(2,3), 'f', 2) + "\n"
+ QString::number(m_BB_targetPos(3,0), 'f', 3) + " "
+ QString::number(m_BB_targetPos(3,1), 'f', 3) + " "
+ QString::number(m_BB_targetPos(3,2), 'f', 3) + " "
+ QString::number(m_BB_targetPos(3,3), 'f', 2);
emit sendMsgToWidget(msg, 0);
//emit logEventWithMessage(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), 0, msg);
}
void ControllerThread::updateJointSpaceCommand(double pitch, double yaw, double roll, double trans)
{
// qDebug() << "New Joint Target Received";
QMutexLocker locker(m_mutex);
// check limits
// update motor QCs
// emit event to DataLogger
}
void ControllerThread::updateConfigSpaceCommand(double alpha, double theta, double gamma, double d)
{
// this is not implemented at the moment, just test code
// qDebug() << "New Config Target Received";
QMutexLocker locker(m_mutex);
// run through kinematics
Eigen::Transform<double,3,Eigen::Affine> tempT;
tempT = m_cathKin.forwardKinematics(gamma, theta, alpha, d);
// check limits
double norm = (m_targetPos.matrix().col(3) - tempT.matrix().col(3)).norm();
qDebug() << "Norm:" << norm;
if(norm < 500.0) // less than 50 cm
{
// update target
;
}
// emit event to DataLogger
}
void ControllerThread::updateTaskSpaceCommand(double x, double y, double z, double delPsi, bool isAbsolute)
{
// qDebug() << "New Task Target Received";
QMutexLocker locker(m_mutex);
// Store the current tip pose as the new origin
m_BBfixed_CTorig = m_BB_CT_curTipPos;
// update target
if(isAbsolute)
{
m_input_AbsXYZ(0) = x;
m_input_AbsXYZ(1) = y;
m_input_AbsXYZ(2) = z;
m_input_RelXYZ(0) = 0.0; // TODO: this may be problematic, might want to chage the GUI to have both abs and rel editable at the same time
m_input_RelXYZ(1) = 0.0;
m_input_RelXYZ(2) = 0.0;
// m_deltaXYZPsiToTarget(0) = x - m_BBfixed_CTorig(0,3);
// m_deltaXYZPsiToTarget(1) = y - m_BBfixed_CTorig(1,3);
// m_deltaXYZPsiToTarget(2) = z - m_BBfixed_CTorig(2,3);
}
else
{
m_input_RelXYZ(0) = x;
m_input_RelXYZ(1) = y;
m_input_RelXYZ(2) = z;
m_input_AbsXYZ(0) = 0.0; // TODO: this may be problematic, might want to chage the GUI to have both abs and rel editable at the same time
m_input_AbsXYZ(1) = 0.0;
m_input_AbsXYZ(2) = 0.0;
// m_deltaXYZPsiToTarget(0) = x;
// m_deltaXYZPsiToTarget(1) = y;
// m_deltaXYZPsiToTarget(2) = z;
}
m_input_delPsi = delPsi;
// m_deltaXYZPsiToTarget(3) = delPsi;
// check limits
// emit event to DataLogger
std::vector<double> xyzdxyzpsi = {m_input_AbsXYZ(0), m_input_AbsXYZ(1), m_input_AbsXYZ(2),
m_input_RelXYZ(0), m_input_RelXYZ(1), m_input_RelXYZ(2), delPsi*deg180overPi};
emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_USER_XYZDXYZPSI, xyzdxyzpsi);
//std::cout << "New deltaXYZPsi : " << m_deltaXYZPsiToTarget << std::endl;
std::cout << "New AbsXYZ RelXYZ DelPsi: " << m_input_AbsXYZ << m_input_RelXYZ << m_input_delPsi << std::endl;
}
void ControllerThread::resetBB()
{
QMutexLocker locker(m_mutex);
// get latest BB reading, and put it into m_basTipPos_fixed ( = T_Box_SBm_fixed )
// m_basTipPos_fixed is the same as T_Box_SBm_fixed
Transform_From_EMreading(m_latestReading[EM_SENSOR_BB], m_basTipPos_fixed);
// update m_BB_Box
m_BB_Box = m_BB_SBm * m_basTipPos_fixed.inverse(); // T_BB_Box = T_BB_SBm * T_SBm_Box
// Save the fixed BB position, T_Box_BBfixed = T_Box_SBm_fixed * inv(T_BB_SBm)
m_Box_BBfixed = m_basTipPos_fixed * m_BB_SBm.inverse();
std::vector<double> T_basTipPos_fixed(m_basTipPos_fixed.matrix().data(), m_basTipPos_fixed.matrix().data() + m_basTipPos_fixed.matrix().size());
emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_RESETBB_SUCCESS);
if(T_basTipPos_fixed.size() == 16)
{
emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_RESETBB, T_basTipPos_fixed);
}
}
void ControllerThread::startControlCycle()
{
QMutexLocker locker(m_mutex);
if(m_isReady && !m_keepControlling) // ready to control
{
//Start the cycle
m_keepControlling = true;
// m_timer = new QTimer(this);
// connect(m_timer, SIGNAL(timeout()), this, SLOT(controlCycle()));
// m_timer->start(6); // every 6ms
// if(m_timer->isActive())
// {
// qDebug() << "Timer started.";
// emit statusChanged(CONTROLLER_LOOP_STARTED);
// emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_LOOP_STARTED);
// }
// else
// {
// qDebug() << "Timer is not active.";
// emit statusChanged(CONTROLLER_LOOP_STOPPED);
// emit logError(SRC_CONTROLLER, LOG_ERROR, QTime::currentTime(), CONTROLLER_INITIALIZE_FAILED, QString("Timer is not active."));
// }
emit statusChanged(CONTROLLER_LOOP_STARTED);
emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_LOOP_STARTED);
}
else
{
if(m_keepControlling)
qDebug() << "Controller is already running.";
else
{
qDebug() << "Controller is not ready.";
emit statusChanged(CONTROLLER_INITIALIZE_FAILED);
emit logError(SRC_CONTROLLER, LOG_ERROR, QTime::currentTime(), CONTROLLER_INITIALIZE_FAILED, QString("Controller is not ready."));
}
}
}
void ControllerThread::stopControlCycle()
{
QMutexLocker locker(m_mutex);
if(m_keepControlling)
{
m_keepControlling = false;
// m_timer->stop();
// disconnect(m_timer, SIGNAL(timeout()), 0, 0);
// delete m_timer;
emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_LOOP_STOPPED);
emit statusChanged(CONTROLLER_LOOP_STOPPED);
qDebug() << "Timer stopped.";
}
else
{
qDebug() << "Timer already stopped.";
}
}
void ControllerThread::setGains(GainsPYRT gains)
{
QMutexLocker locker(m_mutex);
m_gains = gains;
locker.unlock();
qDebug() << "Gains set:\nPitch:" << gains.kPitchMin << gains.kPitchMax
<< "\nYaw:" << gains.kYawMin << gains.kYawMax
<< "\nRoll:" << gains.kRollMin << gains.kRollMax
<< "\nTrans:" << gains.kTransMin << gains.kTransMax;
}
void ControllerThread::setLimits(ConvergenceLimits limits)
{
QMutexLocker locker(m_mutex);
m_convLimits = limits;
locker.unlock();
qDebug() << "Convergence limits set:\nPosition:" << limits.posMin << limits.posMax
<< "\nAngle:" << limits.angleMin << limits.angleMax;
}
void ControllerThread::setModeFlags(ModeFlags flags)
{
QMutexLocker locker(m_mutex);
if(flags.inVivoMode)
{
if(!m_modeFlags.inVivoMode) // we're turning on in vivo mode
{
m_respModel.setInVivo(true);
}
}
else
{
if(m_modeFlags.inVivoMode) // we're turning off in vivo mode
{
m_respModel.setInVivo(false);
}
}
m_modeFlags = flags;
unsigned int numcyc = m_numCycles;
locker.unlock();
// qDebug() << "Mode flags set: " << flags.coordFrame
// << flags.tethered << flags.instTrackState
// << flags.instTrackMode << flags.EKFstate
// << flags.inVivoMode;
//emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_RESETBB_SUCCESS);
std::vector<double> modes(6);
modes.push_back(flags.coordFrame);
modes.push_back(flags.tethered);
modes.push_back(flags.instTrackState);
modes.push_back(flags.instTrackMode);
modes.push_back(flags.EKFstate);
modes.push_back(flags.inVivoMode);
emit logData(QTime::currentTime(), numcyc, CONTROLLER_MODES, modes);
}
void ControllerThread::setUSangle(double usAngle)
{
QMutexLocker locker(m_mutex);
usAngle *= piOverDeg180;
m_USangle = usAngle;
m_BT_CT = m_BT_CT.Identity();
m_BT_CT(0,0) = cos(usAngle);
m_BT_CT(1,1) = m_BT_CT(0,0);
m_BT_CT(0,1) = -sin(usAngle);
m_BT_CT(1,0) = -m_BT_CT(0,1);
m_BT_CT(2,3) = 30.0; // 21.7;
// m_BT_CT << cos(usAngle), -sin(usAngle), 0, 0,
// sin(usAngle), cos(usAngle), 0, 0,
// 0, 0, 1, 21.7;
std::cout << "New m_BT_CT:\n" << m_BT_CT.matrix() << std::endl;
//qInfo() << "US angle updated to" << m_USangle*deg180overPi << "degrees.";
std::vector<double> usang = {m_USangle*deg180overPi};
emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_USANGLE, usang);
}
void ControllerThread::initializeRespModel()
{
QMutexLocker locker(m_mutex);
// TODO : start sending data to m_respModel
m_respModelInitializing = true;
emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_RESP_MODEL_INIT_BEGIN);
}
void ControllerThread::re_initializeRespModel()
{
QMutexLocker locker(m_mutex);
m_respModel.resetModel();
m_respModelInitializing = true;
emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_RESP_MODEL_INIT_BEGIN);
}
void ControllerThread::stopRespModel()
{
QMutexLocker locker(m_mutex);
m_respModel.resetModel();
m_respModelInitializing = false;
emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_RESP_MODEL_STOPPED);
}
void ControllerThread::updateFutureSamples(int n)
{
if(n >= EDGE_EFFECT)
m_respModel.updateNfutureSamples(n);
else
qDebug() << "updateFutureSamples: n < EDGE_EFFECT";
}
void ControllerThread::startSweep(unsigned int nSteps_, double stepAngle_, double convLimit_, qint64 imgDuration_)
{
if(!m_sweep.getIsActive())
{
m_sweep = Sweep(nSteps_, stepAngle_, convLimit_, imgDuration_);
m_sweep.activate();
std::vector<double> sweepParams = {(double)nSteps_,
stepAngle_*deg180overPi,
convLimit_*deg180overPi,
(double)imgDuration_};
emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_SWEEP_START, sweepParams);
emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_SWEEP_STARTED);
}
else
qDebug() << "Already sweeping!";
}
void ControllerThread::abortSweep()
{
m_sweep.abort();
emit logEvent(SRC_CONTROLLER, LOG_INFO, QTime::currentTime(), CONTROLLER_SWEEP_ABORTED);
}
void ControllerThread::controlCycle()
{
//QMutexLocker locker(m_mutex); // already locked by calling function
if(m_isReady && m_keepControlling)
{
switch(m_modeFlags.coordFrame)
{
case COORD_FRAME_WORLD:
computeCoordFrameWorld();
break;
case COORD_FRAME_MOBILE:
computeCoordFrameMobile();
break;
default:
computeCoordFrameWorld();
qCritical() << "Unknown Coord Frame Mode! Defaulting to World";
break;
}
// handle sweep
if(m_sweep.getIsActive())
{
QString msg; std::vector<double> convd; std::vector<double> newDelPsi;
int status = m_sweep.update( m_dXYZPsi(3) );
switch (status) {
case SWEEP_INACTIVE: // shouldn't happen
break;
case SWEEP_WAIT_TO_CONVERGE: // ignore
break;
case SWEEP_CONVERGED:
// emit signal to turn on frame transmission
emit toggleFrameClientContinuousStreaming(true);
convd = {(double)m_sweep.getRemainingSteps()};
emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_SWEEP_CONVERGED, convd);
break;
case SWEEP_CONVERGED_ACQUIRING: // ignore
break;
case SWEEP_NEXT: // done collecting
// emit signal to turn off frame transmission
emit toggleFrameClientContinuousStreaming(false);
m_input_delPsi += m_sweep.getStepAngle();
newDelPsi = {m_input_delPsi};
emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_NEXT_SWEEP, newDelPsi);
msg = QString("%1 sweeps remaining.").arg(m_sweep.getRemainingSteps());
emit sendMsgToWidget(msg, 1); // update status text
break;
case SWEEP_DONE:
emit toggleFrameClientContinuousStreaming(false);
msg = QString("Sweep complete after %1 s.").arg(m_sweep.getOverallTimeElapsed()/1000);
emit sendMsgToWidget(msg, 1); // update status text
break;
default:
msg = QString("Sweep unknown state!");
emit sendMsgToWidget(msg, 1); // update status text
break;
}
}
// calculate gains
updateGains();
// feed into control_icra2016
Eigen::Matrix<double, 4, 2> jointsCurrAndTarget;
jointsCurrAndTarget = m_cathKin.control_icra2016(m_BB_CT_curTipPos, m_dXYZPsi, m_currGamma);
//jointsCurrAndTarget = m_cathKin.control_icra2016(m_BBmobile_CT, m_dXYZPsi, m_currGamma);
Eigen::Vector4d configCurr = m_cathKin.inverseKinematics(m_BB_CT_curTipPos, m_currGamma);
Eigen::Vector4d currTask = m_cathKin.configToTaskSpace(configCurr);
// Use SVM
#ifdef SVM_ON
std::vector<double> inputs = {configCurr(0),configCurr(1),configCurr(2),configCurr(3),
m_dXYZPsi(0),m_dXYZPsi(1),m_dXYZPsi(2),m_dXYZPsi(3)};
std::vector<double> predictions(4, 0);
SVMregression(&SVMregressionStackDataGlobal, &inputs[0], &predictions[0]);
#endif
// get relative motor counts
Eigen::Vector4d relQCs; // knob_tgt - knob_curr
relQCs(0) = (jointsCurrAndTarget(0,1) - jointsCurrAndTarget(0,0)) * m_gains.kTrans * 0.001 * EPOS_TRANS_RAD2QC;
relQCs(1) = (jointsCurrAndTarget(1,1) - jointsCurrAndTarget(1,0)) * m_gains.kPitch * EPOS_PITCH_RAD2QC;
relQCs(2) = (jointsCurrAndTarget(2,1) - jointsCurrAndTarget(2,0)) * m_gains.kYaw * EPOS_YAW_RAD2QC;
relQCs(3) = (jointsCurrAndTarget(3,1) - jointsCurrAndTarget(3,0)) * m_gains.kRoll * EPOS_ROLL_RAD2QC;
// Jacobian based
// Eigen::Vector4d configCurr = m_cathKin.inverseKinematics(m_BB_CT_curTipPos, m_currGamma);
// Eigen::Matrix<double, 6, 4> J = m_cathKin.JacobianNumeric(configCurr(0), configCurr(1), configCurr(2), configCurr(3));
// m_cathKin.dampedLeastSquaresStep(J, m_dXYZPsi);
// // *****
// Eigen::Vector4d targetTask(m_input_AbsXYZ(0), m_input_AbsXYZ(1), m_input_AbsXYZ(2), m_input_delPsi);
// Eigen::Vector4d targetConfig = m_cathKin.JacobianStep(currTask, targetTask, configCurr);
// Eigen::Vector4d currJoint = m_cathKin.configToJointSpace(configCurr);
// Eigen::Vector4d targetJoint = m_cathKin.configToJointSpace(targetConfig);
std::vector<double> task = {currTask(0),currTask(1),currTask(2),currTask(3)};
emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_CURR_TASK, task);
emit reportCurrentXYZPSI(XYZPSI(currTask(0),currTask(1),currTask(2),currTask(3)));
// // *****
// FIXME: 1/20/2017: Trying to fix BBmobile discrepancy
// // figure out distance from BBcurr to xy plane of BBfixed
// double ratio = m_BBfixed_BBmobile(2,3)/m_BBfixed_BBmobile(2,2);
// //Eigen::Vector4d offset_ = m_BBfixed_BBmobile.matrix().col(2)*ratio; // extend along z axis
// Eigen::Transform<double,3,Eigen::Affine> T_BBtrans_CT(m_BBmobile_CT);
// //T_BBtrans_CT.matrix().col(3) += offset_;
// T_BBtrans_CT(2,3) += ratio;
// Eigen::Vector4d configCurr = m_cathKin.inverseKinematics(T_BBtrans_CT, m_currGamma);
// Eigen::Vector4d currTask = m_cathKin.configToTaskSpace(configCurr);
//// Eigen::Vector4d tmp = {currTask(0),currTask(1),currTask(2),1.0};
//// tmp = (m_BBfixed_BBmobile * tmp).eval();
//// currTask.segment<3>(0) = tmp.segment<3>(0);
// currTask.segment<3>(0) = m_BB_CT_curTipPos.matrix().col(3).segment<3>(0);
//// Eigen::Vector4d tmp(m_input_AbsXYZ(0), m_input_AbsXYZ(1), m_input_AbsXYZ(2),1.0);
//// tmp = (m_BBfixed_BBmobile.inverse() * tmp).eval();
//// Eigen::Vector4d targetTask(tmp(0), tmp(1), tmp(2)+ratio, m_input_delPsi);
// Eigen::Vector4d targetTask(m_input_AbsXYZ(0), m_input_AbsXYZ(1), m_input_AbsXYZ(2), m_input_delPsi);
// Eigen::Vector4d targetConfig = m_cathKin.JacobianStep(currTask, targetTask, configCurr);
// Eigen::Vector4d currJoint = m_cathKin.configToJointSpace(configCurr);
// Eigen::Vector4d targetJoint = m_cathKin.configToJointSpace(targetConfig);
//// Eigen::Vector4d deltaConfig = m_cathKin.JacobianStepSingle(currTask, targetTask, configCurr);
//// Eigen::Vector4d currJoint = m_cathKin.configToJointSpace(Eigen::Vector4d::Zero());
//// Eigen::Vector4d targetJoint = m_cathKin.configToJointSpace(deltaConfig);
// // get relative motor counts
// Eigen::Vector4d relQCs; // knob_tgt - knob_curr
// relQCs(0) = (targetJoint(0) - currJoint(0)) * m_gains.kTrans * 0.001 * EPOS_TRANS_RAD2QC;
// relQCs(1) = (targetJoint(1) - currJoint(1)) * m_gains.kPitch * EPOS_PITCH_RAD2QC;
// relQCs(2) = (targetJoint(2) - currJoint(2)) * m_gains.kYaw * EPOS_YAW_RAD2QC;
// relQCs(3) = (targetJoint(3) - currJoint(3)) * m_gains.kRoll * EPOS_ROLL_RAD2QC;
// check if QCs are finite
if( !(isfinite(relQCs(0)) && isfinite(relQCs(1)) && isfinite(relQCs(2)) && isfinite(relQCs(3))) )
{
relQCs = relQCs.Zero();
}
std::vector<long> targetPos;
targetPos.push_back((long)relQCs(0));
targetPos.push_back((long)relQCs(1));
targetPos.push_back((long)relQCs(2));
targetPos.push_back((long)relQCs(3));
// limit QCs to EPOS velocity limits
// TODO : velocity is in RPMs, so we should convert this velocity to QCs/control cycle (= Ascension time = ~6ms)
if(abs(targetPos[0]) > EPOS_VELOCITY[0])
targetPos[0] = boost::math::copysign(EPOS_VELOCITY[0], targetPos[0]);
if(abs(targetPos[1]) > EPOS_VELOCITY[1])
targetPos[1] = boost::math::copysign(EPOS_VELOCITY[1], targetPos[1]);
if(abs(targetPos[2]) > EPOS_VELOCITY[2])
targetPos[2] = boost::math::copysign(EPOS_VELOCITY[2], targetPos[2]);
if(abs(targetPos[3]) > EPOS_VELOCITY[3])
targetPos[3] = boost::math::copysign(EPOS_VELOCITY[3], targetPos[3]);
printf("QCs - T: %ld P: %ld Y: %ld R: %ld\n", targetPos[0], targetPos[1], targetPos[2], targetPos[3]);
// TODO : check if the EPOS Servo Loop is active, if not, don't send commands
emit setEPOSservoTargetPos(targetPos, false); //relative
// emit logData(QTime::currentTime(), newData);
std::cout << QTime::currentTime().toString().toStdString() << " Cycle:" << m_numCycles << std::endl;
m_numCycles++;
}
else
{
m_currGamma = atan2(m_BBfixed_BBmobile(1,0), m_BBfixed_BBmobile(0,0));
Eigen::Vector4d configCurr = m_cathKin.inverseKinematics(m_BB_CT_curTipPos, m_currGamma);
Eigen::Vector4d currTask = m_cathKin.configToTaskSpace(configCurr);
std::vector<double> task = {currTask(0),currTask(1),currTask(2),currTask(3)};
emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_CURR_TASK, task);
}
}
void ControllerThread::computeCoordFrameWorld()
{
// Calculate the angle between the new x-axis and the original x-axis
Eigen::Transform<double,3,Eigen::Affine> T_CTorig_CT = m_BBfixed_CTorig.inverse()*m_BB_CT_curTipPos;
// This is the total amount of psy that has occurred at the tip since we started
double total_psy = atan2(T_CTorig_CT(1,0), T_CTorig_CT(0,0));
// Existing roll in the catheter handle
// Assuming the BB point has rotated about its Z axis, the amount of roll in
// the handle is calculated as the angle of rotation about the base z-axis.
// Here we calculate the angle between the new x-axis and the original
// x-axis.
m_currGamma = atan2(m_BBfixed_BBmobile(1,0), m_BBfixed_BBmobile(0,0));
//printf("Psy : %.3f Gamma : %.3f\n", total_psy * deg180overPi, m_currGamma * deg180overPi);
std::vector<double> psyGamma = {total_psy*deg180overPi, m_currGamma*deg180overPi};
emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_CURR_PSY_GAMMA, psyGamma);
switch(m_modeFlags.instTrackState)
{
case INST_TRACK_OFF:
// How much does the cath still need to move?
// calculate delta x,y,z,psi
// MATLAB code cycleinput5.m > lines 112-126
switch(m_modeFlags.tethered)
{
case MODE_TETHETERED:
m_deltaXYZPsiToTarget(0) = m_input_AbsXYZ(0) - m_BBfixed_CTorig(0,3);
m_deltaXYZPsiToTarget(1) = m_input_AbsXYZ(1) - m_BBfixed_CTorig(1,3);
m_deltaXYZPsiToTarget(2) = m_input_AbsXYZ(2) - m_BBfixed_CTorig(2,3);
break;
case MODE_RELATIVE:
m_deltaXYZPsiToTarget(0) = m_input_RelXYZ(0);
m_deltaXYZPsiToTarget(1) = m_input_RelXYZ(1);
m_deltaXYZPsiToTarget(2) = m_input_RelXYZ(2);
break;
default:
m_deltaXYZPsiToTarget(0) = m_input_AbsXYZ(0) - m_BBfixed_CTorig(0,3);
m_deltaXYZPsiToTarget(1) = m_input_AbsXYZ(1) - m_BBfixed_CTorig(1,3);
m_deltaXYZPsiToTarget(2) = m_input_AbsXYZ(2) - m_BBfixed_CTorig(2,3);
qCritical() << "Unknown Mode! Defaulting to tethered.";
break;
}
m_deltaXYZPsiToTarget(3) = m_input_delPsi;
m_dXYZPsi(0) = m_deltaXYZPsiToTarget(0) - (m_BB_CT_curTipPos(0,3) - m_BBfixed_CTorig(0,3));
m_dXYZPsi(1) = m_deltaXYZPsiToTarget(1) - (m_BB_CT_curTipPos(1,3) - m_BBfixed_CTorig(1,3));
m_dXYZPsi(2) = m_deltaXYZPsiToTarget(2) - (m_BB_CT_curTipPos(2,3) - m_BBfixed_CTorig(2,3));
m_dXYZPsi(3) = m_deltaXYZPsiToTarget(3) - total_psy;
break;
case INST_TRACK_ON:
// World, IT
switch(m_modeFlags.instTrackMode)
{
case INST_TRACK_POSITION:
// World, IT, Position
switch(m_modeFlags.EKFstate)
{
case EKF_OFF: // World, IT, Position
m_dXYZPsi(0) = m_BB_targetPos(0,3) - m_BB_CT_curTipPos(0,3);
m_dXYZPsi(1) = m_BB_targetPos(1,3) - m_BB_CT_curTipPos(1,3);
m_dXYZPsi(2) = m_BB_targetPos(2,3) - m_BB_CT_curTipPos(2,3);
m_dXYZPsi(3) = 0;
break;
case EKF_ON: // World, IT, Position, EKF
// dx = T_BBfixed_Instr_EKF_x - T_BBfixed_CT(1,4);
// dy = T_BBfixed_Instr_EKF_y - T_BBfixed_CT(2,4);
// dz = T_BBfixed_Instr_EKF_z - T_BBfixed_CT(3,4);
// dpsi = 0;
// TODO : add EKF info here
m_dXYZPsi(0) = m_BB_targetPos(0,3) - m_BB_CT_curTipPos(0,3);
m_dXYZPsi(1) = m_BB_targetPos(1,3) - m_BB_CT_curTipPos(1,3);
m_dXYZPsi(2) = m_BB_targetPos(2,3) - m_BB_CT_curTipPos(2,3);
m_dXYZPsi(3) = 0;
break;
default:
m_dXYZPsi(0) = m_BB_targetPos(0,3) - m_BB_CT_curTipPos(0,3);
m_dXYZPsi(1) = m_BB_targetPos(1,3) - m_BB_CT_curTipPos(1,3);
m_dXYZPsi(2) = m_BB_targetPos(2,3) - m_BB_CT_curTipPos(2,3);
m_dXYZPsi(3) = 0;
qCritical() << "Unknown EKFstate! Defaulting to EKF Off.";
break;
}
break;
// World, IT, Position ends
case INST_TRACK_IMAGER:
// World, IT, Imager
{
Eigen::Vector3d objectXYZ;
switch(m_modeFlags.EKFstate)
{
case EKF_OFF: // World, IT, Imager
objectXYZ = m_BB_targetPos.matrix().col(3).segment(0,3);
break;
case EKF_ON: // World, IT, Imager, EKF
// object_loc = [T_BBfixed_Instr_EKF_x;
// T_BBfixed_Instr_EKF_y;
// T_BBfixed_Instr_EKF_z];
// TODO : add EKF info here
objectXYZ = m_BB_targetPos.matrix().col(3).segment(0,3);
break;
default:
objectXYZ = m_BB_targetPos.matrix().col(3).segment(0,3);
qCritical() << "Unknown EKFstate! Defaulting to EKF Off.";
break;
}
m_dXYZPsi(0) = m_input_AbsXYZ(0) - m_BB_CT_curTipPos(0,3);
m_dXYZPsi(1) = m_input_AbsXYZ(1) - m_BB_CT_curTipPos(1,3);
m_dXYZPsi(2) = m_input_AbsXYZ(2) - m_BB_CT_curTipPos(2,3);
m_dXYZPsi(3) = computeSweep(m_BB_CT_curTipPos, objectXYZ);
}
break;
// World, IT, Imager ends
default:
break;
}
break;
// World, IT ends
default:
break;
}
//printf("dx : %.3f dy : %.3f dz : %.3f dpsi : %.3f\n", m_dXYZPsi(0), m_dXYZPsi(1), m_dXYZPsi(2), m_dXYZPsi(3)* deg180overPi);
std::vector<double> dxyzpsi = {m_dXYZPsi(0), m_dXYZPsi(1), m_dXYZPsi(2), m_dXYZPsi(3)*deg180overPi};
emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_DXYZPSI, dxyzpsi);
}
void ControllerThread::computeCoordFrameMobile()
{
//% Use models to reconstruct one 4x4 matrix at this time point
// % Tip
// T_BBfixed_CTtraj(1:3,1:3) = convert_eaa_3x3(reshape(BBfixed_CTtraj_model(4:7),1,4));
// T_BBfixed_CTtraj(1,4) = BBfixed_CTtraj_model(1);
// T_BBfixed_CTtraj(2,4) = BBfixed_CTtraj_model(2);
// T_BBfixed_CTtraj(3,4) = BBfixed_CTtraj_model(3);
// T_BBfixed_CTtraj(4,1:4) = [0 0 0 1];
EigenVector7d CT_des = m_respModel.getT_BBfixed_CT_des();
EigenVector7d CT_future_des = m_respModel.getT_BBfixed_CTtraj_future_des();
EigenVector7d BB_des = m_respModel.getT_BBfixed_BB_des();
Eigen::AngleAxis<double> rotCTdes(CT_des(6), Eigen::Vector3d(CT_des(3),CT_des(4),CT_des(5)));
Eigen::Translation3d transCTdes(CT_des(0),CT_des(1),CT_des(2));
EigenAffineTransform3d T_BBfixed_CT_des = transCTdes * rotCTdes;
//printf("transCTdes: x %.3f y %.3f z %.3f\n",CT_des(0),CT_des(1),CT_des(2));
Eigen::AngleAxis<double> rotCTtraj(CT_future_des(6), Eigen::Vector3d(CT_future_des(3),CT_future_des(4),CT_future_des(5)));
Eigen::Translation3d transCTtraj(CT_future_des(0),CT_future_des(1),CT_future_des(2));
EigenAffineTransform3d T_BBfixed_CTtraj_future_des = transCTtraj * rotCTtraj;
Eigen::AngleAxis<double> rotBBdes(BB_des(6), Eigen::Vector3d(BB_des(3),BB_des(4),BB_des(5)));
Eigen::Translation3d transBBdes(BB_des(0),BB_des(1),BB_des(2));
EigenAffineTransform3d T_BBfixed_BB_des = transBBdes * rotBBdes;
//% Rotation about the z-axis of the catheter tip.
// % Here we calculate the angle between the current x-axis and the
// % pure-breathing x-axis.
// T_CTtraj_CT=inv(T_BBfixed_CTtraj)*T_BBfixed_CT;
EigenAffineTransform3d T_CTtraj_CT = T_BBfixed_CT_des.inverse() * m_BB_CT_curTipPos;
// % This is the total amount of psy that has occurred at the tip compared
// % with pure breathing
// total_psy=atan2(T_CTtraj_CT(2,1),T_CTtraj_CT(1,1));
double total_psy = atan2(T_CTtraj_CT(1,0), T_CTtraj_CT(0,0));
//% Existing roll in the catheter handle, from Base_Roll which was a separate
// % function but is now incorporated into here
// T_BBtraj_BBmob = inv(T_BBfixed_BBtraj) * T_BBfixed_BBmob;
// % Assuming the BB point has rotated about its Z axis, the amount of roll in
// % the handle is calculated as the angle of rotation about the base z-axis.
// % Here we calculate the angle between the new x-axis and the trajectory
// % x-axis.
// gamma=atan2(T_BBtraj_BBmob(2,1),T_BBtraj_BBmob(1,1));
EigenAffineTransform3d T_BBtraj_BBmob = T_BBfixed_BB_des.inverse() * m_BBfixed_BBmobile;
m_currGamma = atan2(T_BBtraj_BBmob(1,0), T_BBtraj_BBmob(0,0));
//printf("Psy : %.3f Gamma : %.3f\n", total_psy * deg180overPi, m_currGamma * deg180overPi);
std::vector<double> psyGamma = {total_psy*deg180overPi, m_currGamma*deg180overPi};
emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_CURR_PSY_GAMMA, psyGamma);
//% Get BT w.r.t. mobile BB, rather than fixed BB
// T_BBmob_BT = inv(T_BBfixed_BBmob)*T_BBfixed_CT*inv(T_BT_CT);
EigenAffineTransform3d T_BBmob_BT = m_BBfixed_BBmobile.inverse() * m_BBfixed_CTorig * m_BT_CT.inverse();
//% Initialize even if EKF is off
// T_BBfixed_CT_future = zeros(1,16);
EigenAffineTransform3d T_BBfixed_CT_future = EigenAffineTransform3d::Identity();
switch(m_modeFlags.instTrackState)
{
case INST_TRACK_OFF:
switch(m_modeFlags.tethered)
{
case MODE_TETHETERED:
// TODO : % **** this is not implemented correctly right now
// % If the cath is tethered to a point... fix this later
// % Right now I'm just copying the relative case over here in case I
// % hit the wrong button by accident
m_dXYZPsi(0) = m_input_AbsXYZ(0) + T_BBfixed_CT_des(0,3) - m_BB_CT_curTipPos(0,3);
m_dXYZPsi(1) = m_input_AbsXYZ(1) + T_BBfixed_CT_des(1,3) - m_BB_CT_curTipPos(1,3);
m_dXYZPsi(2) = m_input_AbsXYZ(2) + T_BBfixed_CT_des(2,3) - m_BB_CT_curTipPos(2,3);
m_dXYZPsi(3) = m_input_delPsi - total_psy;
break;
case MODE_RELATIVE:
//% If the cath is being told to do relative adjustments then that's
// % like adding the relative adjustments to the Traj point. Then I
// % just take the difference between where I am now and the relative
// % change from the Traj point.
// dx = inputbox_delt_x + T_BBfixed_CTtraj(1,4) - T_BBfixed_CT(1,4);
// dy = inputbox_delt_y + T_BBfixed_CTtraj(2,4) - T_BBfixed_CT(2,4);
// dz = inputbox_delt_z + T_BBfixed_CTtraj(3,4) - T_BBfixed_CT(3,4);
// dpsi = inputbox_delt_psi - total_psy;
m_dXYZPsi(0) = m_input_AbsXYZ(0) + T_BBfixed_CT_des(0,3) - m_BB_CT_curTipPos(0,3);
m_dXYZPsi(1) = m_input_AbsXYZ(1) + T_BBfixed_CT_des(1,3) - m_BB_CT_curTipPos(1,3);
m_dXYZPsi(2) = m_input_AbsXYZ(2) + T_BBfixed_CT_des(2,3) - m_BB_CT_curTipPos(2,3);
m_dXYZPsi(3) = m_input_delPsi - total_psy;
break;
default:
qCritical() << "Unknown Mode! MOBILE - INST_TRACK_OFF.";
break;
}
break;
case INST_TRACK_ON: // Mobile, IT then
switch(m_modeFlags.instTrackMode)
{
case INST_TRACK_POSITION:
// Mobile, IT, Position
switch(m_modeFlags.EKFstate)
{
case EKF_OFF: // Mobile, IT, Position
m_dXYZPsi(0) = m_BB_targetPos(0,3) - m_BB_CT_curTipPos(0,3);
m_dXYZPsi(1) = m_BB_targetPos(1,3) - m_BB_CT_curTipPos(1,3);
m_dXYZPsi(2) = m_BB_targetPos(2,3) - m_BB_CT_curTipPos(2,3);
m_dXYZPsi(3) = 0.0;
break;
case EKF_ON: // Mobile, IT, Position, EKF
T_BBfixed_CT_future = T_BBfixed_CTtraj_future_des * T_CTtraj_CT;
// dx = T_BBfixed_Instr_EKF_x - T_BBfixed_CT_future(1,4);
// dy = T_BBfixed_Instr_EKF_y - T_BBfixed_CT_future(2,4);
// dz = T_BBfixed_Instr_EKF_z - T_BBfixed_CT_future(3,4);
// dpsi = 0;
// TODO : add EKF info here
// this is doing inst track with predicted CT
m_dXYZPsi(0) = m_BB_targetPos(0,3) - T_BBfixed_CT_future(0,3);
m_dXYZPsi(1) = m_BB_targetPos(1,3) - T_BBfixed_CT_future(1,3);
m_dXYZPsi(2) = m_BB_targetPos(2,3) - T_BBfixed_CT_future(2,3);
m_dXYZPsi(3) = 0;
break;
default:
m_dXYZPsi(0) = m_BB_targetPos(0,3) - m_BB_CT_curTipPos(0,3);
m_dXYZPsi(1) = m_BB_targetPos(1,3) - m_BB_CT_curTipPos(1,3);
m_dXYZPsi(2) = m_BB_targetPos(2,3) - m_BB_CT_curTipPos(2,3);
m_dXYZPsi(3) = 0.0;
qCritical() << "Unknown EKFstate! Mobile, IT, Position.";
break;
}
break;
// Mobile, IT, Position ends
case INST_TRACK_IMAGER:
// Mobile, IT, Imager
{
Eigen::Vector3d objectXYZ;
switch(m_modeFlags.EKFstate)
{
case EKF_OFF: // Mobile, IT, Imager
objectXYZ = m_BB_targetPos.matrix().col(3).segment(0,3);
m_dXYZPsi(3) = computeSweep(m_BB_CT_curTipPos, objectXYZ);
break;
case EKF_ON: // Mobile, IT, Imager, EKF
// % Take future CT traj point and transform by the same
// % matrix that transforms from current CT traj to current
// % CT. This is the best estimate that we can get of where
// % the CT will be in the future.
T_BBfixed_CT_future = T_BBfixed_CTtraj_future_des * T_CTtraj_CT;
// object_loc = [T_BBfixed_Instr_EKF_x;
// T_BBfixed_Instr_EKF_y;
// T_BBfixed_Instr_EKF_z];
// TODO: add Kalman here
objectXYZ = m_BB_targetPos.matrix().col(3).segment(0,3);
m_dXYZPsi(3) = computeSweep(T_BBfixed_CT_future, objectXYZ);
break;
default:
objectXYZ = m_BB_targetPos.matrix().col(3).segment(0,3);
m_dXYZPsi(3) = computeSweep(m_BB_CT_curTipPos, objectXYZ);
qCritical() << "Unknown EKFstate! Defaulting to EKF Off.";
break;
}
m_dXYZPsi(0) = T_BBfixed_CT_des(0,3) - m_BB_CT_curTipPos(0,3);
m_dXYZPsi(1) = T_BBfixed_CT_des(1,3) - m_BB_CT_curTipPos(1,3);
m_dXYZPsi(2) = T_BBfixed_CT_des(2,3) - m_BB_CT_curTipPos(2,3);
}
break;
// Mobile, IT, Imager ends
default:
qCritical() << "Unknown! Mobile, IT.";
break;
}
break;
default:
break;
}
//printf("m_dXYZPsi - x %.3f y %.3f z %.3f psi %.3f\n", m_dXYZPsi(0), m_dXYZPsi(1), m_dXYZPsi(2), m_dXYZPsi(3)*deg180overPi);
std::vector<double> dxyzpsi = {m_dXYZPsi(0), m_dXYZPsi(1), m_dXYZPsi(2), m_dXYZPsi(3)*deg180overPi};
emit logData(QTime::currentTime(), m_numCycles, CONTROLLER_DXYZPSI, dxyzpsi);
}
double ControllerThread::computeSweep(const Eigen::Transform<double,3,Eigen::Affine> &currT, const Eigen::Vector3d &objXYZ)
{
Eigen::Vector3d currLoc = currT.matrix().col(3).segment(0,3); // current location catheter xyz
Eigen::Vector3d y_1 = currT.matrix().col(1).segment(0,3); // normal to the catheter's XZ plane
// distance from the current point to the obj
double d_obj_cur = (objXYZ - currLoc).norm();
// distance from object to the catheter's XZ plane
double d_obj_plane = y_1.dot(objXYZ - currLoc) / y_1.norm();
double ratio = d_obj_plane / d_obj_cur;
if(abs(ratio) > 1.0)
ratio = ratio / abs(ratio); // otherwise, asin will be invalid
double psy = 0.0;
if(d_obj_cur > 0.0001)
psy = asin(ratio); // angle between object and the catheter's XZ plane
return psy;
}
void ControllerThread::updateGains()
{
// Calculate distance from target
double distError = m_dXYZPsi.segment(0,3).norm();
double angleError = m_dXYZPsi(3);
// Update gains
double kPitch = 0.0, kYaw = 0.0, kRoll = 0.0, kTrans = 0.0;
if(distError < m_convLimits.posMin)
{
kPitch = m_gains.kPitchMin;
kYaw = m_gains.kYawMin;
kTrans = m_gains.kTransMin;
}
else if(distError > m_convLimits.posMax)
{
kPitch = m_gains.kPitchMax;
kYaw = m_gains.kYawMax;
kTrans = m_gains.kTransMax;
}
else
{
double tPos = (distError - m_convLimits.posMin)/(m_convLimits.posMax - m_convLimits.posMin);
kPitch = lerp(m_gains.kPitchMin, m_gains.kPitchMax, tPos);
kYaw = lerp(m_gains.kYawMin, m_gains.kYawMax, tPos);
kTrans = lerp(m_gains.kTransMin, m_gains.kTransMax, tPos);
}
if(angleError < m_convLimits.angleMin)
{
kRoll = m_gains.kRollMin;
}
else if(angleError > m_convLimits.angleMax)
{
kRoll = m_gains.kRollMax;
}
else
{
double tAng = (angleError - m_convLimits.angleMin)/(m_convLimits.angleMax - m_convLimits.angleMin);
kRoll = lerp(m_gains.kRollMin, m_gains.kRollMax, tAng);
}
m_gains.kRoll = kRoll;
m_gains.kPitch = kPitch;
m_gains.kYaw = kYaw;
m_gains.kTrans = kTrans;
std::cout << "Gains - kR: " << kRoll << " kP: " << kPitch << " kY: " << kYaw << " kT: " << kTrans << std::endl;
}
// ----------------
// ACCESSORS
// ----------------
// ----------------
// HELPER FUNCTIONS
// ----------------
static void Transform_From_EMreading(DOUBLE_POSITION_MATRIX_TIME_Q_RECORD &input, Eigen::Transform<double,3,Eigen::Affine> &output)
{
// QElapsedTimer elTimer;
// elTimer.start();
Eigen::Translation3d trans(input.x, input.y, input.z);
Eigen::Matrix3d rot;
rot << input.s[0][0], input.s[0][1], input.s[0][2],
input.s[1][0], input.s[1][1], input.s[1][2],
input.s[2][0], input.s[2][1], input.s[2][2];
// Eigen::Matrix3d rot;
// rot << input.s[0][0], input.s[1][0], input.s[2][0],
// input.s[0][1], input.s[1][1], input.s[2][1],
// input.s[0][2], input.s[1][2], input.s[2][2];
output = trans * rot;
// std::cout << output.matrix() << std::endl;
// qint64 elNsec = elTimer.nsecsElapsed();
// qDebug() << "Nsec elapsed:" << elNsec;
}
Eigen::Transform<double,3,Eigen::Affine> ControllerThread::readTransformFromTxtFile(const QString &path)
{
Eigen::Transform<double,3,Eigen::Affine> tform;
QFile file(path);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "File doesn't exist:" << path << " !!!";
return tform;
}
QTextStream in(&file);
for(size_t i = 0; i < 3; i++)
{
for(size_t j = 0; j < 4; j++)
{
if(!in.atEnd())
{
in >> tform(i,j);
}
else
{
qDebug() << "File ended prematurely at element (" << i << "," << j << "):" << path << " !!!";
return tform;
}
}
}
// convert from meters to mm
tform.translation() *= 1000.0;
std::cout << "Loaded:" << path.toStdString().c_str() << std::endl;
std::cout << tform.matrix() << std::endl;
return tform;
}
void ControllerThread::loadConstants()
{
m_BB_Box = readTransformFromTxtFile(QStringLiteral("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\Constants\\C_T_BB_Box.txt"));
m_STm_BT = readTransformFromTxtFile(QStringLiteral("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\Constants\\C_T_STm_BT.txt"));
m_BT_CT = readTransformFromTxtFile(QStringLiteral("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\Constants\\C_T_BT_CT.txt"));
m_BB_SBm = readTransformFromTxtFile(QStringLiteral("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\Constants\\C_T_BB_SBm.txt"));
m_ISm_INSTR = readTransformFromTxtFile(QStringLiteral("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\Constants\\C_T_ISm_INSTR.txt"));
}
inline const QString getCurrTimeStr()
{
return QTime::currentTime().toString("HH.mm.ss.zzz");
}
inline const QString getCurrDateTimeStr()
{
return QDateTime::currentDateTime().toString("dd/MM/yyyy - hh:mm:ss.zzz");
}
| 52,543 | C++ | 38.358801 | 149 | 0.586377 |
adegirmenci/HBL-ICEbot/ControllerWidget/sweep.h | #ifndef SWEEP_H
#define SWEEP_H
#include <QObject>
#include <QElapsedTimer>
#include "kinematics_4dof.h"
#include "../icebot_definitions.h"
class Sweep
{
public:
explicit Sweep(unsigned int nSteps_ = 30,
double stepAngle_ = 2.0*piOverDeg180,
double convLimit_ = 1.0*piOverDeg180,
qint64 imgDuration_ = 3000);
void activate();
void abort() {reset();}
void reset();
int update(const double currPsy);
double getStepAngle() { return stepAngle; }
unsigned int getRemainingSteps() { return remSteps; }
bool getIsConverged() { return isConverged; }
bool getIsActive() { return isActive; }
unsigned int getNumControlCycles() { return nControlCycles; }
qint64 getOverallTimeElapsed() { return overallTimer.elapsed(); }
private:
bool isActive; // are we currently sweeping?
unsigned int nControlCycles; // how many control cycles have elapsed since the beginning of this sweep
unsigned int nSteps; // number of desired steps (angle increments)
unsigned int remSteps; // remaining number of steps (angle increments)
double stepAngle; // angle increment between sweps
double convergenceLimit; // convergence criterion (CURR_PSY angle from 0)
bool isConverged; // did we converge?
qint64 imagingDuration; // how many ms to image for at current angle once converged
QElapsedTimer timer; // keep track of ms spent at current angle after convergence
QElapsedTimer overallTimer;
};
#endif // SWEEP_H
| 1,539 | C | 33.999999 | 106 | 0.692008 |
adegirmenci/HBL-ICEbot/ControllerWidget/controllerthread.h | #ifndef CONTROLLERTHREAD_H
#define CONTROLLERTHREAD_H
#include <QObject>
#include <QMutex>
#include <QMutexLocker>
#include <QThread>
#include <QString>
#include <QTime>
#include <QTimer>
#include <QElapsedTimer>
#include <QFile>
#include <QDebug>
#include <QSharedPointer>
#include <QAtomicInt>
#include <atomic>
#include <vector>
#include <memory>
// included in kinematics_4dof.h
//#include <Eigen/Dense>
//#include <Eigen/SVD>
//#include <Eigen/StdVector>
//#include <Eigen/Geometry>
#include <iostream>
//#include <fstream>
//#include <iterator>
#include "kinematics_4dof.h"
#include "filtfilt.h"
#include "cyclicmodel.h"
#include "../icebot_definitions.h"
#include "../AscensionWidget/3DGAPI/ATC3DG.h"
#include "gainswidget.h"
#include "sweep.h"
// MATLAB SVM Include Files
//#define SVM_ON
#ifdef SVM_ON
#include <cmath>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include "SVMregression_types.h"
#include "SVMregression.h"
#include "SVMregression_initialize.h"
#include "SVMregression_terminate.h"
static SVMregressionStackData SVMregressionStackDataGlobal;
#endif
struct ModeFlags
{
int coordFrame;
int tethered;
int instTrackState;
int instTrackMode;
int EKFstate;
int inVivoMode;
explicit ModeFlags(int cF = COORD_FRAME_WORLD,
int tth = MODE_TETHETERED,
int iTS = INST_TRACK_OFF,
int iTM = INST_TRACK_POSITION,
int EKFs = EKF_OFF,
int iVM = IN_VIVO_OFF) :
coordFrame(cF), tethered(tth), instTrackState(iTS), instTrackMode(iTM), EKFstate(EKFs), inVivoMode(iVM)
{ }
};
struct XYZPSI
{
double x;
double y;
double z;
double psi;
explicit XYZPSI(double x_ = 0.0, double y_ = 0.0, double z_ = 0.0, double psi_ = 0.0):
x(x_), y(y_), z(z_), psi(psi_)
{ }
};
Q_DECLARE_METATYPE(ModeFlags)
Q_DECLARE_METATYPE(EigenVectorFiltered)
Q_DECLARE_METATYPE(XYZPSI)
class ControllerThread : public QObject
{
Q_OBJECT
public:
explicit ControllerThread(QObject *parent = 0);
~ControllerThread();
signals:
void statusChanged(int event);
void logData(QTime timeStamp,
int loopIdx,
int dataType,
std::vector<double> data);
void logEvent(int source, // LOG_SOURCE
int logType, // LOG_TYPES
QTime timeStamp,
int eventID); // FRMGRAB_EVENT_IDS
void logEventWithMessage(int source, // LOG_SOURCE
int logType, // LOG_TYPES
QTime timeStamp,
int eventID, // FRMGRAB_EVENT_IDS
QString &message);
void sendMsgToWidget(QString msg, int destination);
void logError(int source, // LOG_SOURCE
int logType, // LOG_TYPES
QTime timeStamp,
int errCode, // FRMGRAB_ERROR_CODES
QString message);
void finished(); // emit upon termination
void setEPOSservoTargetPos(std::vector<long> targetPos, bool moveAbsOrRel);
void send_CT_toFrameClient(std::vector<double> T_BB_CT_curTipPos, double time);
void sendDataToRespModelWidget(int numSamples,
bool isTrained,
bool inVivoMode,
double omega0);
void reportCurrentXYZPSI(XYZPSI currXYZPSI);
void toggleFrameClientContinuousStreaming(bool turnOn);
public slots:
void setEpoch(const QDateTime &epoch);
void printThreadID();
void receiveEMdata(QTime timeStamp,
int sensorID,
DOUBLE_POSITION_MATRIX_TIME_Q_RECORD data);
void receiveLatestEMreading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> readings);
void updateJointSpaceCommand(double pitch, double yaw, double roll, double trans);
void updateConfigSpaceCommand(double alpha, double theta, double gamma, double d);
void updateTaskSpaceCommand(double x, double y, double z, double delPsi, bool isAbsolute);
void resetBB();
void startControlCycle(); // start timer
void stopControlCycle(); // stop timer
const bool isControlling() { return m_keepControlling; }
void setGains(GainsPYRT gains);
void setLimits(ConvergenceLimits limits);
void setModeFlags(ModeFlags flags);
void setUSangle(double usAngle);
void initializeRespModel();
void re_initializeRespModel();
void stopRespModel();
void updateFutureSamples(int n);
void startSweep(unsigned int nSteps_,
double stepAngle_,
double convLimit_,
qint64 imgDuration_);
void abortSweep();
private slots:
void controlCycle(); // on a timer
private:
// Instead of using "m_mutex.lock()"
// use "QMutexLocker locker(&m_mutex);"
// this will unlock the mutex when the locker goes out of scope
mutable QMutex *m_mutex;
// Timer for calling controlLoop every xxx msecs
QTimer *m_timer;
// Epoch for time stamps
// During InitializeController(), check 'isEpochSet' flag
// If Epoch is set externally from MainWindow, the flag will be true
// Otherwise, Epoch will be set internally
QDateTime m_epoch;
bool m_isEpochSet;
// Flag to indicate if Controller is ready
// True if InitializeController was successful
bool m_isReady;
// Flag to tell that we are still controlling
bool m_keepControlling;
// Flag to abort actions
bool m_abort;
const int m_prec = 4; // precision for print operations
// latest reading
std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> m_prevReading;
std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> m_latestReading;
// transforms
Eigen::Transform<double,3,Eigen::Affine> m_BB_Box,
m_Box_SBm,
m_STm_BT,
m_BT_CT,
m_BB_CT_curTipPos,
m_BBfixed_CTorig,
m_BB_SBm,
m_BBfixed_BBmobile,
m_BBmobile_BT,
m_BBmobile_CT,
m_curTipPos,
m_ISm_INSTR,
m_basTipPos_fixed,
m_basTipPos_mobile,
m_Box_BBfixed,
m_Box_BBmobile,
m_targetPos,
m_BB_targetPos,
m_currChest;
// delta x,y,z,psi to target
Eigen::Vector3d m_input_AbsXYZ, m_input_RelXYZ;
double m_input_delPsi;
Eigen::Vector4d m_dXYZPsi, m_deltaXYZPsiToTarget;
double m_currGamma;
public:
// Respiration Model -- this is public for now, change later
CyclicModel m_respModel;
private:
bool m_respModelInitializing;
// gains
GainsPYRT m_gains;
// convergence limits
ConvergenceLimits m_convLimits;
// Mode Flags
ModeFlags m_modeFlags;
// US angle
double m_USangle;
// keep track of number of control cycles
// an atomic variable alleviates the need to use mutexes during mutation
std::atomic<unsigned int> m_numCycles;
// Kinematics oject
Kinematics_4DOF m_cathKin;
// Sweep object
Sweep m_sweep;
// --- Private methods ---
void computeCoordFrameWorld(); // Coord Frame: world
void computeCoordFrameMobile(); // Coord Frame: mobile
double computeSweep(const Eigen::Transform<double,3,Eigen::Affine> &currT, const Eigen::Vector3d &objXYZ);
void updateGains(); // Update gains
Eigen::Transform<double,3,Eigen::Affine> readTransformFromTxtFile(const QString &path);
void loadConstants();
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
// ----------------
// HELPER FUNCTIONS
// ----------------
inline const QString getCurrTimeStr();
inline const QString getCurrDateTimeStr();
static void Transform_From_EMreading(DOUBLE_POSITION_MATRIX_TIME_Q_RECORD &input, Eigen::Transform<double,3,Eigen::Affine> &output);
#endif // CONTROLLERTHREAD_H
| 8,500 | C | 29.912727 | 132 | 0.594471 |
adegirmenci/HBL-ICEbot/ControllerWidget/cyclicmodel.cpp | #include "cyclicmodel.h"
CyclicModel::CyclicModel(QObject *parent) :
QObject(parent)
{
resetModel();
std::cout << "--- Initialized CyclicModel. ---" << std::endl;
}
CyclicModel::~CyclicModel()
{
}
void CyclicModel::resetModel()
{
// ------------------ EMPTY BUFFERS ------------------ //
// UNFILTERED DATA
m_BBfixed_CT .clear();
m_BBfixed_Instr.clear();
m_BBfixed_BB .clear();
m_Bird4 .clear();
m_Bird4_new.clear();
// TIME DATA
m_timeData_init.clear();
m_timeData_new .clear();
// ------------------ INIT BUFFERS ------------------ //
// UNFILTERED DATA
m_BBfixed_CT .reserve(N_SAMPLES); // this stores all of the incoming CT points
m_BBfixed_Instr.reserve(N_SAMPLES); // this stores all of the incoming instr_x points
m_BBfixed_BB .reserve(N_SAMPLES); // this stores all of the incoming BB points
m_Bird4 .reserve(N_SAMPLES); // this remains constant after initialization
m_Bird4_new.resize(N_SAMPLES, 0.0); // most recent chest tracker data
// FILTERED DATA
m_BBfixed_CT_filtered = EigenMatrixFiltered::Zero(N_FILTERED,7); // this remains constant after initialization
m_BBfixed_BB_filtered = EigenMatrixFiltered::Zero(N_FILTERED,7); // this remains constant after initialization
m_Bird4_filtered = EigenVectorFiltered::Zero(N_FILTERED); // this remains constant after initialization
m_Bird4_filtered_new = EigenVectorFiltered::Zero(N_FILTERED); // most recent filtered chest tracker data
m_breathSignalFromModel = EigenVectorFiltered::Zero(N_FILTERED);
// ***CURRENT*** RECTANGULAR COMPONENTS
m_BBfixed_CT_rectangular = EigenMatrixRectangular::Zero(N_RECT,7); // 7 components: x,y,z,xaxis,yaxis,zaxis,angle
m_BBfixed_BB_rectangular = EigenMatrixRectangular::Zero(N_RECT,7); // 7 components: x,y,z,xaxis,yaxis,zaxis,angle
m_Bird4_rectangular = EigenVectorRectangular::Zero(N_RECT); // 1 component : x (benchtop) or -z (in vivo)
// ***CURRENT*** POLAR COMPONENTS
m_BBfixed_CT_polar = EigenMatrixPolar::Zero(N_POLAR,7); // 7 components: x,y,z,xaxis,yaxis,zaxis,angle
m_BBfixed_BB_polar = EigenMatrixPolar::Zero(N_POLAR,7); // 7 components: x,y,z,xaxis,yaxis,zaxis,angle
m_Bird4_polar = EigenVectorPolar::Zero(N_POLAR); // 1 component : x (benchtop) or -z (in vivo)
// TIME DATA
m_timeData_init.reserve(N_SAMPLES); // stores the time vector for the model initialization observations
m_timeData_new .resize(N_SAMPLES, 0.0); // stores time for the most recent observations
m_nFutureSamples = 2*EDGE_EFFECT;
m_omega0 = 2.*pi/BREATH_RATE; // frequency [rad/sec]
m_omega0_init = 2.*pi/BREATH_RATE;
m_periods.clear(); // averaging filter for period
m_numSamples = 0; // number of observations added IN TOTAL
m_isTrained = false; // is the model trained
m_lastTrainingTimestamp = 0; // when last training was performed
m_isInVivo = true; // are we in IN VIVO mode
}
void CyclicModel::addTrainingObservation(const EigenAffineTransform3d &T_BB_CT_curTipPos,
const EigenAffineTransform3d &T_BB_targetPos,
const EigenAffineTransform3d &T_Box_BBmobile,
const EigenAffineTransform3d &T_BB_Box,
const EigenAffineTransform3d &T_Bird4,
const double sampleTime)
{
// em_tip = m_BB_CT_curTipPos // m_BB_CT_curTipPos is the current CT point w.r.t. BBfixed
// em_instr = m_BB_targetPos // m_BB_targetPos is the current INST point w.r.t. BBfixed
// local_Box_BBmobile = m_Box_BBmobile // m_Box_BBmobile is the current BB point w.r.t. Box
// local_BB_Box = m_BB_Box // m_BB_Box is the current Box point w.r.t. BBfixed
// local_Bird4 = m_Bird4 // 4th EM tracker
// local_BB_Box * local_Box_BBmobile = em_base; // T_BB_Box * T_Box_BBmobile = T_BBfixed_BBmobile
// BBfixed_CT.insert(BBfixed_CT.end(), em_tip, em_tip+16);
// BBfixed_Instr.insert(BBfixed_Instr.end(), em_instr, em_instr+16);
// BBfixed_BB.insert(BBfixed_BB.end(), em_base, em_base+16);
// Bird4.insert(Bird4.end(), local_Bird4, local_Bird4+16);
if( m_numSamples < N_SAMPLES)
{
EigenAffineTransform3d T_BB_BBm = T_BB_Box * T_Box_BBmobile;
// axis angle
Eigen::AngleAxisd tempEA_CT (T_BB_CT_curTipPos.rotation()),
tempEA_Inst(T_BB_targetPos.rotation()),
tempEA_BB (T_BB_BBm.rotation()); //, tempEA_Bird(T_Bird4.rotation());
// Create 7d Eigen::Vectors to hold the x,y,z,xaxis,yaxis,zaxis,angle
EigenVector7d tempCT, tempInst, tempBB;
tempCT << T_BB_CT_curTipPos(0,3), T_BB_CT_curTipPos(1,3), T_BB_CT_curTipPos(2,3),
tempEA_CT.axis()(0), tempEA_CT.axis()(1), tempEA_CT.axis()(2), tempEA_CT.angle();
tempInst << T_BB_targetPos(0,3), T_BB_targetPos(1,3), T_BB_targetPos(2,3),
tempEA_Inst.axis()(0), tempEA_Inst.axis()(1), tempEA_Inst.axis()(2), tempEA_Inst.angle();
tempBB << T_BB_BBm(0,3), T_BB_BBm(1,3), T_BB_BBm(2,3),
tempEA_BB.axis()(0), tempEA_BB.axis()(1), tempEA_BB.axis()(2), tempEA_BB.angle();
double tempBird4;
if(m_isInVivo)
tempBird4 = -T_Bird4(2,3); // -z axis of the EM tracker (in vivo)
else
tempBird4 = T_Bird4(0,3); // x axis of the EM tracker (benchtop)
// push newest readings
m_BBfixed_CT.push_back(tempCT);
m_BBfixed_Instr.push_back(tempInst);
m_BBfixed_BB.push_back(tempBB);
m_Bird4.push_back(tempBird4);
m_timeData_init.push_back(sampleTime);
// send to plotter
switch (m_plotFocus)
{
case RESP_MODEL_PLOT_BIRD4:
emit sendToPlotBird4(0, sampleTime, tempBird4);
break;
case RESP_MODEL_PLOT_CT:
emit sendToPlotBird4(0, sampleTime, tempCT.segment(0,3).norm());
break;
default:
emit sendToPlotBird4(0, sampleTime, tempBird4);
break;
}
m_numSamples++;
printf("x: %.3f\n",m_BBfixed_CT.back()(0));
}
else
{
printf("Already have enough training points!\n");
printf("I'll forgive you and fix this.\n");
printf("Train model and call addObservation.\n");
trainModel();
addObservation(T_Bird4, sampleTime);
}
}
void CyclicModel::addObservation(const EigenAffineTransform3d &T_Bird4, const double sampleTime)
{
printf("Entering addObservation\n");
if(m_isTrained)
{
QElapsedTimer elTimer;
elTimer.start();
// erase oldest observation
m_Bird4_new .erase(m_Bird4_new.begin());
m_timeData_new.erase(m_timeData_new.begin());
double tempBird4;
if(m_isInVivo)
tempBird4 = -T_Bird4(2,3); // -z axis of the EM tracker (in vivo)
else
tempBird4 = T_Bird4(0,3); // x axis of the EM tracker (benchtop)
// add new observation
m_Bird4_new.push_back(tempBird4);
m_timeData_new.push_back(sampleTime);
// send to plotter
switch (m_plotFocus)
{
case RESP_MODEL_PLOT_BIRD4:
emit sendToPlotBird4(0, sampleTime, tempBird4);
break;
case RESP_MODEL_PLOT_CT:
emit sendToPlotBird4(0, sampleTime, tempBird4 - 130.);
break;
default:
emit sendToPlotBird4(0, sampleTime, tempBird4);
break;
}
m_numSamples++;
qint64 elNsec = elTimer.nsecsElapsed();
printf("Insert new obs: %d ns\n", elNsec);
// up to here take about 3 microseconds
// Retrain model
std::cout << "Retrain model...";
retrainModel();
std::cout << "...done." << std::endl;
// send to plotter
switch (m_plotFocus)
{
case RESP_MODEL_PLOT_BIRD4:
emit sendToPlotBird4(1, m_timeData_new[N_FILTERED+EDGE_EFFECT-1], m_Bird4_filtered_new.tail(1)[0]);
emit sendToPlotBird4(2, m_timeData_new[N_FILTERED+EDGE_EFFECT-1], m_breathSignalFromModel.tail(1)[0]);
break;
case RESP_MODEL_PLOT_CT:
//emit sendToPlotBird4(1, m_timeData_new.back(), m_BBfixed_CTtraj_future_des(1));
//emit sendToPlotBird4(2, m_timeData_new.back(), m_BBfixed_CT_des(1));
emit sendToPlotBird4(1, m_timeData_new.back(), m_BBfixed_CTtraj_future_des.segment(0, 3).norm());
emit sendToPlotBird4(2, m_timeData_new.back(), m_BBfixed_CT_des.segment(0, 3).norm());
break;
default:
emit sendToPlotBird4(1, m_timeData_new[N_FILTERED+EDGE_EFFECT-1], m_Bird4_filtered_new.tail(1)[0]);
emit sendToPlotBird4(2, m_timeData_new[N_FILTERED+EDGE_EFFECT-1], m_breathSignalFromModel.tail(1)[0]);
break;
}
}
else
{
std::cout << "Not trained yet!\n" << std::endl;
std::cout << "FATAL ERROR!!!\n" << std::endl; // becuase we lost this data
}
}
void CyclicModel::trainModel()
{
if(m_numSamples < N_SAMPLES) // not enough samples
{
std::cout << "m_numSamples is less than N_SAMPLES!" << std::endl;
m_isTrained = false;
}
else if(m_isTrained) // already trained
{
std::cout << "Already trained!" << std::endl;
}
else // train
{
// size_t m = N_HARMONICS; // m = number of sinusoid components
// double delta_t = SAMPLE_DELTA_TIME; // Time step for each collected data point
size_t N_initpts = m_BBfixed_CT.size(); // number of initialization points
std::cout << "Training model.\n" << std::endl;
if(N_initpts <= 2*EDGE_EFFECT)
{
std::cout << "Error: N_initpts < 2*edge_effect.\n" << std::endl;
return;
}
if(N_initpts != N_SAMPLES)
{
std::cout << "Error: N_initpts != N_SAMPLES\n" << std::endl;
}
// calculate things from inputs
// size_t num_states = N_STATES;
// size_t N_filtered = N_initpts - 2*EDGE_EFFECT;
// low pass filter the data
filterTrainingData();
std::cout << "Filtered training data.\n" << std::endl;
// // save filtered data
// QString outputFile1("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\LoggedData\\m_BBfixed_CT_filtered.txt");
// QString outputFile2("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\LoggedData\\m_BBfixed_BB_filtered.txt");
// QString outputFile3("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\LoggedData\\m_Bird4_filtered.txt");
// save4x4FilteredData(outputFile1, m_BBfixed_CT_filtered);
// save4x4FilteredData(outputFile2, m_BBfixed_BB_filtered);
// saveFilteredData(outputFile3, m_Bird4_filtered);
// Use peak detection to look at the filtered data and find the period
updatePeriod( peakDetector(true) ); // run for init
std::cout << "Updated period.\n" << std::endl;
// Get Fourier decomposition
// TODO : should compare if the column by column computation is slower than the whole matrix approach
// Eigen::VectorXd z_init_x = m_BBfixed_CT_filtered.col(0);
// Eigen::VectorXd z_init_y = m_BBfixed_CT_filtered.col(1);
// Eigen::VectorXd z_init_z = m_BBfixed_CT_filtered.col(2);
// Eigen::VectorXd z_init_xaxis = m_BBfixed_CT_filtered.col(3);
// Eigen::VectorXd z_init_yaxis = m_BBfixed_CT_filtered.col(4);
// Eigen::VectorXd z_init_zaxis = m_BBfixed_CT_filtered.col(5);
// Eigen::VectorXd z_init_angle = m_BBfixed_CT_filtered.col(6);
// cycle_recalculate(m_BBfixed_CT_filtered, m_BBfixed_CT_rectangular, m_BBfixed_CT_polar);
// cycle_recalculate(m_BBfixed_BB_filtered, m_BBfixed_BB_rectangular, m_BBfixed_BB_polar);
// cycle_recalculate(m_Bird4_filtered, m_Bird4_rectangular, m_Bird4_polar);
// TODO : is this faster?
// m_BBfixed_CT_polarRect = cycle_recalculate_concurrentM(m_BBfixed_CT_filtered, m_omega0);
// m_BBfixed_BB_polarRect = cycle_recalculate_concurrentM(m_BBfixed_BB_filtered, m_omega0);
// m_Bird4_polarRect = cycle_recalculate_concurrentV(m_Bird4_filtered, m_omega0);
mConcurrent1 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentM, m_BBfixed_CT_filtered, m_omega0, m_timeData_init);
mConcurrent2 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentM, m_BBfixed_BB_filtered, m_omega0, m_timeData_init);
mConcurrent3 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentV, m_Bird4_filtered, m_omega0, m_timeData_init);
// 3 should finish first, process that while the others are running
mConcurrent3.waitForFinished();
m_Bird4_polarRect = mConcurrent3.result();
m_Bird4_polar = m_Bird4_polarRect.segment(0, N_POLAR);
m_Bird4_rectangular = m_Bird4_polarRect.segment(N_POLAR, N_RECT);
std::cout << "m_Bird4_polarRect\n" << m_Bird4_polarRect << std::endl;
std::cout << "m_Bird4_polar\n" << m_Bird4_polar << std::endl;
std::cout << "m_Bird4_rectangular\n" << m_Bird4_rectangular << std::endl;
// 1 should be done sooner since it was launched first
mConcurrent1.waitForFinished();
m_BBfixed_CT_polarRect = mConcurrent1.result();
m_BBfixed_CT_polar = m_BBfixed_CT_polarRect.block(0,0, N_POLAR, 7);
m_BBfixed_CT_rectangular = m_BBfixed_CT_polarRect.block(N_POLAR,0, N_RECT, 7);
// 2 should be done
mConcurrent2.waitForFinished();
m_BBfixed_BB_polarRect = mConcurrent2.result();
m_BBfixed_BB_polar = m_BBfixed_BB_polarRect.block(0,0, N_POLAR, 7);
m_BBfixed_BB_rectangular = m_BBfixed_BB_polarRect.block(N_POLAR,0, N_RECT, 7);
std::cout << "Model created.\n" << std::endl;
m_lastTrainingTimestamp = QDateTime::currentMSecsSinceEpoch();
// ************************************************************* //
// //
// copy all of the init data over to the containers for new data //
// //
// ************************************************************* //
m_Bird4_new = m_Bird4; // deep copy
m_timeData_new = m_timeData_init; // deep copy
// training is done!
m_isTrained = true;
}
}
void CyclicModel::retrainModel()
{
if(!m_isTrained)
{
std::cerr << "Not trained yet!" << std::endl;
}
else
{
QElapsedTimer elTimer;
elTimer.start();
// low pass filter the data
filterNewObservations();
qint64 elNsec = elTimer.nsecsElapsed();
printf("filterNewObservations: %d ns\n", elNsec);
elTimer.restart();
// update Fourier components
// TODO : run these concurrently
// Eigen::MatrixXd m_BBfixed_CT_polarRect = cycle_recalculate_concurrent(m_BBfixed_CT_filtered, m_omega0);
// Eigen::MatrixXd m_BBfixed_BB_polarRect = cycle_recalculate_concurrent(m_BBfixed_BB_filtered, m_omega0);
// Eigen::VectorXd m_Bird4_polarRect = cycle_recalculate_concurrent(m_Bird4_filtered, m_omega0);
// std::cout << "mConcurrent1.resultCount() " << mConcurrent1.resultCount() << mConcurrent1.isRunning() << mConcurrent1.isFinished() << std::endl;
// std::cout << "mConcurrent2.resultCount() " << mConcurrent2.resultCount() << mConcurrent2.isRunning() << mConcurrent2.isFinished()<< std::endl;
// std::cout << "mConcurrent3.resultCount() " << mConcurrent3.resultCount() << mConcurrent3.isRunning() << mConcurrent3.isFinished()<< std::endl;
// if( (mConcurrent1.resultCount() > 0) && (mConcurrent2.resultCount() > 0) && (mConcurrent3.resultCount() > 0) )
if( mConcurrent3.resultCount() > 0 )
{
// m_BBfixed_CT_polarRect = mConcurrent1.result();
// // mConcurrent1 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentM, m_BBfixed_CT_filtered, m_omega0);
// m_BBfixed_CT_polar = m_BBfixed_CT_polarRect.block(0,0, N_POLAR, 7);
// m_BBfixed_CT_rectangular = m_BBfixed_CT_polarRect.block(N_POLAR,0, N_RECT, 7);
// m_BBfixed_BB_polarRect = mConcurrent2.result();
// // mConcurrent2 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentM, m_BBfixed_BB_filtered, m_omega0);
// m_BBfixed_BB_polar = m_BBfixed_BB_polarRect.block(0,0, N_POLAR, 7);
// m_BBfixed_BB_rectangular = m_BBfixed_BB_polarRect.block(N_POLAR,0, N_RECT, 7);
m_Bird4_polarRect = mConcurrent3.result();
// mConcurrent3 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentV, m_Bird4_filtered_new, m_omega0); // m_Bird4_filtered
m_Bird4_polar = m_Bird4_polarRect.segment(0, N_POLAR); // segment(i,n) : i = start idx, n = num elements
m_Bird4_rectangular = m_Bird4_polarRect.segment(N_POLAR, N_RECT);
// std::cout << "m_Bird4_polar\n" << m_Bird4_polar << std::endl;
// std::cout << "m_Bird4_rectangular\n" << m_Bird4_rectangular << std::endl;
// elNsec = elTimer.nsecsElapsed();
// std::cout << "Cycle recalc x2+x1 Nsec elapsed: " << elNsec << std::endl;
// elTimer.restart();
// update the prediction of m_breathSignalFromModel
double t_minus_t_begin; // m_breathSignalFromModel = EigenVectorFiltered::Zero(N_FILTERED);
for(size_t i = 0; i < N_FILTERED; i++)
{
t_minus_t_begin = m_timeData_new[i+EDGE_EFFECT] - m_timeData_new[EDGE_EFFECT];//- m_timeData_init[N_FILTERED + EDGE_EFFECT - 1];
// t_minus_t_begin = (m_numSamples - N_SAMPLES + i)*SAMPLE_DELTA_TIME;
if(m_isInVivo)
{
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// FIXME : do we need to differentiate b/w in vivo and benchtop?
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
m_breathSignalFromModel(i) = getPrediction(t_minus_t_begin, m_Bird4_polar, m_Bird4_rectangular);
// WE'RE NOT SURE IF THIS -1.0 IS SUPPOSED TO BE HERE !!!!!!!!!!
}
else
{
m_breathSignalFromModel(i) = getPrediction(t_minus_t_begin, m_Bird4_polar, m_Bird4_rectangular);
}
}
// update period / freq
updatePeriod( peakDetector(false) );
elNsec = elTimer.nsecsElapsed();
printf("Update period: %d ns\n", elNsec);
elTimer.restart();
// update Fourier components
// mConcurrent1 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentM, m_BBfixed_CT_filtered, m_omega0, m_timeData_new);
// mConcurrent2 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentM, m_BBfixed_BB_filtered, m_omega0, m_timeData_new);
mConcurrent3 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentV, m_Bird4_filtered_new, m_omega0, m_timeData_new);
}
else
{
// if( (!mConcurrent1.isRunning()) && (!mConcurrent2.isRunning()) && (!mConcurrent3.isRunning()) )
if( !mConcurrent3.isRunning() )
{
// std::cout << "Start concurrent." << std::endl;
// mConcurrent1 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentM, m_BBfixed_CT_filtered, m_omega0, m_timeData_new);
// mConcurrent2 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentM, m_BBfixed_BB_filtered, m_omega0, m_timeData_new);
mConcurrent3 = QtConcurrent::run(this, &CyclicModel::cycle_recalculate_concurrentV, m_Bird4_filtered_new, m_omega0, m_timeData_new);
}
// TODO : is this the best way to test this? what if one of them finishes during these checks?
// update the prediction of m_breathSignalFromModel
double t_minus_t_begin; // m_breathSignalFromModel = EigenVectorFiltered::Zero(N_FILTERED);
for(size_t i = 0; i < N_FILTERED; i++)
{
t_minus_t_begin = m_timeData_new[i+EDGE_EFFECT] - m_timeData_new[EDGE_EFFECT];//- m_timeData_init[N_FILTERED + EDGE_EFFECT - 1];
// t_minus_t_begin = (m_numSamples - N_SAMPLES + i)*SAMPLE_DELTA_TIME;
if(m_isInVivo)
{
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// FIXME : do we need to differentiate b/w in vivo and benchtop?
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
m_breathSignalFromModel(i) = getPrediction(t_minus_t_begin, m_Bird4_polar, m_Bird4_rectangular);
// WE'RE NOT SURE IF THIS -1.0 IS SUPPOSED TO BE HERE !!!!!!!!!!
}
else
{
m_breathSignalFromModel(i) = getPrediction(t_minus_t_begin, m_Bird4_polar, m_Bird4_rectangular);
}
}
}
m_lastTrainingTimestamp = QDateTime::currentMSecsSinceEpoch();
std::cout << "m_Bird4_polar: " << m_Bird4_polar(6);
// get predictions based on the models
//double t0 = m_timeData_new.back() - m_timeData_init[EDGE_EFFECT];
// double t0 = m_timeData_init.back() - m_timeData_init[EDGE_EFFECT];
// double t1 = t0; // + 0.0; fudge factor may be needed?
// double t2 = t1 + (m_nFutureSamples - EDGE_EFFECT)*SAMPLE_DELTA_TIME;
double t0 = m_timeData_init.back() - m_timeData_init[N_FILTERED + EDGE_EFFECT - 1];
double t1 = t0; // + 0.0; fudge factor may be needed?
double t2 = t1 + (m_nFutureSamples - EDGE_EFFECT)*SAMPLE_DELTA_TIME;
getPrediction7Axis(t1, m_BBfixed_CT_polar, m_BBfixed_CT_rectangular, m_BBfixed_CT_des, m_Bird4_polar(6));
getPrediction7Axis(t2, m_BBfixed_CT_polar, m_BBfixed_CT_rectangular, m_BBfixed_CTtraj_future_des, m_Bird4_polar(6));
getPrediction7Axis(t1, m_BBfixed_BB_polar, m_BBfixed_BB_rectangular, m_BBfixed_BB_des, m_Bird4_polar(6));
printf("CT_des_x %.3f CTtraj_future_des %.3f BB_des %.3f\n", m_BBfixed_CT_des(0), m_BBfixed_CTtraj_future_des(0), m_BBfixed_BB_des(0));
elNsec = elTimer.nsecsElapsed();
std::cout << "getPrediction Nsec elapsed: " << elNsec << std::endl;
elTimer.restart();
}
}
void CyclicModel::updatePeriod(const double period)
{
// omega_0 = 2*pi*1/period; % 2*pi*breathing frequency (rad/sec)
if(period > 20.)
m_omega0 = 2.0*pi/BREATH_RATE;
else
m_omega0 = 2.0*pi/period;
}
void CyclicModel::setPlotFocus(int idx)
{
m_plotFocus = idx;
}
void CyclicModel::setInVivo(const bool isInVivo)
{
if( (!m_isTrained) && (m_numSamples == 0) )
m_isInVivo = isInVivo;
else
printf("Can't modify mode now!\n");
}
void CyclicModel::filterTrainingData()
{
// TODO: run concurrent?
m_LowPassFilter.run(m_BBfixed_CT, m_BBfixed_CT_filtered);
//m_LowPassFilter.run(m_BBfixed_Instr, m_BBfixed_Instr_filtered);
m_LowPassFilter.run(m_BBfixed_BB, m_BBfixed_BB_filtered);
m_LowPassFilter.run(m_Bird4, m_Bird4_filtered);
}
void CyclicModel::filterNewObservations()
{
// TODO : only filter for the last added point
m_LowPassFilter.run(m_Bird4_new, m_Bird4_filtered_new);
}
double CyclicModel::peakDetector(const bool runForInit)
{
std::vector<size_t> peakIdx; // container for indices
double thresh;
if(runForInit){
// look at Bird4
// EigenVectorFiltered::Index maxRow, maxCol, minRow, minCol;
auto maxBird = m_Bird4_filtered.maxCoeff();//(&maxRow, &maxCol);
auto minBird = m_Bird4_filtered.minCoeff();
double diffBird = maxBird - minBird;
thresh = minBird + diffBird * PEAK_THRESHOLD;
// find indices that are greater than thresh
auto it = std::find_if(m_Bird4_filtered.data(), m_Bird4_filtered.data() + m_Bird4_filtered.size(),
[thresh](double i){return i > thresh;});
while (it != (m_Bird4_filtered.data() + m_Bird4_filtered.size()) ) {
peakIdx.emplace_back(std::distance(m_Bird4_filtered.data(), it));
it = std::find_if(std::next(it), m_Bird4_filtered.data() + m_Bird4_filtered.size(),
[thresh](double i){return i > thresh;});
}
}
else
{
// look at Bird4
// EigenVectorFiltered::Index maxRow, maxCol, minRow, minCol;
auto maxBird = m_Bird4_filtered_new.maxCoeff();//(&maxRow, &maxCol);
auto minBird = m_Bird4_filtered_new.minCoeff();
double diffBird = maxBird - minBird;
thresh = minBird + diffBird * PEAK_THRESHOLD;
// find indices that are greater than thresh
auto it = std::find_if(m_Bird4_filtered_new.data(), m_Bird4_filtered_new.data() + m_Bird4_filtered_new.size(),
[thresh](double i){return i > thresh;});
while (it != (m_Bird4_filtered_new.data() + m_Bird4_filtered_new.size()) ) {
peakIdx.emplace_back(std::distance(m_Bird4_filtered_new.data(), it));
it = std::find_if(std::next(it), m_Bird4_filtered_new.data() + m_Bird4_filtered_new.size(),
[thresh](double i){return i > thresh;});
}
}
// get the timestamp at peaks
std::vector<double> peaksTime; peaksTime.reserve(peakIdx.size());
// if initializing, then use "m_timeData_init", otherwise use "m_timeData_new"
if(runForInit){
for(auto it = peakIdx.begin(); it != peakIdx.end(); ++it){
peaksTime.emplace_back(m_timeData_init[(*it) + EDGE_EFFECT]);
}
std::cout << "///runForInit///" << std::endl;
}
else{
for(auto it = peakIdx.begin(); it != peakIdx.end(); ++it){
peaksTime.emplace_back(m_timeData_new[(*it) + EDGE_EFFECT]);
}
std::cout << "///m_timeData_new///" << std::endl;
}
std::cout << std::endl;
// take the difference of time stamps
std::vector<double> peaksTdiff; peaksTdiff.reserve(peaksTime.size() - 1);
std::transform(peaksTime.begin()+1,peaksTime.end(),
peaksTime.begin(),std::back_inserter(peaksTdiff),std::minus<double>());
// find time differences larger than 1 seconds
std::cout << "peakDetector peakGapsIdx: " << std::endl;
double largeTimeGap = 1.0; // seconds
std::vector<size_t> peakGapsIdx; // container for indices
std::vector<double>::iterator it2 = std::find_if(peaksTdiff.begin(), peaksTdiff.end(),
[largeTimeGap](double i){return i > largeTimeGap;});
while (it2 != peaksTdiff.end()) {
peakGapsIdx.emplace_back(std::distance(peaksTdiff.begin(), it2));
it2 = std::find_if(std::next(it2), peaksTdiff.end(),
[largeTimeGap](double i){return i > largeTimeGap;});
std::cout << peakGapsIdx.back() << " ";
}
std::cout << std::endl;
// we better have peaks
if(peakGapsIdx.size() < 1)
{
std::cout << "PeakDetector is in trouble! n=" << peakGapsIdx.size() << std::endl;
return BREATH_RATE;
}
std::vector<double> peakTimesRight, peakTimesLeft;
peakTimesLeft.emplace_back(peaksTime.front());
for(auto it3 = peakGapsIdx.begin(); it3 != peakGapsIdx.end(); ++it3){
peakTimesRight.emplace_back(peaksTime[*it3]);
peakTimesLeft.emplace_back(peaksTime[1 + *it3]);
}
peakTimesRight.emplace_back(peaksTime.back());
// if peak_detect_me(1) > tops_thresh
// tops_peak_times_right(1)=[];
// tops_peak_times_left(1)=[];
// end
// if peak_detect_me(end) > tops_thresh
// tops_peak_times_right(end)=[];
// tops_peak_times_left(end)=[];
// end
if(runForInit)
{
if( m_Bird4_filtered.head(1)[0] > thresh )
{
peakTimesRight.erase(peakTimesRight.begin());
peakTimesLeft.erase(peakTimesLeft.begin());
}
if( m_Bird4_filtered.tail(1)[0] > thresh )
{
peakTimesRight.pop_back();
peakTimesLeft.pop_back();
}
}
else{
if( m_Bird4_filtered_new.head(1)[0] > thresh )
{
peakTimesRight.erase(peakTimesRight.begin());
peakTimesLeft.erase(peakTimesLeft.begin());
}
if( m_Bird4_filtered_new.tail(1)[0] > thresh )
{
peakTimesRight.pop_back();
peakTimesLeft.pop_back();
}
}
// better not be empty
if(peakTimesLeft.size() < 1)
{
std::cout << "PeakDetector is in trouble 2!\n" << std::endl << std::flush;
return BREATH_RATE;
}
// tops_peak_times_means = mean([tops_peak_times_right tops_peak_times_left],2);
std::vector<double> mean; mean.reserve(peakTimesRight.size());
std::transform(peakTimesRight.begin(), peakTimesRight.end(),
peakTimesLeft.begin(), std::back_inserter(mean),
[](double r, double l){ return (l+r)/2.0; });
// if length(tops_peak_times_means)>1
// tops_peak_times_diffs = tops_peak_times_means(2:end)-tops_peak_times_means(1:(end-1));
// period=mean(tops_peak_times_diffs);
// else
// period=breath_expected;
// end
double period = 0.0;
if(mean.size() > 1)
{
// take the difference of the means
std::vector<double> meanDiffs; meanDiffs.reserve(mean.size());
std::transform(mean.begin()+1, mean.end(),
mean.begin(), std::back_inserter(meanDiffs), std::minus<double>());
period = std::accumulate(meanDiffs.begin(),meanDiffs.end(),0.0) / (double)meanDiffs.size();
}
else
{
period = BREATH_RATE;
printf("Not enough means\n");
}
if(runForInit)
{
// save the original peaks
//m_respPeakMean = mean;
// In vivo version has an error checker to make sure the breathing period is
// between 4 - 5.5 seconds
if(m_isInVivo)
{ // clamp
if( (period < (BREATH_RATE*0.8)) || (period > (BREATH_RATE*1.2)) )
period = BREATH_RATE;
}
m_periods.clear();
m_periods.resize(PERIOD_FILTER_SIZE, period);
m_periods.push_back(0); // index for circular buffer
m_omega0_init = 2.0*pi/period;;
}
else
{
// double period_old = 2.0*pi/m_omega0;
// // Get the time difference between peaks
//// % All of these steps account for the fact that there could be multiple
//// % peaks detected for the model or for the measured values. We need to find
//// % the smallest absolute value peak time difference, but then preserve the
//// % sign on that time difference to know whether the period should be faster
//// % or slower.
//// for j=1:size(tops_peak_times_means_model,1)
//// for i=1:size(tops_peak_times_means_meas,1)
//// peak_time_diff(i,j) = tops_peak_times_means_model(j)-tops_peak_times_means_meas(i);
//// end
//// [~, idx(j)]=min(abs(peak_time_diff(:,j)));
//// time_diff(j)=peak_time_diff(idx(j),j);
//// end
//// [~,idx2]=min(abs(time_diff));
//// min_time_diff=time_diff(idx2);
// peakDetectorForBreathModel(); // filter the breathing signal
// m_respPeakMean = m_breathSignalPeakMean;
// if(m_respPeakMean.size() < 1)
// {
// std::cout << "PeakDetector is in trouble 3!\n" << std::endl;
// return period_old;
// }
// if (mean.size() == 0)
// {
// printf("mean.size() == 0");
// return period_old;
// }
// Eigen::MatrixXd peakTimeDiff = Eigen::MatrixXd::Zero(m_respPeakMean.size(), mean.size());
// Eigen::VectorXd timeDiff = Eigen::VectorXd::Zero(m_respPeakMean.size());
// double minTimeDiff;
// Eigen::VectorXd::Index minIdx;
// for(size_t iMeanModel = 0; iMeanModel < m_respPeakMean.size(); iMeanModel++)
// {
// for(size_t jMeanMeas = 0; jMeanMeas < mean.size(); jMeanMeas++)
// {
// peakTimeDiff(iMeanModel,jMeanMeas) = m_respPeakMean[iMeanModel] - mean[jMeanMeas];
// }
// peakTimeDiff.row(iMeanModel).cwiseAbs().minCoeff(&minIdx);
// timeDiff[iMeanModel] = peakTimeDiff(iMeanModel,minIdx);
// }
// timeDiff.cwiseAbs().minCoeff(&minIdx);
// minTimeDiff = timeDiff(minIdx);
//// minTimeDiff = timeDiff.cwiseAbs().minCoeff();
// double period_new;
// if(mean.size() > 0)
// {
// printf("period_old: %.3f | minTimeDiff: %.3f | mean[0]: %.3f | m_timeData_new[EDGE_EFFECT]: %.3f\n",
// period_old, minTimeDiff, mean[0], m_timeData_new[EDGE_EFFECT]);
// period_new = period_old*(1.0 - minTimeDiff/(mean[0] - m_timeData_new[EDGE_EFFECT])); // mean[minIdx], m_timeData_init[EDGE_EFFECT]
// //period_new = period_old*(1.0 - minTimeDiff/(mean[0] - m_timeData_init[EDGE_EFFECT])); // mean[minIdx], m_timeData_init[EDGE_EFFECT]
// if(m_isInVivo) // in vivo mode
// {
// if( (period_new < (BREATH_RATE*0.9)) || (period_new > (BREATH_RATE*1.1)) )
// period_new = period_old;
// }
// else // benchtop mode
// {
// if( (period_new < (period_old*0.9)) || (period_new > (period_old*1.1)) )
// {
// printf("New period %.3f is oob, setting to old.\n", period_new);
// period_new = period_old;
// }
// }
// // period = period_new;
// }
// else
// printf("Mean is empty.\n");
m_periods[m_periods[PERIOD_FILTER_SIZE]] = period; // add new period to filter
m_periods[PERIOD_FILTER_SIZE] = (double)(((int)(m_periods[PERIOD_FILTER_SIZE] + 1)) % (PERIOD_FILTER_SIZE)); // increment and mod counter
period = std::accumulate(m_periods.begin(),m_periods.end()-1,0.0) / (double)(PERIOD_FILTER_SIZE); // mean
}
std::cout << "Period: " << period << std::endl << std::flush;
return period;
}
void CyclicModel::peakDetectorForBreathModel()
{
// look at m_breathSignalFromModel
auto maxBird = m_breathSignalFromModel.maxCoeff();
auto minBird = m_breathSignalFromModel.minCoeff();
double diffBird = maxBird - minBird;
double thresh = minBird + diffBird * PEAK_THRESHOLD;
// find indices that are greater than thresh
std::vector<size_t> peakIdx; // container for indices
auto it = std::find_if(m_breathSignalFromModel.data(), m_breathSignalFromModel.data() + m_breathSignalFromModel.size(),
[thresh](double i){return i > thresh;});
while (it != (m_breathSignalFromModel.data() + m_breathSignalFromModel.size()) ) {
peakIdx.emplace_back(std::distance(m_breathSignalFromModel.data(), it));
it = std::find_if(std::next(it), m_breathSignalFromModel.data() + m_breathSignalFromModel.size(),
[thresh](double i){return i > thresh;});
}
// get the timestamp at peaks
std::vector<double> peaksTime; peaksTime.reserve(peakIdx.size());
// read m_timeData_new
for(auto it = peakIdx.begin(); it != peakIdx.end(); ++it){
peaksTime.emplace_back(m_timeData_new[(*it) + EDGE_EFFECT]);
}
if (peaksTime.size() == 0)
{
std::cout << "PeakDetector is in trouble! peaksTime.size is 0" << std::endl;
return;
}
// take the difference of time stamps
std::vector<double> peaksTdiff; peaksTdiff.reserve(peaksTime.size() - 1);
std::transform(peaksTime.begin()+1,peaksTime.end(),
peaksTime.begin(),std::back_inserter(peaksTdiff),std::minus<double>());
// find time differences larger than 1 seconds
std::cout << "peakDetectorForBreathModel : peakGapsIdx: " << std::endl;
double largeTimeGap = 1.0; // seconds
std::vector<size_t> peakGapsIdx; // container for indices
auto it2 = std::find_if(std::begin(peaksTdiff), std::end(peaksTdiff),
[largeTimeGap](double i){return i > largeTimeGap;});
while (it2 != std::end(peaksTdiff)) {
peakGapsIdx.emplace_back(std::distance(std::begin(peaksTdiff), it2));
it2 = std::find_if(std::next(it2), std::end(peaksTdiff),
[largeTimeGap](double i){return i > largeTimeGap;});
std::cout << peakGapsIdx.back() << " ";
}
std::cout << std::endl;
// we better have peaks
if(peakGapsIdx.size() < 1)
{
std::cout << "PeakDetector is in trouble! n=" << peakGapsIdx.size() << std::endl;
return;
}
std::vector<double> peakTimesRight, peakTimesLeft;
peakTimesLeft.emplace_back(peaksTime.front());
for(auto it3 = peakGapsIdx.begin(); it3 != peakGapsIdx.end(); ++it3){
peakTimesRight.emplace_back(peaksTime[*it3]);
peakTimesLeft.emplace_back(peaksTime[1 + *it3]);
}
peakTimesRight.emplace_back(peaksTime.back());
if( m_breathSignalFromModel.head(1)[0] > thresh )
{
peakTimesRight.erase(peakTimesRight.begin());
peakTimesLeft.erase(peakTimesLeft.begin());
}
if( m_breathSignalFromModel.tail(1)[0] > thresh )
{
peakTimesRight.pop_back();
peakTimesLeft.pop_back();
}
// better not be empty
if(peakTimesLeft.size() < 1)
{
std::cout << "PeakDetector is in trouble 2! n=" << peakTimesLeft.size() << std::endl;
return;
}
// tops_peak_times_means = mean([tops_peak_times_right tops_peak_times_left],2);
std::vector<double> mean; mean.reserve(peakTimesRight.size());
std::transform(peakTimesRight.begin(), peakTimesRight.end(),
peakTimesLeft.begin(), std::back_inserter(mean),
[](double r, double l){ return (l+r)/2.0; });
m_breathSignalPeakMean = mean;
}
void CyclicModel::cycle_recalculate(const EigenMatrixFiltered &z_init,
EigenMatrixRectangular &x_rect,
EigenMatrixPolar &x_polar, const double omega0)
{
// TODO: add error checking to ensure that the vector size is correct
if( z_init.cols() != 7 )
printf("cycle_recalculate: Wrong column size!\n");
if( z_init.rows() != N_FILTERED )
printf("cycle_recalculate: Wrong row size!\n");
// get all of the constants
size_t m = N_HARMONICS; // m = number of sinusoid components
double delta_t = SAMPLE_DELTA_TIME; // Time step for each collected data point
size_t N_initpts = N_SAMPLES; // number of initialization points
size_t edge_effect = EDGE_EFFECT;
double omega_0 = omega0;
// calculate things from inputs
size_t num_states = m * 2 + 2;
//size_t N_filtered = N_initpts - 2 * edge_effect;
// parse the already low pass filtered data
Eigen::VectorXd z_init_x = z_init.col(0);
Eigen::VectorXd z_init_y = z_init.col(1);
Eigen::VectorXd z_init_z = z_init.col(2);
Eigen::VectorXd z_init_xaxis = z_init.col(3);
Eigen::VectorXd z_init_yaxis = z_init.col(4);
Eigen::VectorXd z_init_zaxis = z_init.col(5);
Eigen::VectorXd z_init_angle = z_init.col(6);
// allocate zero matrices
Eigen::MatrixXd A_init_x(N_FILTERED, num_states - 1); A_init_x.setZero(); A_init_x.col(0).setOnes();
Eigen::MatrixXd A_init_y(N_FILTERED, num_states - 1); A_init_y.setZero(); A_init_y.col(0).setOnes();
Eigen::MatrixXd A_init_z(N_FILTERED, num_states - 1); A_init_z.setZero(); A_init_z.col(0).setOnes();
Eigen::MatrixXd A_init_xaxis(N_FILTERED, num_states - 1); A_init_xaxis.setZero(); A_init_xaxis.col(0).setOnes();
Eigen::MatrixXd A_init_yaxis(N_FILTERED, num_states - 1); A_init_yaxis.setZero(); A_init_yaxis.col(0).setOnes();
Eigen::MatrixXd A_init_zaxis(N_FILTERED, num_states - 1); A_init_zaxis.setZero(); A_init_zaxis.col(0).setOnes();
Eigen::MatrixXd A_init_angle(N_FILTERED, num_states - 1); A_init_angle.setZero(); A_init_angle.col(0).setOnes();
for (int i = 0; i < N_FILTERED; i++)
{
for (int j = 1; j <= m; j++)
{
A_init_x(i, j) = sin(j*omega_0*i*delta_t);
A_init_y(i, j) = sin(j*omega_0*i*delta_t);
A_init_z(i, j) = sin(j*omega_0*i*delta_t);
A_init_xaxis(i, j) = sin(j*omega_0*i*delta_t);
A_init_yaxis(i, j) = sin(j*omega_0*i*delta_t);
A_init_zaxis(i, j) = sin(j*omega_0*i*delta_t);
A_init_angle(i, j) = sin(j*omega_0*i*delta_t);
A_init_x(i, j + m) = cos(j*omega_0*i*delta_t);
A_init_y(i, j + m) = cos(j*omega_0*i*delta_t);
A_init_z(i, j + m) = cos(j*omega_0*i*delta_t);
A_init_xaxis(i, j + m) = cos(j*omega_0*i*delta_t);
A_init_yaxis(i, j + m) = cos(j*omega_0*i*delta_t);
A_init_zaxis(i, j + m) = cos(j*omega_0*i*delta_t);
A_init_angle(i, j + m) = cos(j*omega_0*i*delta_t);
}
}
// Step 2. Use least squares estimate to solve for x.
//VectorXd x_init_x = pseudoInverse(A_init_x) * z_init_x;
Eigen::VectorXd x_init_x = A_init_x.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_x);
Eigen::VectorXd x_init_y = A_init_y.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_y);
Eigen::VectorXd x_init_z = A_init_z.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_z);
Eigen::VectorXd x_init_xaxis = A_init_xaxis.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_xaxis);
Eigen::VectorXd x_init_yaxis = A_init_yaxis.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_yaxis);
Eigen::VectorXd x_init_zaxis = A_init_zaxis.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_zaxis);
Eigen::VectorXd x_init_angle = A_init_angle.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_angle);
x_rect.col(0) = x_init_x;
x_rect.col(1) = x_init_y;
x_rect.col(2) = x_init_z;
x_rect.col(3) = x_init_xaxis;
x_rect.col(4) = x_init_yaxis;
x_rect.col(5) = x_init_zaxis;
x_rect.col(6) = x_init_angle;
//VectorXd x_rect_x = x_init_x;
//VectorXd x_rect_y = x_init_y;
//VectorXd x_rect_z = x_init_z;
//VectorXd x_rect_xaxis = x_init_xaxis;
//VectorXd x_rect_yaxis = x_init_yaxis;
//VectorXd x_rect_zaxis = x_init_zaxis;
//VectorXd x_rect_angle = x_init_angle;
// Step 3. Convert from rectangular into polar and assemble the state
// vector, x, at k = 430 (which is the last trustworthy state we can know)
// State vector, x
// x = [c; r(1:4); omega; theta(1:4)];
Eigen::VectorXd x_polar_x(num_states); x_polar_x.setZero();
Eigen::VectorXd x_polar_y(num_states); x_polar_y.setZero();
Eigen::VectorXd x_polar_z(num_states); x_polar_z.setZero();
Eigen::VectorXd x_polar_xaxis(num_states); x_polar_xaxis.setZero();
Eigen::VectorXd x_polar_yaxis(num_states); x_polar_yaxis.setZero();
Eigen::VectorXd x_polar_zaxis(num_states); x_polar_zaxis.setZero();
Eigen::VectorXd x_polar_angle(num_states); x_polar_angle.setZero();
x_polar_x(0) = x_init_x(0); // c(dc offset)
x_polar_y(0) = x_init_y(0); // c(dc offset)
x_polar_z(0) = x_init_z(0); // c(dc offset)
x_polar_xaxis(0) = x_init_xaxis(0); // c(dc offset)
x_polar_yaxis(0) = x_init_yaxis(0); // c(dc offset)
x_polar_zaxis(0) = x_init_zaxis(0); // c(dc offset)
x_polar_angle(0) = x_init_angle(0); // c(dc offset)
for (size_t i = 1; i <= m; i++)
{
x_polar_x(i) = std::sqrt(std::pow(x_init_x(i), 2) + std::pow(x_init_x(i + m), 2)); // r_i, convert rectangular coords back to polar
x_polar_y(i) = std::sqrt(std::pow(x_init_y(i), 2) + std::pow(x_init_y(i + m), 2)); // r_i, convert rectangular coords back to polar
x_polar_z(i) = std::sqrt(std::pow(x_init_z(i), 2) + std::pow(x_init_z(i + m), 2)); // r_i, convert rectangular coords back to polar
x_polar_xaxis(i) = std::sqrt(std::pow(x_init_xaxis(i), 2) + std::pow(x_init_xaxis(i + m), 2)); // r_i, convert rectangular coords back to polar
x_polar_yaxis(i) = std::sqrt(std::pow(x_init_yaxis(i), 2) + std::pow(x_init_yaxis(i + m), 2)); // r_i, convert rectangular coords back to polar
x_polar_zaxis(i) = std::sqrt(std::pow(x_init_zaxis(i), 2) + std::pow(x_init_zaxis(i + m), 2)); // r_i, convert rectangular coords back to polar
x_polar_angle(i) = std::sqrt(std::pow(x_init_angle(i), 2) + std::pow(x_init_angle(i + m), 2)); // r_i, convert rectangular coords back to polar
}
x_polar_x(m + 1) = omega_0; // omega_0, (rad / sec)
x_polar_y(m + 1) = omega_0; // omega_0, (rad / sec)
x_polar_z(m + 1) = omega_0; // omega_0, (rad / sec)
x_polar_xaxis(m + 1) = omega_0; // omega_0, (rad / sec)
x_polar_yaxis(m + 1) = omega_0; // omega_0, (rad / sec)
x_polar_zaxis(m + 1) = omega_0; // omega_0, (rad / sec)
x_polar_angle(m + 1) = omega_0; // omega_0, (rad / sec)
for (int i = 0; i < m; i++)
{
x_polar_x(i + m + 2) = (i + 1.0)*omega_0*N_initpts*delta_t + atan2(x_init_x(i + m + 1), x_init_x(i + 1)); // theta = i*omega*T + phi, (rad)
x_polar_y(i + m + 2) = (i + 1.0)*omega_0*N_initpts*delta_t + atan2(x_init_y(i + m + 1), x_init_y(i + 1)); // theta = i*omega*T + phi, (rad)
x_polar_z(i + m + 2) = (i + 1.0)*omega_0*N_initpts*delta_t + atan2(x_init_z(i + m + 1), x_init_z(i + 1)); // theta = i*omega*T + phi, (rad)
x_polar_xaxis(i + m + 2) = (i + 1.0)*omega_0*N_initpts*delta_t + atan2(x_init_xaxis(i + m + 1), x_init_xaxis(i + 1)); // theta = i*omega*T + phi, (rad)
x_polar_yaxis(i + m + 2) = (i + 1.0)*omega_0*N_initpts*delta_t + atan2(x_init_yaxis(i + m + 1), x_init_yaxis(i + 1)); // theta = i*omega*T + phi, (rad)
x_polar_zaxis(i + m + 2) = (i + 1.0)*omega_0*N_initpts*delta_t + atan2(x_init_zaxis(i + m + 1), x_init_zaxis(i + 1)); // theta = i*omega*T + phi, (rad)
x_polar_angle(i + m + 2) = (i + 1.0)*omega_0*N_initpts*delta_t + atan2(x_init_angle(i + m + 1), x_init_angle(i + 1)); // theta = i*omega*T + phi, (rad)
}
x_polar.col(0) = x_polar_x;
x_polar.col(1) = x_polar_y;
x_polar.col(2) = x_polar_z;
x_polar.col(3) = x_polar_xaxis;
x_polar.col(4) = x_polar_yaxis;
x_polar.col(5) = x_polar_zaxis;
x_polar.col(6) = x_polar_angle;
}
void CyclicModel::cycle_recalculate(const EigenVectorFiltered &z_init, EigenVectorRectangular &x_rect, EigenVectorPolar &x_polar, const double omega0)
{
// TODO: add error checking to ensure that the vector size is correct
if( z_init.rows() != N_FILTERED )
printf("cycle_recalculate: Wrong row size!\n");
// get all of the constants
size_t m = N_HARMONICS; // m = number of sinusoid components
double delta_t = SAMPLE_DELTA_TIME; // Time step for each collected data point
size_t N_initpts = N_SAMPLES; // number of initialization points
size_t edge_effect = EDGE_EFFECT;
double omega_0 = omega0;
// calculate things from inputs
size_t num_states = m * 2 + 2;
//size_t N_filtered = N_initpts - 2 * edge_effect;
// parse the already low pass filtered data
// Eigen::VectorXd z_init_x = z_init;
// allocate zero matrices
Eigen::MatrixXd A_init(N_FILTERED, num_states - 1); A_init.setZero(); A_init.col(0).setOnes();
for (int i = 0; i < N_FILTERED; i++)
{
for (int j = 1; j <= m; j++)
{
A_init(i, j) = sin(j*omega_0*i*delta_t);
A_init(i, j + m) = cos(j*omega_0*i*delta_t);
}
}
// Step 2. Use least squares estimate to solve for x.
//VectorXd x_init_x = pseudoInverse(A_init) * z_init;
Eigen::VectorXd x_init = A_init.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init);
// Eigen::VectorXd x_init = A_init.colPivHouseholderQr().solve(z_init); // maybe faster?
x_rect = x_init;
// Step 3. Convert from rectangular into polar and assemble the state
// vector, x, at k = 430 (which is the last trustworthy state we can know)
// State vector, x
// x = [c; r(1:4); omega; theta(1:4)];
x_polar.setZero(num_states);
x_polar(0) = x_init(0); // c(dc offset)
for (size_t i = 1; i <= m; i++)
{
x_polar(i) = std::sqrt(std::pow(x_init(i), 2) + std::pow(x_init(i + m), 2)); // r_i, convert rectangular coords back to polar
}
x_polar(m + 1) = omega_0; // omega_0, (rad / sec)
for (int i = 0; i < m; i++)
{
x_polar(i + m + 2) = (i + 1.0)*omega_0*N_initpts*delta_t + atan2(x_init(i + m + 1), x_init(i + 1)); // theta = i*omega*T + phi, (rad)
}
//x_polar = x_polar;
}
Eigen::MatrixXd CyclicModel::cycle_recalculate_concurrentM(const EigenMatrixFiltered &z_init, const double omega0, const std::vector<double> &timeData)
{
if( z_init.cols() != 7 )
printf("cycle_recalculate: Wrong column size!\n");
if( z_init.rows() != N_FILTERED )
printf("cycle_recalculate: Wrong row size!\n");
// get all of the constants
size_t m = N_HARMONICS; // m = number of sinusoid components
double delta_t = SAMPLE_DELTA_TIME; // Time step for each collected data point
size_t N_initpts = N_SAMPLES; // number of initialization points
//size_t edge_effect = EDGE_EFFECT;
double omega_0 = omega0;
// calculate things from inputs
size_t num_states = m * 2 + 2;
//size_t N_filtered = N_initpts - 2 * edge_effect;
// parse the already low pass filtered data
Eigen::VectorXd z_init_x = z_init.col(0);
Eigen::VectorXd z_init_y = z_init.col(1);
Eigen::VectorXd z_init_z = z_init.col(2);
Eigen::VectorXd z_init_xaxis = z_init.col(3);
Eigen::VectorXd z_init_yaxis = z_init.col(4);
Eigen::VectorXd z_init_zaxis = z_init.col(5);
Eigen::VectorXd z_init_angle = z_init.col(6);
// allocate zero matrices
Eigen::MatrixXd A_init_x(N_FILTERED, num_states - 1); A_init_x.setZero(); A_init_x.col(0).setOnes();
Eigen::MatrixXd A_init_y(N_FILTERED, num_states - 1); A_init_y.setZero(); A_init_y.col(0).setOnes();
Eigen::MatrixXd A_init_z(N_FILTERED, num_states - 1); A_init_z.setZero(); A_init_z.col(0).setOnes();
Eigen::MatrixXd A_init_xaxis(N_FILTERED, num_states - 1); A_init_xaxis.setZero(); A_init_xaxis.col(0).setOnes();
Eigen::MatrixXd A_init_yaxis(N_FILTERED, num_states - 1); A_init_yaxis.setZero(); A_init_yaxis.col(0).setOnes();
Eigen::MatrixXd A_init_zaxis(N_FILTERED, num_states - 1); A_init_zaxis.setZero(); A_init_zaxis.col(0).setOnes();
Eigen::MatrixXd A_init_angle(N_FILTERED, num_states - 1); A_init_angle.setZero(); A_init_angle.col(0).setOnes();
double t, s, c;
for (int i = 0; i < N_FILTERED; i++)
{
t = timeData[i+EDGE_EFFECT] - timeData[EDGE_EFFECT];
for (int j = 1; j <= m; j++)
{
s = sin(j*omega_0*t);
c = cos(j*omega_0*t);
A_init_x(i, j) = s;
A_init_y(i, j) = s;
A_init_z(i, j) = s;
A_init_xaxis(i, j) = s;
A_init_yaxis(i, j) = s;
A_init_zaxis(i, j) = s;
A_init_angle(i, j) = s;
A_init_x(i, j + m) = c;
A_init_y(i, j + m) = c;
A_init_z(i, j + m) = c;
A_init_xaxis(i, j + m) = c;
A_init_yaxis(i, j + m) = c;
A_init_zaxis(i, j + m) = c;
A_init_angle(i, j + m) = c;
}
}
// Step 2. Use least squares estimate to solve for x.
//VectorXd x_init_x = pseudoInverse(A_init_x) * z_init_x;
Eigen::VectorXd x_init_x = A_init_x.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_x);
Eigen::VectorXd x_init_y = A_init_y.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_y);
Eigen::VectorXd x_init_z = A_init_z.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_z);
Eigen::VectorXd x_init_xaxis = A_init_xaxis.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_xaxis);
Eigen::VectorXd x_init_yaxis = A_init_yaxis.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_yaxis);
Eigen::VectorXd x_init_zaxis = A_init_zaxis.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_zaxis);
Eigen::VectorXd x_init_angle = A_init_angle.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init_angle);
// Eigen::VectorXd x_init_x = A_init_x.colPivHouseholderQr().solve(z_init_x);
// Eigen::VectorXd x_init_y = A_init_y.colPivHouseholderQr().solve(z_init_y);
// Eigen::VectorXd x_init_z = A_init_z.colPivHouseholderQr().solve(z_init_z);
// Eigen::VectorXd x_init_xaxis = A_init_xaxis.colPivHouseholderQr().solve(z_init_xaxis);
// Eigen::VectorXd x_init_yaxis = A_init_yaxis.colPivHouseholderQr().solve(z_init_yaxis);
// Eigen::VectorXd x_init_zaxis = A_init_zaxis.colPivHouseholderQr().solve(z_init_zaxis);
// Eigen::VectorXd x_init_angle = A_init_angle.colPivHouseholderQr().solve(z_init_angle);
EigenMatrixRectangular x_rect;
x_rect.col(0) = x_init_x;
x_rect.col(1) = x_init_y;
x_rect.col(2) = x_init_z;
x_rect.col(3) = x_init_xaxis;
x_rect.col(4) = x_init_yaxis;
x_rect.col(5) = x_init_zaxis;
x_rect.col(6) = x_init_angle;
//VectorXd x_rect_x = x_init_x;
//VectorXd x_rect_y = x_init_y;
//VectorXd x_rect_z = x_init_z;
//VectorXd x_rect_xaxis = x_init_xaxis;
//VectorXd x_rect_yaxis = x_init_yaxis;
//VectorXd x_rect_zaxis = x_init_zaxis;
//VectorXd x_rect_angle = x_init_angle;
// Step 3. Convert from rectangular into polar and assemble the state
// vector, x, at k = 430 (which is the last trustworthy state we can know)
// State vector, x
// x = [c; r(1:4); omega; theta(1:4)];
Eigen::VectorXd x_polar_x(num_states); x_polar_x.setZero();
Eigen::VectorXd x_polar_y(num_states); x_polar_y.setZero();
Eigen::VectorXd x_polar_z(num_states); x_polar_z.setZero();
Eigen::VectorXd x_polar_xaxis(num_states); x_polar_xaxis.setZero();
Eigen::VectorXd x_polar_yaxis(num_states); x_polar_yaxis.setZero();
Eigen::VectorXd x_polar_zaxis(num_states); x_polar_zaxis.setZero();
Eigen::VectorXd x_polar_angle(num_states); x_polar_angle.setZero();
x_polar_x(0) = x_init_x(0); // c(dc offset)
x_polar_y(0) = x_init_y(0); // c(dc offset)
x_polar_z(0) = x_init_z(0); // c(dc offset)
x_polar_xaxis(0) = x_init_xaxis(0); // c(dc offset)
x_polar_yaxis(0) = x_init_yaxis(0); // c(dc offset)
x_polar_zaxis(0) = x_init_zaxis(0); // c(dc offset)
x_polar_angle(0) = x_init_angle(0); // c(dc offset)
for (size_t i = 1; i <= m; i++)
{
x_polar_x(i) = std::sqrt(std::pow(x_init_x(i), 2) + std::pow(x_init_x(i + m), 2)); // r_i, convert rectangular coords back to polar
x_polar_y(i) = std::sqrt(std::pow(x_init_y(i), 2) + std::pow(x_init_y(i + m), 2)); // r_i, convert rectangular coords back to polar
x_polar_z(i) = std::sqrt(std::pow(x_init_z(i), 2) + std::pow(x_init_z(i + m), 2)); // r_i, convert rectangular coords back to polar
x_polar_xaxis(i) = std::sqrt(std::pow(x_init_xaxis(i), 2) + std::pow(x_init_xaxis(i + m), 2)); // r_i, convert rectangular coords back to polar
x_polar_yaxis(i) = std::sqrt(std::pow(x_init_yaxis(i), 2) + std::pow(x_init_yaxis(i + m), 2)); // r_i, convert rectangular coords back to polar
x_polar_zaxis(i) = std::sqrt(std::pow(x_init_zaxis(i), 2) + std::pow(x_init_zaxis(i + m), 2)); // r_i, convert rectangular coords back to polar
x_polar_angle(i) = std::sqrt(std::pow(x_init_angle(i), 2) + std::pow(x_init_angle(i + m), 2)); // r_i, convert rectangular coords back to polar
}
x_polar_x(m + 1) = omega_0; // omega_0, (rad / sec)
x_polar_y(m + 1) = omega_0; // omega_0, (rad / sec)
x_polar_z(m + 1) = omega_0; // omega_0, (rad / sec)
x_polar_xaxis(m + 1) = omega_0; // omega_0, (rad / sec)
x_polar_yaxis(m + 1) = omega_0; // omega_0, (rad / sec)
x_polar_zaxis(m + 1) = omega_0; // omega_0, (rad / sec)
x_polar_angle(m + 1) = omega_0; // omega_0, (rad / sec)
t = timeData[N_FILTERED + EDGE_EFFECT - 1] - timeData[EDGE_EFFECT];
for (int i = 0; i < m; i++)
{
x_polar_x(i + m + 2) = (i + 1.0)*omega_0*t + std::atan2(x_init_x(i + m + 1), x_init_x(i + 1)); // theta = i*omega*T + phi, (rad)
x_polar_y(i + m + 2) = (i + 1.0)*omega_0*t + std::atan2(x_init_y(i + m + 1), x_init_y(i + 1)); // theta = i*omega*T + phi, (rad)
x_polar_z(i + m + 2) = (i + 1.0)*omega_0*t + std::atan2(x_init_z(i + m + 1), x_init_z(i + 1)); // theta = i*omega*T + phi, (rad)
x_polar_xaxis(i + m + 2) = (i + 1.0)*omega_0*t + std::atan2(x_init_xaxis(i + m + 1), x_init_xaxis(i + 1)); // theta = i*omega*T + phi, (rad)
x_polar_yaxis(i + m + 2) = (i + 1.0)*omega_0*t + std::atan2(x_init_yaxis(i + m + 1), x_init_yaxis(i + 1)); // theta = i*omega*T + phi, (rad)
x_polar_zaxis(i + m + 2) = (i + 1.0)*omega_0*t + std::atan2(x_init_zaxis(i + m + 1), x_init_zaxis(i + 1)); // theta = i*omega*T + phi, (rad)
x_polar_angle(i + m + 2) = (i + 1.0)*omega_0*t + std::atan2(x_init_angle(i + m + 1), x_init_angle(i + 1)); // theta = i*omega*T + phi, (rad)
}
EigenMatrixPolar x_polar;
x_polar.col(0) = x_polar_x;
x_polar.col(1) = x_polar_y;
x_polar.col(2) = x_polar_z;
x_polar.col(3) = x_polar_xaxis;
x_polar.col(4) = x_polar_yaxis;
x_polar.col(5) = x_polar_zaxis;
x_polar.col(6) = x_polar_angle;
Eigen::MatrixXd result(N_POLAR + N_RECT, 7);
result << x_polar, x_rect;
return result;
}
Eigen::VectorXd CyclicModel::cycle_recalculate_concurrentV(const EigenVectorFiltered &z_init, const double omega0, const std::vector<double> &timeData)
{
// TODO: add error checking to ensure that the vector size is correct
if( z_init.rows() != N_FILTERED )
printf("cycle_recalculate: Wrong row size!\n");
EigenVectorPolar x_polar;
EigenVectorRectangular x_rect;
// get all of the constants
size_t m = N_HARMONICS; // m = number of sinusoid components
double delta_t = SAMPLE_DELTA_TIME; // Time step for each collected data point
size_t N_initpts = N_SAMPLES; // number of initialization points -> should this be N_FILTERED?
//size_t edge_effect = EDGE_EFFECT;
double omega_0 = omega0;
// calculate things from inputs
size_t num_states = m * 2 + 2;
//size_t N_filtered = N_initpts - 2 * edge_effect;
// parse the already low pass filtered data
// Eigen::VectorXd z_init_x = z_init;
// allocate zero matrices
Eigen::MatrixXd A_init(N_FILTERED, num_states - 1); A_init.setZero(); A_init.col(0).setOnes();
double t;
for (int i = 0; i < N_FILTERED; i++)
{
t = timeData[i+EDGE_EFFECT] - timeData[EDGE_EFFECT];
for (int j = 1; j <= m; j++)
{
// A_init(i, j) = sin(j*omega_0*i*delta_t);
// A_init(i, j + m) = cos(j*omega_0*i*delta_t);
A_init(i, j) = std::sin(j*omega_0*t);
A_init(i, j + m) = std::cos(j*omega_0*t);
}
}
// Step 2. Use least squares estimate to solve for x.
//VectorXd x_init_x = pseudoInverse(A_init) * z_init;
Eigen::VectorXd x_init = A_init.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(z_init);
//Eigen::VectorXd x_init = A_init.colPivHouseholderQr().solve(z_init); // maybe faster?
x_rect = x_init;
// Step 3. Convert from rectangular into polar and assemble the state
// vector, x, at k = 430 (which is the last trustworthy state we can know)
// State vector, x
// x = [c; r(1:4); omega; theta(1:4)];
x_polar.setZero(num_states);
x_polar(0) = x_init(0); // c(dc offset)
for (size_t i = 1; i <= m; i++)
{
x_polar(i) = std::sqrt(std::pow(x_init(i), 2) + std::pow(x_init(i + m), 2)); // r_i, convert rectangular coords back to polar
}
x_polar(m + 1) = omega_0; // (rad / sec)
t = timeData[N_FILTERED + EDGE_EFFECT - 1] - timeData[EDGE_EFFECT];
for (int i = 0; i < m; i++)
{
x_polar(i + m + 2) = std::fmod(((double)i + 1.0)*omega_0*t + std::atan2(x_init(i + m + 1), x_init(i + 1)), 2*pi); // theta = i*omega*T + phi, (rad)
}
Eigen::VectorXd result(N_POLAR + N_RECT);
result << x_polar, x_rect;
return result;
}
double CyclicModel::getPrediction(const double timeShift, const EigenVectorPolar &x_polar, const EigenVectorRectangular &x_rect)
{
// Make sure the time coming in is already (t1[j] - t_begin)
double x_des;
using namespace std;
if(m_isTrained)
{
x_des = 0.0;
for (size_t i = 0; i < N_HARMONICS; i++)
{
x_des += x_polar(i+1) * std::sin( (i+1.0)*x_polar(N_HARMONICS+1)*timeShift + std::atan2( x_rect(i+N_HARMONICS+1), x_rect(i+1) ) );
//x_des += x_polar(i+1) * std::sin( ( (i+1.0)*x_polar(N_HARMONICS+1)*timeShift + std::atan2( x_rect(i+N_HARMONICS+1), x_rect(i+1) ) )/2.0 );
//x_des += x_polar(i+1) * std::sin( (i+1.0)*(x_polar(N_HARMONICS+1)*timeShift) + x_polar(i+N_HARMONICS+1) );
}
x_des += x_polar(0);
}
else
{
x_des = std::numeric_limits<double>::quiet_NaN();
printf("quiet_NaN!!!\n");
}
return x_des ;
}
void CyclicModel::getPrediction7Axis(const double timeShift, const EigenMatrixPolar &x_polar, const EigenMatrixRectangular &x_rect, EigenVector7d &X_des, const double phase)
{
// Make sure the time coming in is already (t1[j] - t_begin)
// double period_orig = 2*pi/m_omega0_init;
// double period_new = 2*pi/m_omega0;
// double dif = (period_orig - period_new)/period_orig;
double phDif = m_omega0_init * timeShift;
if(m_isTrained)
{
X_des = EigenVector7d::Zero();
// if(X_des.size() != 7)
// printf("X_des.size() != 7\n");
for(size_t j = 0; j < X_des.size(); j++)
{
for (size_t i = 0; i < N_HARMONICS; i++)
{
//X_des(j) = X_des(j) + x_polar(i+1,j) * sin( (i+1.0)*x_polar(N_HARMONICS+1,j)*timeShift + atan2( x_rect(i+N_HARMONICS+1,j), x_rect(i+1,j) ) );
//X_des(j) = X_des(j) + x_polar(i+1,j) * sin( (i+1.0)*m_omega0*(phase/2.0/pi * period_orig) + atan2( x_rect(i+N_HARMONICS+1,j), x_rect(i+1,j) ) );
//X_des(j) = X_des(j) + x_polar(i+1,j) * sin( (i+1.0)*m_omega0*((phase/2.0/pi-dif) * period_orig) + atan2( x_rect(i+N_HARMONICS+1,j), x_rect(i+1,j) ) );
//X_des(j) = X_des(j) + x_polar(i+1,j) * sin( (i+1.0)*phase + atan2( x_rect(i+N_HARMONICS+1,j), x_rect(i+1,j) ) );
//X_des(j) = X_des(j) + x_polar(i+1,j) * sin( (i+1.0)*(phase + m_omega0_init*(m_timeData_init.back() - m_timeData_init.front())) );
//X_des(j) = X_des(j) + x_polar(i+1,j) * sin( phase + (i+1.0)*( m_omega0_init*(m_timeData_init.back() - m_timeData_init[EDGE_EFFECT])));
X_des(j) = X_des(j) + x_polar(i+1,j) * sin( (i+1.0)*(phase + phDif - atan2( x_rect(N_HARMONICS+1,j), x_rect(1,j) )) + atan2( x_rect(i+N_HARMONICS+1,j), x_rect(i+1,j) ) );
}
X_des(j) = X_des(j) + x_polar(0,j);
}
}
else
{
//X_des = EigenVector7d::Zero();
X_des = EigenVector7d::Constant(std::numeric_limits<double>::quiet_NaN());
printf("quiet_NaN7!!!\n");
}
}
void CyclicModel::loadData(QString filename, std::vector<double> &X)
{
// check if the directory exists
QFile inFile(filename);
if( inFile.open(QIODevice::ReadOnly) )
qDebug() << "Opened inFile" << filename;
QTextStream in(&inFile);
double dummy;
while(!in.atEnd())
{
in >> dummy;
X.push_back(dummy);
}
qDebug() << "Read" << X.size() << "points.";
}
void CyclicModel::load4x4Data(QString filename, EigenStdVecVector7d &X)
{
// check if the directory exists
QFile inFile(filename);
if( inFile.open(QIODevice::ReadOnly) )
qDebug() << "Opened inFile" << filename;
QTextStream in(&inFile);
double dummy;
EigenAffineTransform3d tempT;
while(!in.atEnd())
{
for(size_t i = 0; i < 4; i++)
{
for(size_t j = 0; j < 4; j++)
{
if(in.atEnd())
{
qDebug() << "Early termination!" << filename;
return;
}
in >> dummy;
if(i < 3)
tempT(i,j) = dummy;
}
}
// axis angle
EigenVector7d temp7d;
Eigen::AngleAxisd tempEA(tempT.rotation());
temp7d << tempT(0,3), tempT(1,3), tempT(2,3),
tempEA.axis()(0), tempEA.axis()(1), tempEA.axis()(2), tempEA.angle();
// push newest readings
X.push_back(temp7d);
}
qDebug() << "Read" << X.size() << "points.";
}
void CyclicModel::load4x4Data(QString filename, std::vector<std::vector<double> > &X)
{
// check if the directory exists
QFile inFile(filename);
if( inFile.open(QIODevice::ReadOnly) )
qDebug() << "Opened inFile" << filename;
QTextStream in(&inFile);
double dummy;
EigenAffineTransform3d tempT;
X.clear();
X.resize(7,std::vector<double>());
while(!in.atEnd())
{
for(size_t i = 0; i < 4; i++)
{
for(size_t j = 0; j < 4; j++)
{
if(in.atEnd())
{
qDebug() << "Early termination!" << filename;
return;
}
in >> dummy;
if(i < 3)
tempT(i,j) = dummy;
}
}
// axis angle
EigenVector7d temp7d;
Eigen::AngleAxisd tempEA(tempT.rotation());
// push newest readings
X[0].push_back(tempT(0,3));
X[1].push_back(tempT(1,3));
X[2].push_back(tempT(2,3));
X[3].push_back(tempEA.axis()(0));
X[4].push_back(tempEA.axis()(1));
X[5].push_back(tempEA.axis()(2));
X[6].push_back(tempEA.angle());
}
qDebug() << "Read" << X.size() << "points.";
}
void CyclicModel::saveFilteredData(QString filename, const std::vector<double> &Y)
{
QFile outFile(filename);
if( outFile.open(QIODevice::WriteOnly) )
qDebug() << "Opened outFile" << filename;
QTextStream out(&outFile);
for(size_t i = 0; i < Y.size(); i++)
out << QString::number(Y[i], 'f', 4) << "\n";
qDebug() << "Wrote" << Y.size() << "points.";
}
void CyclicModel::saveFilteredData(QString filename, const EigenVectorFiltered &Y)
{
QFile outFile(filename);
if( outFile.open(QIODevice::WriteOnly) )
qDebug() << "Opened outFile" << filename;
QTextStream out(&outFile);
for(size_t i = 0; i < Y.size(); i++)
out << QString::number(Y[i], 'f', 4) << "\n";
qDebug() << "Wrote" << Y.size() << "points.";
}
void CyclicModel::save4x4FilteredData(QString filename, const EigenStdVecVector7d &Y)
{
QFile outFile(filename);
if( outFile.open(QIODevice::WriteOnly) )
qDebug() << "Opened outFile" << filename;
QTextStream out(&outFile);
for(size_t i = 0; i < Y.size(); i++)
{
out << QString::number(Y[i](0), 'f', 4) << " "
<< QString::number(Y[i](1), 'f', 4) << " "
<< QString::number(Y[i](2), 'f', 4) << " "
<< QString::number(Y[i](3), 'f', 4) << " "
<< QString::number(Y[i](4), 'f', 4) << " "
<< QString::number(Y[i](5), 'f', 4) << " "
<< QString::number(Y[i](6), 'f', 4) << "\n";
}
qDebug() << "Wrote" << Y.size() << "points.";
}
void CyclicModel::save4x4FilteredData(QString filename, const EigenMatrixFiltered &Y)
{
QFile outFile(filename);
if( outFile.open(QIODevice::WriteOnly) )
qDebug() << "Opened outFile" << filename;
QTextStream out(&outFile);
for(size_t i = 0; i < Y.rows(); i++)
{
out << QString::number(Y(i,0), 'f', 4) << " "
<< QString::number(Y(i,1), 'f', 4) << " "
<< QString::number(Y(i,2), 'f', 4) << " "
<< QString::number(Y(i,3), 'f', 4) << " "
<< QString::number(Y(i,4), 'f', 4) << " "
<< QString::number(Y(i,5), 'f', 4) << " "
<< QString::number(Y(i,6), 'f', 4) << "\n";
}
qDebug() << "Wrote" << Y.rows() << "points.";
}
void CyclicModel::testLPF()
{
//FIR lpf (Low_pass (60, 150, FILTER_ORDER));
QString inputFile("D:\\Dropbox\\Harvard\\ICEbot share\\Current working directory\\2016-12-11 Testing Cpp FiltFilt\\data_to_filter_x.txt");
QString outputFile("D:\\Dropbox\\Harvard\\ICEbot share\\Current working directory\\2016-12-11 Testing Cpp FiltFilt\\filtered_data_x_Cpp.txt");
filtfilt lpf;
std::vector<double> X,Y;
loadData(inputFile, X);
X.pop_back(); // delete the last 0
// for(auto x : X)
// std::cout << x << std::endl;
QElapsedTimer elTimer;
elTimer.start();
lpf.run(X, Y);
lpf.run(X, Y);
lpf.run(X, Y);
lpf.run(X, Y);
lpf.run(X, Y);
qint64 elNsec = elTimer.nsecsElapsed();
qDebug() << "\nNsec elapsed:" << elNsec/5;
saveFilteredData(outputFile, Y);
// test run(const std::vector<double> &X, EigenVectorFiltered &Y);
EigenVectorFiltered Y2;
elTimer.restart();
lpf.run(X, Y2);
lpf.run(X, Y2);
lpf.run(X, Y2);
lpf.run(X, Y2);
lpf.run(X, Y2);
elNsec = elTimer.nsecsElapsed();
qDebug() << "\n>>> EigenVectorFiltered Nsec elapsed:" << elNsec/5;
//saveFilteredData(outputFile, Y2);
// Test 7 axis filtering
QString inputFile7d("D:\\Dropbox\\Harvard\\ICEbot share\\Current working directory\\2016-12-11 Testing Cpp FiltFilt\\data_to_filter.txt");
QString outputFile7d("D:\\Dropbox\\Harvard\\ICEbot share\\Current working directory\\2016-12-11 Testing Cpp FiltFilt\\filtered_data_Cpp.txt");
EigenStdVecVector7d X_7dv, Y_7dv;
load4x4Data(inputFile7d, X_7dv);
elTimer.restart();
lpf.run(X_7dv, Y_7dv);
elNsec = elTimer.nsecsElapsed();
qDebug() << "\n>>> 7d Nsec elapsed:" << elNsec;
//save4x4FilteredData(outputFile7d, Y_7dv);
// test run(const std::vector<double> &X, EigenVectorFiltered &Y);
EigenMatrixFiltered Y3;
elTimer.restart();
lpf.run(X_7dv, Y3);
elNsec = elTimer.nsecsElapsed();
qDebug() << "\n>>> EigenMatrixFiltered Nsec elapsed:" << elNsec;
save4x4FilteredData(outputFile7d, Y3);
//
std::vector<std::vector<double>> Xvv;
load4x4Data(inputFile7d, Xvv);
elTimer.restart();
EigenVectorFiltered temp;
for(size_t i = 0; i<7; i++)
{
lpf.run(Xvv[i], temp);
Y3.col(i) = temp;
}
elNsec = elTimer.nsecsElapsed();
qDebug() << "\n>>> std::vector<std::vector<double>> Nsec elapsed:" << elNsec;
//save4x4FilteredData(outputFile7d, Y3);
}
| 71,550 | C++ | 41.18809 | 186 | 0.578756 |
adegirmenci/HBL-ICEbot/ControllerWidget/sweep.cpp | #include "sweep.h"
Sweep::Sweep(unsigned int nSteps_,
double stepAngle_,
double convLimit_,
qint64 imgDuration_):
isActive(false),
nControlCycles(0),
remSteps(nSteps_),
nSteps(nSteps_),
stepAngle(stepAngle_),
convergenceLimit(convLimit_),
isConverged(false),
imagingDuration(imgDuration_)
{ }
void Sweep::activate()
{
overallTimer.start();
reset();
isActive = true;
}
void Sweep::reset()
{
isActive = false;
nControlCycles = 0;
remSteps = nSteps;
isConverged = false;
}
// reports required psy increment in radians
int Sweep::update(const double currPsy)
{
if(isActive) // sweeping
{
nControlCycles++; // increment counter
if(isConverged) // converged to target
{
if(timer.hasExpired(imagingDuration)) // done with this step
{
remSteps--;
if(remSteps < 1) // done with sweep
{
reset(); // reset counters
return SWEEP_DONE;
}
else
{
isConverged = false;
return SWEEP_NEXT;
}
}
else // still taking images
return SWEEP_CONVERGED_ACQUIRING; // stay in place
}
else // not converged
{
if(abs(currPsy) < convergenceLimit) // converged!
{
isConverged = true;
timer.start(); // start counting down
return SWEEP_CONVERGED;
}
else // twiddle thumbs
{
return SWEEP_WAIT_TO_CONVERGE;
}
}
}
else // not even active
return SWEEP_INACTIVE;
}
| 1,803 | C++ | 23.378378 | 72 | 0.497504 |
adegirmenci/HBL-ICEbot/ControllerWidget/kinematics_4dof.cpp | #include "kinematics_4dof.h"
Kinematics_4DOF::Kinematics_4DOF(double L, double Rc, double Dknob)
: m_L(L), m_Rc(Rc), m_dknob(Dknob)
{
}
Kinematics_4DOF::~Kinematics_4DOF()
{
}
void Kinematics_4DOF::operator =(const Kinematics_4DOF &Other)
{
m_L = Other.m_L;
m_Rc = Other.m_Rc;
m_dknob = Other.m_dknob;
}
Eigen::Transform<double, 3, Eigen::Affine> Kinematics_4DOF::forwardKinematics(double gamma,
double theta,
double alpha,
double d)
{
if(alpha < 0)
{
alpha = std::abs(alpha); // flip sign
theta = wrapToPi(theta + pi);
}
Eigen::Matrix4d t_;
if(alpha > 0.000001)
{
t_ << sin(gamma + theta)*sin(theta) + cos(gamma + theta)*cos(theta)*cos(alpha),
-sin(gamma + theta)*cos(theta) + cos(gamma + theta)*sin(theta)*cos(alpha),
cos(theta + gamma)*sin(alpha),
(m_L*cos(theta + gamma)*(1. - cos(alpha)))/alpha,
-cos(gamma + theta)*sin(theta) + sin(gamma + theta)*cos(theta)*cos(alpha),
cos(gamma + theta)*cos(theta) + sin(gamma + theta)*sin(theta)*cos(alpha),
sin(theta + gamma)*sin(alpha),
(m_L*sin(gamma + theta)*(1. - cos(alpha)))/alpha,
-cos(theta)*sin(alpha),
-sin(theta)*sin(alpha),
cos(alpha),
d + (m_L*sin(alpha))/alpha,
0, 0, 0, 1;
}
else
{
t_ << cos(gamma), -sin(gamma), 0, 0,
sin(gamma), cos(gamma), 0, 0,
0, 0, 1, d + m_L,
0, 0, 0, 1;
}
Eigen::Transform<double, 3, Eigen::Affine> T(t_);
return T;
}
Eigen::Transform<double, 3, Eigen::Affine> Kinematics_4DOF::forwardKinematics(const Eigen::Vector4d &config)
{
return forwardKinematics(config(0),config(1),config(2),config(3));
}
Eigen::Vector4d Kinematics_4DOF::inverseKinematics3D(const double xt,
const double yt,
const double zt,
const double gamma)
{
double theta, alpha, d;
// If gamma is not provided, this problem is underdefined. 1 DoF is free since we didn't specify
// an orientation for the US crystal. We deal with this by setting default gamma to zero.
if( (std::abs(xt) < 0.000001) && (std::abs(yt) < 0.000001) )
{
theta = 0.0; // bending axis 0
alpha = 0.0; // bending angle 0
d = zt - m_L; // translation
}
else
{
double gamma_plus_theta = atan2(yt, xt); // roll plus bending axis angle
//std::cout << "atan2(1.0,0.0) = " << atan2(1.0,0.0) << std::endl;
// Checking for this is not necessary, since atan2 returns pi/2 if x = 0
//if(xt == 0)
// gamma_plus_theta = boost::math::copysign(pi/2., yt);
theta = gamma_plus_theta - gamma;
double df = sqrt(pow(xt,2) + pow(yt,2));
double c = df/m_L; // constant
//bool fZeroSuccess = fZeroAlpha(c, alpha);
fZeroAlpha(c, alpha);
d = zt - (m_L*sin(alpha))/alpha; // translation
}
// gamma = wrapToPi(gamma);
// theta = wrapToPi(theta);
// Calculate tip and final position vectors
Eigen::Transform<double, 3, Eigen::Affine> Tcalc = forwardKinematics(gamma,theta,alpha,d);
// Check if there is any error between given and calculated final position
double tip_given = sqrt(pow(xt,2) + pow(yt,2) + pow(zt,2));
//double tip_calc = sqrt( pow(Tcalc(0,3),2) + pow(Tcalc(1,3),2) + pow(Tcalc(2,3),2) );
double tip_calc = Tcalc.matrix().col(3).segment(0,3).norm();
double err = (tip_given - tip_calc)/tip_given;
if(std::abs(err) > 0.000001)
printf("BIG ERROR (%f) CHECK PARAMETERS\n", err);
// if(true)
// {
// // Report to user
// printf("Distance d is:\n\t %f mm\n", d);
// printf("Angle gamma is:\n\t %f radians\n\t = %f degrees\n", gamma, gamma*180.0/pi);
// printf("Angle theta is:\n\t %f radians\n\t = %f degrees\n", theta, theta*180.0/pi);
// printf("Angle alpha is:\n\t %f radians\n\t = %f degrees\n", alpha, alpha*180.0/pi);
// }
return Eigen::Vector4d(gamma,theta,alpha,d);
}
Eigen::Vector4d Kinematics_4DOF::inverseKinematics(const Eigen::Transform<double, 3, Eigen::Affine> &T,
const double gamma)
{
// get position from matrix
double xt = T(0,3);
double yt = T(1,3);
double zt = T(2,3);
double theta, alpha, d;
if( (std::abs(xt) < 0.000001) && (std::abs(yt) < 0.000001) )
{
theta = 0; // bending axis 0
alpha = 0; // bending angle 0
d = zt - m_L; // translation
}
else
{
double gamma_plus_theta = atan2(yt, xt); // roll plus bending axis angle
theta = gamma_plus_theta - gamma;
bool fZeroSuccess;
if (fmod(gamma_plus_theta,pi) == 0)
{
double c = xt/m_L/cos(gamma_plus_theta); // constant
fZeroSuccess = fZeroAlpha(c, alpha);
}
else
{
double c = yt/m_L/sin(gamma_plus_theta); // constant
fZeroSuccess = fZeroAlpha(c, alpha);
}
d = zt - (m_L*sin(alpha))/alpha; // translation
}
//gamma = wrapToPi(gamma);
theta = wrapToPi(theta);
// Calculate tip and final position vectors
//Eigen::Transform<double, 3, Eigen::Affine> T_curr_calc = forwardKinematics(gamma,theta,alpha,d);
return Eigen::Vector4d(gamma,theta,alpha,d);
}
Eigen::Matrix<double, 4, 2> Kinematics_4DOF::control_icra2016(const Eigen::Transform<double, 3, Eigen::Affine> &T,
const Eigen::Vector4d &dX,
double gamma)
{
// Run inverse kinematics to get configuration space parameters
Eigen::Vector4d configCurr = inverseKinematics(T, gamma);
Eigen::Transform<double, 3, Eigen::Affine> T_Curr = forwardKinematics(configCurr);
Eigen::Vector4d jointsCurr = configToJointSpace(configCurr);
double xt = T_Curr(0,3) + dX(0);
double yt = T_Curr(1,3) + dX(1);
double zt = T_Curr(2,3) + dX(2);
// Figure out angular deltas based on desired tip position
// Keep the same amount of catheter base roll
Eigen::Vector4d configTgt = inverseKinematics3D(xt, yt, zt,
configCurr(0)); // gammaCurr
Eigen::Transform<double, 3, Eigen::Affine> T_Tgt = forwardKinematics(configTgt);
//std::cout << "Target Tform\n" << T_Tgt.matrix() << std::endl;
// Figure out how much to unroll
// Project initial x axis to the final x-y plane
Eigen::Vector3d x_init = T_Curr.rotation().block<3,1>(0,0);
Eigen::Vector3d x_final = T_Tgt.rotation().block<3,1>(0,0);
Eigen::Vector3d z_final = T_Tgt.rotation().block<3,1>(0,2);
Eigen::Vector3d x_init_proj = x_init - x_init.dot(z_final)*z_final;
x_init_proj.normalize();
//std::cout << "x_init_proj\n" << x_init_proj << std::endl;
// Find the angle between the projected and final x axes
Eigen::Vector3d cross_xinit_xfinal = x_final.cross(x_init_proj);
cross_xinit_xfinal.normalize();
//std::cout << "cross_xinit_xfinal\n" << cross_xinit_xfinal << std::endl;
double dot_xinitproj_xfinal = x_init_proj.dot(x_final);
//std::cout << "dot_xinitproj_xfinal\n" << dot_xinitproj_xfinal << std::endl;
// The dot product can be slightly larger than 1 or -1, causing acos to return NAN
if( (-1.0 > dot_xinitproj_xfinal) && (dot_xinitproj_xfinal > -1.01))
dot_xinitproj_xfinal = -1.0;
if( (1.0 < dot_xinitproj_xfinal) && (dot_xinitproj_xfinal < 1.01) )
dot_xinitproj_xfinal = 1.0;
double delta_angle = acos(dot_xinitproj_xfinal);
//std::cout << "delta_angle\n" << delta_angle << std::endl;
if( z_final.dot(cross_xinit_xfinal) < 0.0)
delta_angle = -delta_angle; // account for directionality
//std::cout << "delta_angle\n" << delta_angle << std::endl;
// Add the unroll and user's desired roll angles to handle roll
double angle_diff = delta_angle + dX(3); // dX(3) =>> dpsi in MATLAB
configTgt(0) = configTgt(0) + angle_diff; // (gamma) update handle roll angle
configTgt(1) = configTgt(1) - angle_diff; // (theta) update bending axis angle
// Get the target configuration space paramters and joint angles
T_Tgt = forwardKinematics(configTgt); // update transform
Eigen::Vector4d jointsTgt = configToJointSpace(configTgt);
Eigen::Matrix<double, 4, 2> jointsCurrAndTgt;
//std::cout << "Joints Curr\n" << jointsCurr << std::endl;
//std::cout << "Joints Target\n" << jointsTgt << std::endl;
jointsCurrAndTgt << jointsCurr, jointsTgt;
return jointsCurrAndTgt;
}
Eigen::Matrix<double, 6, 4> Kinematics_4DOF::JacobianNumeric(double gamma,
double theta,
double alpha,
double d)
{
double del_ = 0.0001; // small bump
// vary d
Eigen::Transform<double, 3, Eigen::Affine> T1plus = forwardKinematics(gamma,theta,alpha,d + del_);
Eigen::Transform<double, 3, Eigen::Affine> T1minus = forwardKinematics(gamma,theta,alpha,d - del_);
// vary gamma
Eigen::Transform<double, 3, Eigen::Affine> T2plus = forwardKinematics(gamma + del_,theta,alpha,d);
Eigen::Transform<double, 3, Eigen::Affine> T2minus = forwardKinematics(gamma - del_,theta,alpha,d);
// vary theta
Eigen::Transform<double, 3, Eigen::Affine> T3plus = forwardKinematics(gamma,theta + del_,alpha,d);
Eigen::Transform<double, 3, Eigen::Affine> T3minus = forwardKinematics(gamma,theta - del_,alpha,d);
// vary alpha
Eigen::Transform<double, 3, Eigen::Affine> T4plus = forwardKinematics(gamma,theta,alpha + del_,d);
Eigen::Transform<double, 3, Eigen::Affine> T4minus = forwardKinematics(gamma,theta,alpha - del_,d);
// numerical x
double delx1 = (T1plus(0,3) - T1minus(0,3))/(2*del_);
double delx2 = (T2plus(0,3) - T2minus(0,3))/(2*del_);
double delx3 = (T3plus(0,3) - T3minus(0,3))/(2*del_);
double delx4 = (T4plus(0,3) - T4minus(0,3))/(2*del_);
// numerical y
double dely1 = (T1plus(1,3) - T1minus(1,3))/(2*del_);
double dely2 = (T2plus(1,3) - T2minus(1,3))/(2*del_);
double dely3 = (T3plus(1,3) - T3minus(1,3))/(2*del_);
double dely4 = (T4plus(1,3) - T4minus(1,3))/(2*del_);
// numerical z
double delz1 = (T1plus(2,3) - T1minus(2,3))/(2*del_);
double delz2 = (T2plus(2,3) - T2minus(2,3))/(2*del_);
double delz3 = (T3plus(2,3) - T3minus(2,3))/(2*del_);
double delz4 = (T4plus(2,3) - T4minus(2,3))/(2*del_);
// numerical angle 1
Eigen::Vector3d angles1Plus = T1plus.rotation().eulerAngles(2,1,0);
Eigen::Vector3d angles1Minus = T1minus.rotation().eulerAngles(2,1,0);
Eigen::Vector3d angles1 = (angles1Plus - angles1Minus)/(2*del_);
// numerical angle 2
Eigen::Vector3d angles2Plus = T2plus.rotation().eulerAngles(2,1,0);
Eigen::Vector3d angles2Minus = T2minus.rotation().eulerAngles(2,1,0);
Eigen::Vector3d angles2 = (angles2Plus - angles2Minus)/(2*del_);
// numerical angle 3
Eigen::Vector3d angles3Plus = T3plus.rotation().eulerAngles(2,1,0);
Eigen::Vector3d angles3Minus = T3minus.rotation().eulerAngles(2,1,0);
Eigen::Vector3d angles3 = (angles3Plus - angles3Minus)/(2*del_);
// numerical angle 4
Eigen::Vector3d angles4Plus = T4plus.rotation().eulerAngles(2,1,0);
Eigen::Vector3d angles4Minus = T4minus.rotation().eulerAngles(2,1,0);
Eigen::Vector3d angles4 = (angles4Plus - angles4Minus)/(2*del_);
// numerical angles x
double angx1 = angles1(2);
double angx2 = angles2(2);
double angx3 = angles3(2);
double angx4 = angles4(2);
// numerical angles y
double angy1 = angles1(1);
double angy2 = angles2(1);
double angy3 = angles3(1);
double angy4 = angles4(1);
// numerical angles z
double angz1 = angles1(0);
double angz2 = angles2(0);
double angz3 = angles3(0);
double angz4 = angles4(0);
Eigen::Matrix<double, 6, 4> J;
J << delx1, delx2, delx3, delx4,
dely1, dely2, dely3, dely4,
delz1, delz2, delz3, delz4,
angx1, angx2, angx3, angx4,
angy1, angy2, angy3, angy4,
angz1, angz2, angz3, angz4;
return J;
}
Eigen::Vector4d Kinematics_4DOF::dampedLeastSquaresStep(const Eigen::Matrix<double, 6, 4> &J,
const Eigen::Matrix<double, 6, 1> &C_error)
{
// calculate the condition number
Eigen::Matrix<double, 4, 4> We4 = Eigen::Matrix<double, 4, 4>::Identity() * (1./4.); // weighting matrix
Eigen::Matrix<double, 6, 6> We6 = Eigen::Matrix<double, 6, 6>::Identity() * (1./6.); // weighting matrix
double kap = sqrt( (J*We4*J.transpose()).trace() * (J.transpose()*We6*J).trace() ); // Weighted Frobenius norm
//double kap = sqrt( (J*J.transpose()).trace() * (J.transpose*J).trace() ); // Frobenius norm
double condNum = 1./kap; // condition number
printf("J cond = %.3f\n", condNum);
// lambda = 0.2;
double lambda = condNum;
Eigen::Matrix<double, 6, 6> mtrx = (J * J.transpose() + Eigen::Matrix<double, 6, 6>::Identity() * lambda);
// Eigen::JacobiSVD<MatrixXf> svd(J, ComputeThinU | ComputeThinV);
// Eigen::Matrix<double, 6, 4> E;
// E(0,0) = svd.singularValues()(0) / (svd.singularValues()(0)*svd.singularValues()(0) + kap*kap);
// E(1,1) = svd.singularValues()(1) / (svd.singularValues()(1)*svd.singularValues()(1) + kap*kap);
// E(2,2) = svd.singularValues()(2) / (svd.singularValues()(2)*svd.singularValues()(2) + kap*kap);
// E(3,3) = svd.singularValues()(3) / (svd.singularValues()(3)*svd.singularValues()(3) + kap*kap);
// Eigen::Matrix<double, 4, 6> VEUT = svd.matrixV() * E * svd.matrixU().transpose();
// Eigen::Vector4d delta_C = VEUT * C_error;
//Eigen::Vector4d delta_C = J.transpose()* mtrx.inverse() * C_error;
Eigen::Vector4d delta_C = J.transpose()* mtrx.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(C_error);
return delta_C;
}
// taskSpace = {x,y,z,psi}
// configSpace = {gamma,theta,alpha,d}
Eigen::Vector4d Kinematics_4DOF::taskToConfigSpace(const Eigen::Vector4d &taskSpace)
{
double xt = taskSpace(0), yt = taskSpace(1), zt = taskSpace(2), psi = taskSpace(3);
double gamma, theta, alpha, d;
if( (std::abs(xt) < 0.000001) && (std::abs(yt) < 0.000001) )
{
alpha = 0;
theta = 0;
gamma = psi;
d = zt - m_L;
}
else
{
double gamma_plus_theta = atan2(yt, xt); // roll plus bending axis angle
theta = psi;
gamma = gamma_plus_theta - psi;
bool fZeroSuccess;
if (fmod(gamma_plus_theta,pi) == 0)
{
double c = xt/m_L/cos(gamma_plus_theta); // constant
fZeroSuccess = fZeroAlpha(c, alpha);
}
else
{
double c = yt/m_L/sin(gamma_plus_theta); // constant
fZeroSuccess = fZeroAlpha(c, alpha);
}
d = zt - (m_L*sin(alpha))/alpha; // translation
}
// gamma = wrapToPi(gamma);
// theta = wrapToPi(theta);
if(alpha < 0)
printf("\n\n\n\n\n ALPHA LESS THAN ZERO!!! \n\n\n\n\n");
return Eigen::Vector4d(gamma,theta,alpha,d);
}
// {gamma,theta,alpha,d}
Eigen::Vector4d Kinematics_4DOF::configToTaskSpace(const Eigen::Vector4d &configSpace)
{
double gamma = configSpace(0), theta = configSpace(1), alpha = configSpace(2), d = configSpace(3);
double x,y,z,psi;
if(std::abs(alpha) < 0.0001)
{
x = 0;
y = 0;
z = d + m_L;
psi = gamma;
}
else
{
double r = m_L*(1.0-cos(alpha))/alpha;
x = r*cos(gamma + theta);
y = r*sin(gamma + theta);
z = d + m_L*sin(alpha)/alpha;
psi = theta;
}
return Eigen::Vector4d(x,y,z,psi);
}
Eigen::Matrix4d Kinematics_4DOF::JacobianNumericTaskSpace(const Eigen::Vector4d &configCurr)
{
double gamma = configCurr(0), theta = configCurr(1), alpha = configCurr(2), d = configCurr(3);
double del_ = 0.0001; // small bump
// vary d
Eigen::Transform<double, 3, Eigen::Affine> T1plus = forwardKinematics(gamma,theta,alpha,d + del_);
Eigen::Transform<double, 3, Eigen::Affine> T1minus = forwardKinematics(gamma,theta,alpha,d - del_);
// psi1plus = theta;
// psi1minus = theta;
// vary gamma
Eigen::Transform<double, 3, Eigen::Affine> T2plus = forwardKinematics(gamma + del_,theta,alpha,d);
Eigen::Transform<double, 3, Eigen::Affine> T2minus = forwardKinematics(gamma - del_,theta,alpha,d);
// psi2plus = theta;
// psi2minus = theta;
// vary theta
Eigen::Transform<double, 3, Eigen::Affine> T3plus = forwardKinematics(gamma,theta + del_,alpha,d);
Eigen::Transform<double, 3, Eigen::Affine> T3minus = forwardKinematics(gamma,theta - del_,alpha,d);
double psi3plus = theta + del_;
double psi3minus = theta - del_;
// vary alpha
Eigen::Transform<double, 3, Eigen::Affine> T4plus = forwardKinematics(gamma,theta,alpha + del_,d);
Eigen::Transform<double, 3, Eigen::Affine> T4minus = forwardKinematics(gamma,theta,alpha - del_,d);
// psi4plus = theta;
// psi4minus = theta;
// numerical x
double delx1 = (T1plus(0,3) - T1minus(0,3))/(2*del_);
double delx2 = (T2plus(0,3) - T2minus(0,3))/(2*del_);
double delx3 = (T3plus(0,3) - T3minus(0,3))/(2*del_);
double delx4 = (T4plus(0,3) - T4minus(0,3))/(2*del_);
// numerical y
double dely1 = (T1plus(1,3) - T1minus(1,3))/(2*del_);
double dely2 = (T2plus(1,3) - T2minus(1,3))/(2*del_);
double dely3 = (T3plus(1,3) - T3minus(1,3))/(2*del_);
double dely4 = (T4plus(1,3) - T4minus(1,3))/(2*del_);
// numerical z
double delz1 = (T1plus(2,3) - T1minus(2,3))/(2*del_);
double delz2 = (T2plus(2,3) - T2minus(2,3))/(2*del_);
double delz3 = (T3plus(2,3) - T3minus(2,3))/(2*del_);
double delz4 = (T4plus(2,3) - T4minus(2,3))/(2*del_);
// numerical psi
// psi1,2,4 = 0
double psi3 = (psi3plus - psi3minus)/(2*del_);
Eigen::Matrix4d J;
if(std::abs(alpha) < 0.0001){
J << 1e-12, delx3, delx4, delx1,
dely2, 1e-12, dely4, dely1,
delz2, delz3, delz4, delz1,
psi3, 0.0, 0.0, 0.0;
}
else{
J << delx2, delx3, delx4, delx1,
dely2, dely3, dely4, dely1,
delz2, delz3, delz4, delz1,
0.0, psi3, 0.0, 0.0;
}
return J;
}
Eigen::Vector4d Kinematics_4DOF::JacobianStep(const Eigen::Vector4d &currTask, const Eigen::Vector4d &targetTask, const Eigen::Vector4d &currConfig)
{
Eigen::Vector4d dxyzpsi = targetTask - currTask;
dxyzpsi(3) = wrapToPi(dxyzpsi(3));
double normXYZ = dxyzpsi.segment<3>(0).norm(), errorRot = std::abs(dxyzpsi(3));
double euclThresh = 1.5;
double rotThresh = pi/5;
Eigen::Vector4d delta_C; delta_C = Eigen::Vector4d::Zero();
Eigen::Vector4d newConfig = currConfig;
Eigen::Vector4d newTask = currTask;
//Eigen::Vector4d oldTask = newTask, intm_task;
unsigned int iter = 0;
bool isNotConverged = (normXYZ > 0.01) || (errorRot > 0.01);
while( isNotConverged && (iter < 30) )
{
// clamp error
// don't translate more than 1.5 at a time
if(normXYZ > euclThresh)
dxyzpsi.segment<3>(0) *= euclThresh/normXYZ;
// don't rotate more than 36 degrees at a time
if(std::abs(dxyzpsi(3)) > rotThresh)
dxyzpsi(3) = boost::math::copysign(rotThresh, dxyzpsi(3));
// numerically compute Jacobian
Eigen::Matrix4d J = JacobianNumericTaskSpace(newConfig);
// J_pseudoinverseWithNullspace
Eigen::Vector4d v_(0.5,0.5,0.5,0.5); v_ *= 2.0;
Eigen::JacobiSVD<Eigen::Matrix4d> svd(J, Eigen::ComputeThinU | Eigen::ComputeThinV);
//Eigen::Matrix4d pinvJ = svd.solve(Eigen::Matrix4d::Identity()); // J.inverse();
//delta_C = pinvJ * dxyzpsi + (Eigen::Matrix4d::Identity() - pinvJ*J)*v_;
delta_C = svd.solve(dxyzpsi) + (Eigen::Matrix4d::Identity() - svd.solve(J))*v_;
// oldTask = configToTaskSpace(newConfig);
newConfig += delta_C;
if(newConfig(2) < 0.0) // gamma, theta, alpha, d
{
newConfig(2) = std::abs(newConfig(2));
newConfig(1) = wrapToPi(newConfig(1) + pi);
}
// intm_task = configToTaskSpace(newConfig);
// newTask += (intm_task - oldTask);
newTask = configToTaskSpace(newConfig);
dxyzpsi = targetTask - newTask;
dxyzpsi(3) = wrapToPi(dxyzpsi(3));
normXYZ = dxyzpsi.segment<3>(0).norm();
errorRot = std::abs(dxyzpsi(3));
isNotConverged = (normXYZ > 0.01) || (errorRot > 0.01);
iter++;
}
if(isNotConverged)
{
printf("Not converged, %.3f %.3f.\n", normXYZ, errorRot);
//newConfig = currConfig;
}
else
printf("Converged in %d steps.\n", iter);
return newConfig;
}
Eigen::Vector4d Kinematics_4DOF::JacobianStepSingle(const Eigen::Vector4d &currTask, const Eigen::Vector4d &targetTask, const Eigen::Vector4d &currConfig)
{
Eigen::Vector4d dxyzpsi = targetTask - currTask;
dxyzpsi(3) = wrapToPi(dxyzpsi(3));
double normXYZ = dxyzpsi.segment<3>(0).norm(), errorRot = std::abs(dxyzpsi(3));
double euclThresh = 1.5;
double rotThresh = pi/5;
Eigen::Vector4d delta_C; delta_C = Eigen::Vector4d::Zero();
bool isNotConverged = (normXYZ > 0.01) || (errorRot > 0.01);
if( isNotConverged )
{
// clamp error
// don't translate more than 1.5 at a time
if(normXYZ > euclThresh)
dxyzpsi.segment<3>(0) *= euclThresh/normXYZ;
// don't rotate more than 36 degrees at a time
if(std::abs(dxyzpsi(3)) > rotThresh)
dxyzpsi(3) = boost::math::copysign(rotThresh, dxyzpsi(3));
// numerically compute Jacobian
Eigen::Matrix4d J = JacobianNumericTaskSpace(currConfig);
// J_pseudoinverseWithNullspace
Eigen::Vector4d v_(0.5,0.5,0.5,0.5); v_ *= 2.0;
Eigen::JacobiSVD<Eigen::Matrix4d> svd(J, Eigen::ComputeThinU | Eigen::ComputeThinV);
//Eigen::Matrix4d pinvJ = svd.solve(Eigen::Matrix4d::Identity()); // J.inverse();
//delta_C = pinvJ * dxyzpsi + (Eigen::Matrix4d::Identity() - pinvJ*J)*v_;
delta_C = svd.solve(dxyzpsi) + (Eigen::Matrix4d::Identity() - svd.solve(J))*v_;
}
return delta_C;
}
double Kinematics_4DOF::wrapToPi(double lambda)
{
double signedPI = boost::math::copysign(pi, lambda);
return lambda = fmod(lambda + signedPI,(2*pi)) - signedPI;
}
bool Kinematics_4DOF::fZeroAlpha(const double c, double &alpha)
{
// Newton's Method - init
double a0 = 2*c; // initial guess
double a1 = 0.0, y, yprime;
bool foundSoln = false;
// Newton's Method - iterate
for(size_t i = 0; i < 25; i++)
{
y = 1.0 - cos(a0) - a0*c; // function
yprime = sin(a0) - c; // 1st derivative
if(std::abs(yprime) < 1.0e-14)
break;
a1 = a0 - y/yprime;
if(std::abs(a1 - a0) <= (1.0e-7 * std::abs(a1)) )
{
//printf("Found solution in %d steps.\n", i+1);
foundSoln = true;
break;
}
a0 = a1 ;
}
// Newton's Method - end
if(!foundSoln)
printf("fzero failed!!!\n");
alpha = a1;
return foundSoln;
}
/*!
* @param[in] d Translation
* @param[in] gamma Roll angle
* @param[in] theta Bending axis angle
* @param[in] alpha Bending angle
* @param[in] Rc Catheter radius
* @param[in] dknob Diameter of the knob
* @param[out] outputs A vector that contains the following values:
* phi_trans : Translation
* phi_pitch : Roll angle
* phi_yaw : Bending axis angle
* phi_roll : Bending angle
*/
void Kinematics_4DOF::configToJointSpace(const double gamma,
const double theta,
const double alpha,
const double d,
Eigen::Vector4d &outputs)
{
// Paul added a negative in front of this to be consistent with the way yaw is defined
// for the catheter absolute joint angles
outputs(0) = d;
outputs(1) = 2.0 * ( m_Rc * alpha * cos(theta)) / m_dknob;
outputs(2) = 2.0 * (-m_Rc * alpha * sin(theta)) / m_dknob;
outputs(3) = gamma;
// compensate for pitch/yaw coupling and losses
// double tempPitch, tempYaw;
// tempPitch = outputs(1)*PITCH_WP + outputs(2)*PITCH_WY + PITCH_BIAS;
// tempYaw = outputs(1)*YAW_WP + outputs(2)*YAW_WY + YAW_BIAS;
// outputs(1) = tempPitch;// /PITCH_SUM;
// outputs(2) = tempYaw;// /YAW_SUM;
}
void Kinematics_4DOF::configToJointSpace(const Eigen::Vector4d &inputs, Eigen::Vector4d &outputs)
{
configToJointSpace(inputs(0),inputs(1),inputs(2),inputs(3),outputs);
}
Eigen::Vector4d Kinematics_4DOF::configToJointSpace(const Eigen::Vector4d &inputs)
{
Eigen::Vector4d outputs;
configToJointSpace(inputs, outputs);
return outputs;
}
Eigen::Vector4d Kinematics_4DOF::configToLearnedJointSpace(const Eigen::Vector4d &currConfig,
const Eigen::Matrix<double, 4, -1> &configHistory,
const Eigen::Vector4d &deltaConfig)
{
// feed into ML model to get target joint angles
Eigen::Vector4d joints;// = getJointPrediction(currConfig, configHistory, deltaConfig);
return joints;
}
| 26,681 | C++ | 37.336207 | 154 | 0.568869 |
adegirmenci/HBL-ICEbot/ControllerWidget/gainswidget.cpp | #include "gainswidget.h"
#include "ui_gainswidget.h"
gainsWidget::gainsWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::gainsWidget)
{
ui->setupUi(this);
this->setWindowTitle("Adjust Gains");
qRegisterMetaType<GainsPYRT>("GainsPYRT");
qRegisterMetaType<ConvergenceLimits>("ConvergenceLimits");
}
gainsWidget::~gainsWidget()
{
delete ui;
}
void gainsWidget::on_closeButton_clicked()
{
emit closeGainsWindow();
}
void gainsWidget::closeEvent(QCloseEvent *event)
{
emit closeGainsWindow();
event->accept();
}
void gainsWidget::on_setGainsButton_clicked()
{
GainsPYRT gains;
gains.kPitchMin = ui->gainPitchMinSpinbox->value();
gains.kPitch = gains.kPitchMin;
gains.kPitchMax = ui->gainPitchMaxSpinbox->value();
gains.kYawMin = ui->gainYawMinSpinbox->value();
gains.kYaw = gains.kYawMin;
gains.kYawMax = ui->gainYawMaxSpinbox->value();
gains.kRollMin = ui->gainRollMinSpinbox->value();
gains.kRoll = gains.kRollMin;
gains.kRollMax = ui->gainRollMaxSpinbox->value();
gains.kTransMin = ui->gainTransMinSpinbox->value();
gains.kTrans = gains.kTransMin;
gains.kTransMax = ui->gainTransMaxSpinbox->value();
emit setGains(gains);
}
void gainsWidget::on_setLimitsButton_clicked()
{
ConvergenceLimits limits;
limits.posMin = ui->posConvMinSpinbox->value();
limits.posMax = ui->posConvMaxSpinbox->value();
limits.angleMin = ui->angConvMinSpinbox->value();
limits.angleMax = ui->angConvMaxSpinbox->value();
emit setLimits(limits);
}
| 1,558 | C++ | 22.621212 | 62 | 0.700257 |
adegirmenci/HBL-ICEbot/ControllerWidget/kinematics_4dof.h | #ifndef KINEMATICS_4DOF_H
#define KINEMATICS_4DOF_H
#include <math.h>
//#include <chrono>
//#include <thread>
#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/math/special_functions/sign.hpp>
//#include <boost/math/tools/roots.hpp>
#include <Eigen/Dense>
#include <Eigen/SVD>
#include <Eigen/StdVector>
#include <Eigen/Geometry>
#include "../icebot_definitions.h"
/*!
* \brief Four degree of freedom catheter kinematics class.
* \author Alperen Degirmenci
* \version 1.0alpha
* \date 2015-2016
*/
class Kinematics_4DOF
{
public:
Kinematics_4DOF(double L = 1.0, double Rc = 1.0, double Dknob = 1.0);
~Kinematics_4DOF();
void operator = (const Kinematics_4DOF &Other); // assignment operator definition
// Configuration space to joint space
void configToJointSpace(const double gamma,
const double theta,
const double alpha,
const double d,
Eigen::Vector4d &outputs);
void configToJointSpace(const Eigen::Vector4d &inputs,
Eigen::Vector4d &outputs);
Eigen::Vector4d configToJointSpace(const Eigen::Vector4d &inputs);
// new mapping based on learning
Eigen::Vector4d configToLearnedJointSpace(const Eigen::Vector4d &currConfig,
const Eigen::Matrix<double, 4, -1> &configHistory,
const Eigen::Vector4d &deltaConfig);
// Forward Kinematics
Eigen::Transform<double, 3, Eigen::Affine> forwardKinematics(double gamma,
double theta,
double alpha,
double d);
Eigen::Transform<double, 3, Eigen::Affine> forwardKinematics(const Eigen::Vector4d &config);
// Inverse Kinematics
Eigen::Vector4d inverseKinematics3D(const double xt,
const double yt,
const double zt,
const double gamma = 0.0);
Eigen::Vector4d inverseKinematics(const Eigen::Transform<double, 3, Eigen::Affine> &T,
const double gamma); // 4 DOF
Eigen::Matrix<double, 4, 2> control_icra2016(const Eigen::Transform<double, 3, Eigen::Affine> &T,
const Eigen::Vector4d &dX,
double gamma);
Eigen::Matrix<double, 6, 4> JacobianNumeric(double gamma,
double theta,
double alpha,
double d);
Eigen::Vector4d dampedLeastSquaresStep(const Eigen::Matrix<double, 6, 4> &J,
const Eigen::Matrix<double,6,1> &C_error);
// new kinematics with global heading
Eigen::Vector4d taskToConfigSpace(const Eigen::Vector4d &taskSpace);
Eigen::Vector4d configToTaskSpace(const Eigen::Vector4d &configSpace);
Eigen::Matrix4d JacobianNumericTaskSpace(const Eigen::Vector4d &configCurr);
Eigen::Vector4d JacobianStep(const Eigen::Vector4d &currTask, const Eigen::Vector4d &targetTask, const Eigen::Vector4d &currConfig);
Eigen::Vector4d JacobianStepSingle(const Eigen::Vector4d &currTask, const Eigen::Vector4d &targetTask, const Eigen::Vector4d &currConfig);
private:
// GEOMETRY CONSTANTS
double m_L; // constant length of distal bending section, for all ICE
double m_Rc; // radius of catheter
double m_dknob; // diameter of pulley inside the handle knob
// STATE
Eigen::Vector4d m_state;
// Helper functions
double wrapToPi(double lambda);
bool fZeroAlpha(const double c, double &alpha);
// time since last loop
// time between EM readings
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
static const double pi = boost::math::constants::pi<double>();
static const double deg180overPi = 180.0/pi;
static const double piOverDeg180 = pi/180.0;
template <typename T>
inline T lerp(const T v0, const T v1, const T t) {
return (1-t)*v0 + t*v1;
}
#endif // KINEMATICS_4DOF_H
| 4,361 | C | 35.35 | 142 | 0.583582 |
adegirmenci/HBL-ICEbot/ControllerWidget/controllerwidget.cpp | #include "controllerwidget.h"
#include "ui_controllerwidget.h"
ControllerWidget::ControllerWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::ControllerWidget),
gainWidget(new gainsWidget),
m_respModelWidget(new respModelWidget)
{
ui->setupUi(this);
m_worker = new ControllerThread();
m_worker->moveToThread(&m_thread);
connect(&m_thread, &QThread::finished, m_worker, &QObject::deleteLater);
m_thread.start();
connect(this, SIGNAL(tellWorkerToPrintThreadID()), m_worker, SLOT(printThreadID()));
connect(m_worker, SIGNAL(sendMsgToWidget(QString,int)),
this, SLOT(receiveMsgFromWorker(QString,int)));
connect(m_worker, SIGNAL(statusChanged(int)),
this, SLOT(workerStatusChanged(int)));
// updates
connect(this, SIGNAL(updateJointSpaceCommand(double,double,double,double)),
m_worker, SLOT(updateJointSpaceCommand(double,double,double,double)));
connect(this, SIGNAL(updateConfigSpaceCommand(double,double,double,double)),
m_worker, SLOT(updateConfigSpaceCommand(double,double,double,double)));
connect(this, SIGNAL(updateTaskSpaceCommand(double,double,double,double,bool)),
m_worker, SLOT(updateTaskSpaceCommand(double,double,double,double,bool)));
// control cycle signals
connect(this, SIGNAL(startControlCycle()), m_worker, SLOT(startControlCycle()));
connect(this, SIGNAL(stopControlCycle()), m_worker, SLOT(stopControlCycle()));
// reset BB
connect(this, SIGNAL(tellWorkerToResetBB()), m_worker, SLOT(resetBB()));
// Gains Widget
connect(gainWidget, SIGNAL(closeGainsWindow()), this, SLOT(on_adjustGainsButton_clicked()));
connect(gainWidget, SIGNAL(setGains(GainsPYRT)), m_worker, SLOT(setGains(GainsPYRT)));
connect(gainWidget, SIGNAL(setLimits(ConvergenceLimits)), m_worker, SLOT(setLimits(ConvergenceLimits)));
// Resp Model Widget
connect(m_respModelWidget, SIGNAL(closeRespModelWindow()), this, SLOT(on_respModelButton_clicked()));
connect(m_respModelWidget, SIGNAL(initializeRespModel()), m_worker, SLOT(initializeRespModel()));
connect(m_respModelWidget, SIGNAL(re_initializeRespModel()), m_worker, SLOT(re_initializeRespModel()));
connect(m_respModelWidget, SIGNAL(stopRespModel()), m_worker, SLOT(stopRespModel()));
connect(m_respModelWidget, SIGNAL(newFutureSamplesValue(int)), m_worker, SLOT(updateFutureSamples(int)));
// connect(m_worker, SIGNAL(sendDataToRespModelWidget(int,bool,bool,double,EigenVectorFiltered,EigenVectorFiltered,EigenVectorFiltered)),
// m_respModelWidget, SLOT(receiveDataFromRespModel(int,bool,bool,double,EigenVectorFiltered,EigenVectorFiltered,EigenVectorFiltered)));
connect(m_worker, SIGNAL(sendDataToRespModelWidget(int,bool,bool,double)),
m_respModelWidget, SLOT(receiveDataFromRespModel(int,bool,bool,double)));
connect(&(m_worker->m_respModel), SIGNAL(sendToPlotBird4(unsigned int, double, double)),
m_respModelWidget, SLOT(plotBird4(unsigned int,double,double)));
connect(m_respModelWidget, SIGNAL(changePlotFocus(int)),
&(m_worker->m_respModel), SLOT(setPlotFocus(int)));
// Sweep
connect(this, SIGNAL(workerStartSweep(uint,double,double,qint64)),
m_worker, SLOT(startSweep(uint,double,double,qint64)));
connect(this, SIGNAL(workerAbortSweep()),
m_worker, SLOT(abortSweep()));
// Initalize gains and limits to defaults
gainWidget->on_setGainsButton_clicked();
gainWidget->on_setLimitsButton_clicked();
// Mode Flags
connect(this, SIGNAL(updateModeFlags(ModeFlags)), m_worker, SLOT(setModeFlags(ModeFlags)));
// US angle
connect(this, SIGNAL(updateUSangle(double)), m_worker, SLOT(setUSangle(double)));
ui->jointSpaceGroupBox->setChecked(false);
ui->configSpaceGroupBox->setChecked(false);
// trajectory
m_keepDriving = false;
m_currTrajIdx = 0;
m_ctr = 0;
connect(m_worker, SIGNAL(reportCurrentXYZPSI(XYZPSI)), this, SLOT(receiveCurrentXYZPSI(XYZPSI)));
}
ControllerWidget::~ControllerWidget()
{
m_thread.quit();
m_thread.wait();
qDebug() << "Controller thread quit.";
gainWidget->close();
//m_respModelWidget->close();
emit m_respModelWidget->closeRespModelWindow();
delete gainWidget;
delete m_respModelWidget;
delete ui;
}
void ControllerWidget::workerStatusChanged(int status)
{
switch(status)
{
case CONTROLLER_INITIALIZED:
ui->controllerToggleButton->setEnabled(true);
ui->statusLineEdit->setText("Initialized.");
break;
case CONTROLLER_LOOP_STARTED:
ui->controllerToggleButton->setText( QStringLiteral("Stop Controller") );
ui->controllerToggleButton->setEnabled(true);
ui->statusLineEdit->setText("Running.");
break;
case CONTROLLER_LOOP_STOPPED:
ui->controllerToggleButton->setText( QStringLiteral("Start Controller") );
ui->controllerToggleButton->setEnabled(true);
ui->statusLineEdit->setText("Stopped.");
break;
case CONTROLLER_EPOCH_SET:
ui->statusTextEdit->appendPlainText("Epoch set.");
break;
case CONTROLLER_EPOCH_SET_FAILED:
ui->statusTextEdit->appendPlainText("Epoch set failed!");
break;
case CONTROLLER_RESET:
ui->statusTextEdit->appendPlainText("Controller reset.");
break;
case CONTROLLER_RESET_FAILED:
ui->statusTextEdit->appendPlainText("Controller reset failed!");
break;
default:
ui->statusTextEdit->appendPlainText("Unknown state!");
break;
}
}
void ControllerWidget::receiveMsgFromWorker(QString msg, int destination)
{
if(destination == 0)
{
ui->statusTextEdit->clear();
ui->statusTextEdit->appendPlainText(msg);
}
else
{
ui->statusLineEdit->setText(msg);
}
}
void ControllerWidget::on_testButton_clicked()
{
qDebug() << QTime::currentTime() << "Widget Thread ID: " << reinterpret_cast<int>(QThread::currentThreadId());
emit tellWorkerToPrintThreadID();
}
void ControllerWidget::on_taskSpaceGroupBox_toggled(bool arg1)
{
if(arg1 && ui->configSpaceGroupBox->isChecked())
ui->configSpaceGroupBox->setChecked(false);
if(arg1 && ui->jointSpaceGroupBox->isChecked())
ui->jointSpaceGroupBox->setChecked(false);
}
void ControllerWidget::on_configSpaceGroupBox_toggled(bool arg1)
{
if(arg1 && ui->taskSpaceGroupBox->isChecked())
ui->taskSpaceGroupBox->setChecked(false);
if(arg1 && ui->jointSpaceGroupBox->isChecked())
ui->jointSpaceGroupBox->setChecked(false);
}
void ControllerWidget::on_jointSpaceGroupBox_toggled(bool arg1)
{
if(arg1 && ui->configSpaceGroupBox->isChecked())
ui->configSpaceGroupBox->setChecked(false);
if(arg1 && ui->taskSpaceGroupBox->isChecked())
ui->taskSpaceGroupBox->setChecked(false);
}
void ControllerWidget::on_updateJointSpaceButton_clicked()
{
double pitch = ui->pitchSpinbox->value() * piOverDeg180;
double yaw = ui->yawSpinbox->value() * piOverDeg180;
double roll = ui->rollSpinbox->value() * piOverDeg180;
double trans = ui->transSpinbox->value();
ui->statusTextEdit->appendPlainText(QString("[%5] Joint Space Command: %1 %2 %3 %4")
.arg(pitch)
.arg(yaw)
.arg(roll)
.arg(trans)
.arg(QTime::currentTime().toString("HH:mm:ss")));
emit updateJointSpaceCommand(pitch, yaw, roll, trans);
}
void ControllerWidget::on_updateConfigSpaceButton_clicked()
{
double alpha = ui->alphaSpinbox->value() * piOverDeg180;
double theta = ui->thetaSpinbox->value() * piOverDeg180;
double gamma = ui->gammaSpinbox->value() * piOverDeg180;
double d = ui->dSpinbox->value();
ui->statusTextEdit->appendPlainText(QString("[%5] Config Space Command: %1 %2 %3 %4")
.arg(alpha)
.arg(theta)
.arg(gamma)
.arg(d)
.arg(QTime::currentTime().toString("HH:mm:ss")));
emit updateConfigSpaceCommand(alpha, theta, gamma, d);
}
void ControllerWidget::on_updateTaskSpaceButton_clicked()
{
double x = ui->xSpinbox->value();
double y = ui->ySpinbox->value();
double z = ui->zSpinbox->value();
double delPsi = ui->delPsiSpinbox->value() * piOverDeg180;
bool isAbsolute = ui->absoluteRadiobutton->isChecked();
ui->statusTextEdit->appendPlainText(QString("[%6] Task Space Command: %1 %2 %3 %4 %5")
.arg(x)
.arg(y)
.arg(z)
.arg(delPsi)
.arg(isAbsolute ? "Abs" : "Rel") // ? : ternary operator
.arg(QTime::currentTime().toString("HH:mm:ss")));
emit updateTaskSpaceCommand(x, y, z, delPsi, isAbsolute);
}
void ControllerWidget::on_controllerToggleButton_clicked()
{
ui->controllerToggleButton->setEnabled(false); // disable button
if(m_worker->isControlling())
{
// TODO: this should stop LabJack collection
emit stopControlCycle();
}
else
{
// TODO: this should trigger LabJack collection
emit startControlCycle();
}
}
void ControllerWidget::on_resetBB_Button_clicked()
{
emit tellWorkerToResetBB();
}
void ControllerWidget::on_adjustGainsButton_clicked()
{
if(gainWidget->isHidden())
{
ui->adjustGainsButton->setText("Hide Gains");
gainWidget->show();
gainWidget->raise();
}
else
{
ui->adjustGainsButton->setText("Adjust Gains");
//gainWidget->hide();
gainWidget->close();
}
}
void ControllerWidget::on_relativeRadiobutton_clicked()
{
ui->xSpinbox->setValue(0.0);
ui->ySpinbox->setValue(0.0);
ui->zSpinbox->setValue(0.0);
ui->delPsiSpinbox->setValue(0.0);
}
void ControllerWidget::on_absoluteRadiobutton_clicked()
{
ui->xSpinbox->setValue(0.0);
ui->ySpinbox->setValue(0.0);
ui->zSpinbox->setValue(70.0);
ui->delPsiSpinbox->setValue(0.0);
}
void ControllerWidget::on_updateFlagsButton_clicked()
{
ModeFlags flags;
// int coordFrame;
// int tethered;
// int instTrackState;
// int instTrackMode;
// int EKFstate;
// int inVivoMode;
if(ui->mobileRadioButton->isChecked())
flags.coordFrame = COORD_FRAME_MOBILE;
else if(ui->worldRadioButton->isChecked())
flags.coordFrame = COORD_FRAME_WORLD;
else{
qDebug() << "coordFrame: State not recognized!"; return; }
if(ui->relativeModeRadioButton->isChecked())
flags.tethered = MODE_RELATIVE;
else if(ui->tetheredModeRadioButton->isChecked())
flags.tethered = MODE_TETHETERED;
else{
qDebug() << "tethered: State not recognized!"; return; }
if(ui->ITonRadioButton->isChecked())
flags.instTrackState = INST_TRACK_ON;
else if(ui->IToffRadioButton->isChecked())
flags.instTrackState = INST_TRACK_OFF;
else{
qDebug() << "instTrackState: State not recognized!"; return; }
if(ui->imagerRadioButton->isChecked())
flags.instTrackMode = INST_TRACK_IMAGER;
else if(ui->positionRadioButton->isChecked())
flags.instTrackMode = INST_TRACK_POSITION;
else{
qDebug() << "instTrackMode: State not recognized!"; return; }
if(ui->EKFonRadioButton->isChecked())
flags.EKFstate = EKF_ON;
else if(ui->EKFoffRadioButton->isChecked())
flags.EKFstate = EKF_OFF;
else{
qDebug() << "EKFstate: State not recognized!"; return; }
if(ui->InVivoOnRadioButton->isChecked())
flags.inVivoMode = IN_VIVO_ON;
else if(ui->InVivoOffRadioButton->isChecked())
flags.inVivoMode = IN_VIVO_OFF;
else{
qDebug() << "inVivoMode: State not recognized!"; return; }
emit updateModeFlags(flags);
}
void ControllerWidget::on_setUSangleButton_clicked()
{
double usAngle = ui->usAngleSpinBox->value();
emit updateUSangle(usAngle);
}
void ControllerWidget::on_respModelButton_clicked()
{
if(m_respModelWidget->isHidden())
{
ui->respModelButton->setText("Close RespModel Win");
m_respModelWidget->show();
m_respModelWidget->raise();
}
else
{
ui->respModelButton->setText("Respiration Model");
m_respModelWidget->close();
}
}
void ControllerWidget::receiveCurrentXYZPSI(XYZPSI currXYZPSI)
{
m_currXYZPSI = currXYZPSI;
if( (m_ctr % 5) == 0 )
{
ui->currXspinbox->setValue(currXYZPSI.x);
ui->currYspinbox->setValue(currXYZPSI.y);
ui->currZspinbox->setValue(currXYZPSI.z);
ui->currDelPsiSpinbox->setValue(currXYZPSI.psi);
}
m_ctr++;
}
void ControllerWidget::on_trajOpenFileButton_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Open CSV File"),
"../ICEbot_QT_v1/LoggedData",
tr("CSV File (*.csv)"));
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << file.errorString();
return;
}
QTextStream in(&file);
m_XYZPSIs.clear();
while (!in.atEnd()) {
QString line = in.readLine();
QStringList split = line.split(','); // files are generated using dlmwrite in MATLAB
if(split.size() == 4)
{
XYZPSI xyzpsi;
xyzpsi.x = split[0].toDouble();
xyzpsi.y = split[1].toDouble();
xyzpsi.z = split[2].toDouble();
xyzpsi.psi = split[3].toDouble() * piOverDeg180; // convert to radians
double signedPI = boost::math::copysign(pi, xyzpsi.psi);
xyzpsi.psi = fmod(xyzpsi.psi + signedPI,(2*pi)) - signedPI;
m_XYZPSIs.push_back(xyzpsi);
}
else
{
qDebug() << "Error reading CSV - number of elements in line is not equal to 4!";
break;
}
}
qDebug() << "Read" << m_XYZPSIs.size() << "setpoints from trajectory file.";
if(m_XYZPSIs.size() > 0){
ui->trajDriveButton->setEnabled(true);
ui->trajStepLineEdit->setText(QString("%1 points loaded.").arg(m_XYZPSIs.size()));
}
else{
ui->trajDriveButton->setEnabled(false);
ui->trajStepLineEdit->setText("Error reading file.");
}
}
void ControllerWidget::on_trajDriveButton_clicked()
{
if(m_keepDriving)
{
m_keepDriving = false;
ui->trajDriveButton->setText("Drive");
// stop timer
m_trajTimer->stop();
disconnect(m_trajTimer, SIGNAL(timeout()), 0, 0);
delete m_trajTimer;
}
else
{
m_keepDriving = true;
ui->trajDriveButton->setText("Stop");
m_currTrajIdx = 0;
ui->trajStepLineEdit->setText(QString("%1 of %2.").arg(m_currTrajIdx).arg(m_XYZPSIs.size()));
XYZPSI targetXYZPSI = m_XYZPSIs[m_currTrajIdx];
// send to worker
emit updateTaskSpaceCommand(targetXYZPSI.x, targetXYZPSI.y, targetXYZPSI.z, targetXYZPSI.psi, true);
// update spinbox in UI
ui->xSpinbox->setValue(targetXYZPSI.x);
ui->ySpinbox->setValue(targetXYZPSI.y);
ui->zSpinbox->setValue(targetXYZPSI.z);
ui->delPsiSpinbox->setValue(targetXYZPSI.psi * deg180overPi);
// start timer
m_trajTimer = new QTimer(this);
connect(m_trajTimer, SIGNAL(timeout()), this, SLOT(driveTrajectory()));
m_trajTimer->start(10);
}
}
void ControllerWidget::driveTrajectory()
{
XYZPSI targetXYZPSI = m_XYZPSIs[m_currTrajIdx];
if( (abs(m_currXYZPSI.x - targetXYZPSI.x) < 0.75) &&
(abs(m_currXYZPSI.y - targetXYZPSI.y) < 0.75) &&
(abs(m_currXYZPSI.z - targetXYZPSI.z) < 0.75) && m_keepDriving)
{
m_currTrajIdx++;
ui->trajStepLineEdit->setText(QString("%1 of %2.").arg(m_currTrajIdx).arg(m_XYZPSIs.size()));
if(m_currTrajIdx < m_XYZPSIs.size())
{
// get next traget
targetXYZPSI = m_XYZPSIs[m_currTrajIdx];
// send to worker
emit updateTaskSpaceCommand(targetXYZPSI.x, targetXYZPSI.y, targetXYZPSI.z, targetXYZPSI.psi, true);
// update spinbox in UI
ui->xSpinbox->setValue(targetXYZPSI.x);
ui->ySpinbox->setValue(targetXYZPSI.y);
ui->zSpinbox->setValue(targetXYZPSI.z);
ui->delPsiSpinbox->setValue(targetXYZPSI.psi * deg180overPi);
qDebug() << "Drive to" << targetXYZPSI.x << targetXYZPSI.y << targetXYZPSI.z << targetXYZPSI.psi;
}
else
{
m_keepDriving = false;
ui->trajDriveButton->setText("Drive");
}
}
}
void ControllerWidget::on_sweepButton_clicked()
{
unsigned int nSteps = ui->numSweepsSpinBox->value();
double stepAngle = ui->sweepStepDblSpinBox->value() * piOverDeg180;
double convLimit = ui->sweepThreshDblSpinBox->value() * piOverDeg180;
qint64 imgDuration = ui->acqTimeMsSpinBox->value();
emit workerStartSweep(nSteps, stepAngle, convLimit, imgDuration);
}
void ControllerWidget::on_abortSweepButton_clicked()
{
emit workerAbortSweep();
}
| 17,623 | C++ | 32.762452 | 147 | 0.629915 |
adegirmenci/HBL-ICEbot/ControllerWidget/respmodelwidget.h | #ifndef RESPMODELWIDGET_H
#define RESPMODELWIDGET_H
#include <QWidget>
#include <QCloseEvent>
#include "filtfilt.h"
#include "../icebot_definitions.h"
namespace Ui {
class respModelWidget;
}
class respModelWidget : public QWidget
{
Q_OBJECT
public:
explicit respModelWidget(QWidget *parent = 0);
~respModelWidget();
signals:
void closeRespModelWindow();
void initializeRespModel();
void re_initializeRespModel();
void stopRespModel();
void newFutureSamplesValue(int n);
void changePlotFocus(int idx);
private slots:
void on_closeButton_clicked();
void on_initializeButton_clicked();
void on_futureSamplesSpinBox_valueChanged(int arg1);
void on_reInitButton_clicked();
void receiveDataFromRespModel(int numSamples,
bool isTrained,
bool inVivoMode,
double omega0);//,
//EigenVectorFiltered Bird4_filtered,
//EigenVectorFiltered Bird4_filtered_new,
//EigenVectorFiltered breathSignalFromModel);
void plotBird4(unsigned int plotID, double time, double value);
void on_stopButton_clicked();
void on_bird4RadioButton_clicked();
void on_CTradioButton_clicked();
private:
Ui::respModelWidget *ui;
void closeEvent(QCloseEvent *event);
double m_lastPlotKey; // to limit update rate of plot
};
#endif // RESPMODELWIDGET_H
| 1,530 | C | 20.871428 | 80 | 0.630719 |
adegirmenci/HBL-ICEbot/ControllerWidget/cyclicmodel.h | #ifndef CYCLICMODEL_H
#define CYCLICMODEL_H
#include <QObject>
#include <vector>
#include <algorithm>
#include <iostream>
#include <memory>
#include <limits>
#include <Eigen/Dense>
#include <Eigen/SVD>
#include <Eigen/Geometry>
#include <QString>
#include <QDir>
#include <QFile>
#include <QDataStream>
#include <QTextStream>
#include <QDebug>
#include <QElapsedTimer>
#include <QtConcurrent/QtConcurrentRun>
#include <QFuture>
#include <QDateTime>
#include "filtfilt.h"
#include "../icebot_definitions.h"
class CyclicModel : public QObject
{
Q_OBJECT
public:
explicit CyclicModel(QObject *parent = 0);
~CyclicModel();
// void operator = (const CyclicModel &Other);
// add training data
void addTrainingObservation(const EigenAffineTransform3d &T_BB_CT_curTipPos,
const EigenAffineTransform3d &T_BB_targetPos,
const EigenAffineTransform3d &T_Box_BBmobile,
const EigenAffineTransform3d &T_BB_Box,
const EigenAffineTransform3d &T_Bird4,
const double sampleTime);
// reset model
void resetModel();
// get initial model
void trainModel();
// add respiration data
void addObservation(const EigenAffineTransform3d &T_Bird4,
const double sampleTime);
// update the period
void updatePeriod(const double period);
void updateNfutureSamples(int n) { m_nFutureSamples = n; }
// Accessors
const size_t getNumSamples() { return m_numSamples; }
const bool isTrained() { return m_isTrained; }
const bool isInVivoMode() { return m_isInVivo; }
const double getOmega() { return m_omega0; }
void setInVivo(const bool isInVivo);
EigenVectorFiltered get_Bird4_filtered() { return m_Bird4_filtered; }
EigenVectorFiltered get_Bird4_filtered_new() { return m_Bird4_filtered_new; }
EigenVectorFiltered get_breathSignalFromModel() { return m_breathSignalFromModel; }
EigenVector7d getT_BBfixed_CT_des() { return m_BBfixed_CT_des; }
EigenVector7d getT_BBfixed_CTtraj_future_des() { return m_BBfixed_CTtraj_future_des; }
EigenVector7d getT_BBfixed_BB_des() { return m_BBfixed_BB_des; }
// testing function - external data load and save
void loadData(QString filename, std::vector<double> &X);
void load4x4Data(QString filename, EigenStdVecVector7d &X);
void load4x4Data(QString filename, std::vector<std::vector<double>> &X);
void saveFilteredData(QString filename, const std::vector<double> &Y);
void saveFilteredData(QString filename, const EigenVectorFiltered &Y);
void save4x4FilteredData(QString filename, const EigenStdVecVector7d &Y);
void save4x4FilteredData(QString filename, const EigenMatrixFiltered &Y);
void testLPF();
public slots:
void setPlotFocus(int idx);
signals:
void sendToPlotBird4(unsigned int plotID, double time, double val);
private:
void retrainModel();
void filterTrainingData();
void filterNewObservations();
double peakDetector(const bool runForInit);
void peakDetectorForBreathModel();
double getPrediction(const double timeShift,
const EigenVectorPolar &x_polar,
const EigenVectorRectangular &x_rect);
void getPrediction7Axis(const double timeShift,
const EigenMatrixPolar &x_polar,
const EigenMatrixRectangular &x_rect,
EigenVector7d &X_des,
const double phase);
void cycle_recalculate(const EigenMatrixFiltered &z_init,
EigenMatrixRectangular &x_rect,
EigenMatrixPolar &x_polar, const double omega0);
void cycle_recalculate(const EigenVectorFiltered &z_init,
EigenVectorRectangular &x_rect,
EigenVectorPolar &x_polar, const double omega0);
Eigen::MatrixXd cycle_recalculate_concurrentM(const EigenMatrixFiltered &z_init, const double omega0, const std::vector<double> &timeData);
Eigen::VectorXd cycle_recalculate_concurrentV(const EigenVectorFiltered &z_init, const double omega0, const std::vector<double> &timeData);
// data members
// Low Pass Filter
filtfilt m_LowPassFilter;
// UNFILTERED DATA
// x,y,z,xaxis,yaxis,zaxis,angle - only needed for training
// TODO : how does replacing EigenStdVecVector7d with EigenMatrixFiltered affect performance?
EigenStdVecVector7d m_BBfixed_CT, // this stores all of the incoming CT points
m_BBfixed_Instr, // this stores all of the incoming instr_x points
m_BBfixed_BB; // this stores all of the incoming BB points
// for the chest tracker, we only the need the x (benchtop) or -z (in vivo) axis of this
std::vector<double> m_Bird4, // this remains constant after initialization
m_Bird4_new; // most recent chest tracker data
// FILTERED DATA
// 7 components: x,y,z,xaxis,yaxis,zaxis,angle
EigenMatrixFiltered m_BBfixed_CT_filtered, // this remains constant after initialization
m_BBfixed_BB_filtered; // this remains constant after initialization
// for the chest tracker, we only the need the x (benchtop) or -z (in vivo) axis of this
EigenVectorFiltered m_Bird4_filtered, // this remains constant after initialization
m_Bird4_filtered_new, // most recent filtered chest tracker data
m_breathSignalFromModel;
// ***CURRENT*** RECTANGULAR COMPONENTS
EigenMatrixRectangular m_BBfixed_CT_rectangular, // 7 components: x,y,z,xaxis,yaxis,zaxis,angle
m_BBfixed_BB_rectangular; // 7 components: x,y,z,xaxis,yaxis,zaxis,angle
EigenVectorRectangular m_Bird4_rectangular; // 1 component : x (benchtop) or -z (in vivo)
// ***CURRENT*** POLAR COMPONENTS
EigenMatrixPolar m_BBfixed_CT_polar, // 7 components: x,y,z,xaxis,yaxis,zaxis,angle
m_BBfixed_BB_polar; // 7 components: x,y,z,xaxis,yaxis,zaxis,angle
EigenVectorPolar m_Bird4_polar; // 1 component : x (benchtop) or -z (in vivo)
// MODEL-BASED ESTIMATES OF CURRENT AND FUTURE POSITIONS
EigenVector7d m_BBfixed_CT_des,
m_BBfixed_CTtraj_future_des,
m_BBfixed_BB_des;
// TIME DATA
std::vector<double> m_timeData_init, // stores the time vector for the model initialization observations
m_timeData_new; // stores time for the most recent observations
// PEAK DATA - MEAN OF THE LEFT AND RIGHT
std::vector<double> m_respPeakMean, m_breathSignalPeakMean;
size_t m_nFutureSamples; // how much into the future should we look?
double m_omega0; // frequency
double m_omega0_init;
std::vector<double> m_periods;
size_t m_numSamples; // number of observations added IN TOTAL
bool m_isTrained; // is the model trained
qint64 m_lastTrainingTimestamp; // when last training was performed
bool m_isInVivo; // are we in IN VIVO mode
int m_plotFocus;
// concurrent execution
QFuture<Eigen::MatrixXd> mConcurrent1, mConcurrent2;
QFuture<Eigen::VectorXd> mConcurrent3;
Eigen::MatrixXd m_BBfixed_CT_polarRect;
Eigen::MatrixXd m_BBfixed_BB_polarRect;
Eigen::VectorXd m_Bird4_polarRect;
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
#endif // CYCLICMODEL_H
| 7,516 | C | 38.563158 | 143 | 0.669505 |
adegirmenci/HBL-ICEbot/ControllerWidget/filtfilt.cpp | #include "filtfilt.h"
filtfilt::filtfilt()
{
m_A = {1};
// From MATLAB : m_B = fir1(50,(100/60/2)/(150/2),'low'); // order 50, 100 bpm, 150 Hz sampling
// m_B = {0.00264726249703924, 0.00279642405272151, 0.00319013679531822, 0.00382941384359819,
// 0.00471069197708524, 0.00582582662708399, 0.00716217671948781, 0.00870277868575645,
// 0.0104266071117473, 0.0123089176854006, 0.0143216663725929, 0.0164339971333124,
// 0.0186127890229487, 0.0208232522381201, 0.0230295615915197, 0.0251955150597567,
// 0.0272852044611377, 0.0292636850004373, 0.0310976303728649, 0.0327559603516814,
// 0.0342104282892947, 0.0354361567303369, 0.0364121103516330, 0.0371214966872074,
// 0.0375520865406890, 0.0376964476024575, 0.0375520865406890, 0.0371214966872074,
// 0.0364121103516330, 0.0354361567303369, 0.0342104282892947, 0.0327559603516814,
// 0.0310976303728649, 0.0292636850004373, 0.0272852044611377, 0.0251955150597567,
// 0.0230295615915197, 0.0208232522381201, 0.0186127890229487, 0.0164339971333124,
// 0.0143216663725929, 0.0123089176854006, 0.0104266071117473, 0.00870277868575645,
// 0.00716217671948781, 0.00582582662708399, 0.00471069197708524, 0.00382941384359819,
// 0.00319013679531822, 0.00279642405272151, 0.00264726249703924};
size_t filterOrder = FILTER_ORDER + 1; // must be odd!
double deltaT = SAMPLE_DELTA_TIME;
double samplingFreq = 1.0/deltaT;
double band = (HEART_RATE/60./2.)/(samplingFreq/2.);
m_zzi = std::allocate_shared< Eigen::MatrixXd >( Eigen::aligned_allocator<Eigen::MatrixXd>() );
m_B = FIR_LPF_LeastSquares(filterOrder, band);
// for(auto x : m_B)
// std::cout << x << std::endl;
updateFilterParameters();
}
filtfilt::~filtfilt()
{
}
void filtfilt::run(const std::vector<double> &X, std::vector<double> &Y)
{
int len = X.size(); // length of input
if (len <= m_nfact)
{
std::cerr << "Input data too short! Data must have length more than 3 times filter order." << std::endl;
return;
}
std::vector<double> leftpad = subvector_reverse(X, m_nfact, 1);
double _2x0 = 2 * X[0];
std::transform(leftpad.begin(), leftpad.end(), leftpad.begin(), [_2x0](double val) {return _2x0 - val; });
std::vector<double> rightpad = subvector_reverse(X, len - 2, len - m_nfact - 1);
double _2xl = 2 * X[len-1];
std::transform(rightpad.begin(), rightpad.end(), rightpad.begin(), [_2xl](double val) {return _2xl - val; });
double y0;
std::vector<double> signal1, signal2, zi;
signal1.reserve(leftpad.size() + X.size() + rightpad.size());
append_vector(signal1, leftpad);
append_vector(signal1, X);
append_vector(signal1, rightpad);
zi.resize(m_zzi->size());
// Do the forward and backward filtering
y0 = signal1[0];
std::transform(m_zzi->data(), m_zzi->data() + m_zzi->size(), zi.begin(), [y0](double val){ return val*y0; });
filter(signal1, signal2, zi);
std::reverse(signal2.begin(), signal2.end());
y0 = signal2[0];
std::transform(m_zzi->data(), m_zzi->data() + m_zzi->size(), zi.begin(), [y0](double val){ return val*y0; });
filter(signal2, signal1, zi);
Y = subvector_reverse(signal1, signal1.size() - m_nfact - 1, m_nfact);
}
void filtfilt::run(const std::vector<double> &X, EigenVectorFiltered &Y)
{
int len = X.size(); // length of input
if (len <= m_nfact)
{
std::cerr << "Input data too short! Data must have length more than 3 times filter order." << std::endl;
return;
}
std::vector<double> leftpad = subvector_reverse(X, m_nfact, 1);
double _2x0 = 2 * X[0];
std::transform(leftpad.begin(), leftpad.end(), leftpad.begin(), [_2x0](double val) {return _2x0 - val; });
std::vector<double> rightpad = subvector_reverse(X, len - 2, len - m_nfact - 1);
double _2xl = 2 * X[len-1];
std::transform(rightpad.begin(), rightpad.end(), rightpad.begin(), [_2xl](double val) {return _2xl - val; });
double y0;
std::vector<double> signal1, signal2, zi;
signal1.reserve(leftpad.size() + X.size() + rightpad.size());
append_vector(signal1, leftpad);
append_vector(signal1, X);
append_vector(signal1, rightpad);
zi.resize(m_zzi->size());
// Do the forward and backward filtering
y0 = signal1[0];
std::transform(m_zzi->data(), m_zzi->data() + m_zzi->size(), zi.begin(), [y0](double val){ return val*y0; });
filter(signal1, signal2, zi);
std::reverse(signal2.begin(), signal2.end());
y0 = signal2[0];
std::transform(m_zzi->data(), m_zzi->data() + m_zzi->size(), zi.begin(), [y0](double val){ return val*y0; });
filter(signal2, signal1, zi);
subvector_reverseEig(signal1, signal1.size() - m_nfact - 1 - EDGE_EFFECT, m_nfact + EDGE_EFFECT, Y);
}
void filtfilt::run(const EigenStdVecVector7d &X, EigenStdVecVector7d &Y)
{
int len = X.size(); // length of input
if (len <= m_nfact)
{
std::cerr << "Input data too short! Data must have length more than 3 times filter order." << std::endl;
return;
}
EigenStdVecVector7d leftpad = subvector_reverseEig(X, m_nfact, 1);
EigenVector7d _2x0 = X[0] * 2.0;
std::transform(leftpad.begin(), leftpad.end(), leftpad.begin(), [_2x0](EigenVector7d val) {return _2x0 - val; });
EigenStdVecVector7d rightpad = subvector_reverseEig(X, len - 2, len - m_nfact - 1);
EigenVector7d _2xl = X[len-1] * 2.0;
std::transform(rightpad.begin(), rightpad.end(), rightpad.begin(), [_2xl](EigenVector7d val) {return _2xl - val; });
EigenVector7d y0;
EigenStdVecVector7d signal1, signal2, zi;
// signal1.reserve(leftpad.size() + X.size() + rightpad.size());
append_vector(signal1, leftpad);
append_vector(signal1, X);
append_vector(signal1, rightpad);
zi.resize(m_zzi->size());
// Do the forward and backward filtering
y0 = signal1[0];
std::transform(m_zzi->data(), m_zzi->data() + m_zzi->size(), zi.begin(), [y0](double val){ return y0 * val; });
filter(signal1, signal2, zi);
std::reverse(signal2.begin(), signal2.end());
y0 = signal2[0];
std::transform(m_zzi->data(), m_zzi->data() + m_zzi->size(), zi.begin(), [y0](double val){ return y0 * val; });
filter(signal2, signal1, zi);
Y = subvector_reverseEig(signal1, signal1.size() - m_nfact - 1, m_nfact);
}
void filtfilt::run(const EigenStdVecVector7d &X, EigenMatrixFiltered &Y)
{
int len = X.size(); // length of input , should be equal to N_INPUTS
if (len <= m_nfact)
{
std::cerr << "Input data too short! Data must have length more than 3 times filter order." << std::endl;
return;
}
EigenStdVecVector7d leftpad = subvector_reverseEig(X, m_nfact, 1);
EigenVector7d _2x0 = X[0] * 2.0;
std::transform(leftpad.begin(), leftpad.end(), leftpad.begin(), [_2x0](EigenVector7d val) {return _2x0 - val; });
EigenStdVecVector7d rightpad = subvector_reverseEig(X, len - 2, len - m_nfact - 1);
EigenVector7d _2xl = X[len-1] * 2.0;
std::transform(rightpad.begin(), rightpad.end(), rightpad.begin(), [_2xl](EigenVector7d val) {return _2xl - val; });
EigenVector7d y0;
EigenStdVecVector7d signal1, signal2, zi;
// signal1.reserve(leftpad.size() + X.size() + rightpad.size());
append_vector(signal1, leftpad);
append_vector(signal1, X);
append_vector(signal1, rightpad);
zi.resize(m_zzi->size());
// Do the forward and backward filtering
y0 = signal1[0];
std::transform(m_zzi->data(), m_zzi->data() + m_zzi->size(), zi.begin(), [y0](double val){ return y0 * val; });
filter(signal1, signal2, zi);
std::reverse(signal2.begin(), signal2.end());
y0 = signal2[0];
std::transform(m_zzi->data(), m_zzi->data() + m_zzi->size(), zi.begin(), [y0](double val){ return y0 * val; });
filter(signal2, signal1, zi);
subvector_reverseEig(signal1, signal1.size() - m_nfact - EDGE_EFFECT - 1, m_nfact + EDGE_EFFECT, Y);
}
void filtfilt::filter(const std::vector<double> &X, std::vector<double> &Y, std::vector<double> &Zi)
{
size_t input_size = X.size();
//size_t filter_order = std::max(m_A.size(), m_B.size());
size_t filter_order = m_nfilt;
// m_B.resize(filter_order, 0);
// m_A.resize(filter_order, 0);
Zi.resize(filter_order, 0);
Y.resize(input_size);
const double *x = &X[0];
const double *b = &m_B[0];
const double *a = &m_A[0];
double *z = &Zi[0];
double *y = &Y[0];
// QElapsedTimer elTimer;
// elTimer.start();
for (size_t i = 0; i < input_size; ++i)
{
size_t order = filter_order - 1;
while (order)
{
if (i >= order)
{
z[order - 1] = b[order] * x[i - order] - a[order] * y[i - order] + z[order];
}
--order;
}
y[i] = b[0] * x[i] + z[0];
}
Zi.resize(filter_order - 1);
// qint64 elNsec = elTimer.nsecsElapsed();
// std::cout << "\nNsec elapsed:" << elNsec << std::endl;
}
void filtfilt::filter(const EigenStdVecVector7d &X, EigenStdVecVector7d &Y, EigenStdVecVector7d &Zi)
{
size_t input_size = X.size();
//size_t filter_order = std::max(m_A.size(), m_B.size());
size_t filter_order = m_nfilt;
// m_B.resize(filter_order, 0);
// m_A.resize(filter_order, 0);
Zi.resize(filter_order, EigenVector7d::Zero());
Y.resize(input_size);
// const EigenVector7d *x = &X[0];
const double *b = &m_B[0];
const double *a = &m_A[0];
// EigenVector7d *z = &Zi[0];
// EigenVector7d *y = &Y[0];
// QElapsedTimer elTimer;
// elTimer.start();
for (size_t i = 0; i < input_size; ++i)
{
size_t order = filter_order - 1;
// if(i < order)
// order = i; // may lead to tiny tiny speedup
while (order)
{
if (i >= order)
{
Zi[order - 1] = (X[i - order] * b[order] - Y[i - order] * a[order] + Zi[order]).eval();
}
--order;
}
Y[i] = X[i] * b[0] + Zi[0];
}
Zi.resize(filter_order - 1);
// qint64 elNsec = elTimer.nsecsElapsed();
// std::cout << "\nNsec elapsed:" << elNsec << std::endl;
}
void filtfilt::setFilterCoefficients(const std::vector<double> &B, const std::vector<double> &A)
{
m_A = A;
m_B = B;
updateFilterParameters();
}
void filtfilt::updateFilterParameters()
{
m_na = m_A.size();
m_nb = m_B.size();
m_nfilt = (m_nb > m_na) ? m_nb : m_na;
m_nfact = 3 * (m_nfilt - 1); // length of edge transients
// set up filter's initial conditions to remove DC offset problems at the
// beginning and end of the sequence
m_B.resize(m_nfilt, 0);
m_A.resize(m_nfilt, 0);
m_rows.clear(); m_cols.clear();
//rows = [1:nfilt-1 2:nfilt-1 1:nfilt-2];
add_index_range(m_rows, 0, m_nfilt - 2);
if (m_nfilt > 2)
{
add_index_range(m_rows, 1, m_nfilt - 2);
add_index_range(m_rows, 0, m_nfilt - 3);
}
//cols = [ones(1,nfilt-1) 2:nfilt-1 2:nfilt-1];
add_index_const(m_cols, 0, m_nfilt - 1);
if (m_nfilt > 2)
{
add_index_range(m_cols, 1, m_nfilt - 2);
add_index_range(m_cols, 1, m_nfilt - 2);
}
// data = [1+a(2) a(3:nfilt) ones(1,nfilt-2) -ones(1,nfilt-2)];
auto klen = m_rows.size();
m_data.clear();
m_data.resize(klen);
m_data[0] = 1 + m_A[1]; int j = 1;
if (m_nfilt > 2)
{
for (int i = 2; i < m_nfilt; i++)
m_data[j++] = m_A[i];
for (int i = 0; i < m_nfilt - 2; i++)
m_data[j++] = 1.0;
for (int i = 0; i < m_nfilt - 2; i++)
m_data[j++] = -1.0;
}
// Calculate initial conditions
Eigen::MatrixXd sp = Eigen::MatrixXd::Zero(max_val(m_rows) + 1, max_val(m_cols) + 1);
for (size_t k = 0; k < klen; ++k)
{
sp(m_rows[k], m_cols[k]) = m_data[k];
}
auto bb = Eigen::VectorXd::Map(m_B.data(), m_B.size());
auto aa = Eigen::VectorXd::Map(m_A.data(), m_A.size());
(*m_zzi) = (sp.inverse() * (bb.segment(1, m_nfilt - 1) - (bb(0) * aa.segment(1, m_nfilt - 1))));
if (m_A.empty())
{
std::cerr << "The feedback filter coefficients are empty." << std::endl;
}
if (std::all_of(m_A.begin(), m_A.end(), [](double coef){ return coef == 0; }))
{
std::cerr << "At least one of the feedback filter coefficients has to be non-zero." << std::endl;
}
if (m_A[0] == 0)
{
std::cerr << "First feedback coefficient has to be non-zero." << std::endl;
}
// Normalize feedback coefficients if a[0] != 1;
auto a0 = m_A[0];
if (a0 != 1.0)
{
std::transform(m_A.begin(), m_A.end(), m_A.begin(), [a0](double v) { return v / a0; });
std::transform(m_B.begin(), m_B.end(), m_B.begin(), [a0](double v) { return v / a0; });
}
}
void filtfilt::add_index_range(std::vector<int> &indices, int beg, int end, int inc)
{
for (int i = beg; i <= end; i += inc)
{
indices.push_back(i);
}
}
void filtfilt::add_index_const(std::vector<int> &indices, int value, size_t numel)
{
while (numel--)
{
indices.push_back(value);
}
}
void filtfilt::append_vector(std::vector<double> &vec, const std::vector<double> &tail)
{
vec.insert(vec.end(), tail.begin(), tail.end());
}
void filtfilt::append_vector(EigenStdVecVector7d &vec, const EigenStdVecVector7d &tail)
{
vec.insert(vec.end(), tail.begin(), tail.end());
}
std::vector<double> filtfilt::subvector_reverse(const std::vector<double> &vec, int idx_end, int idx_start)
{
std::vector<double> result(&vec[idx_start], &vec[idx_end+1]);
std::reverse(result.begin(), result.end());
return result;
}
EigenStdVecVector7d filtfilt::subvector_reverseEig(const EigenStdVecVector7d &vec, int idx_end, int idx_start)
{
EigenStdVecVector7d result(&vec[idx_start], &vec[idx_end+1]);
std::reverse(result.begin(), result.end());
return result;
}
void filtfilt::subvector_reverseEig(const std::vector<double> &vec, int idx_end, int idx_start,
EigenVectorFiltered &Y)
{
Eigen::Map<const EigenVectorFiltered> temp(&vec[idx_start], idx_end - idx_start + 1);
Y = temp.reverse();
}
void filtfilt::subvector_reverseEig(const EigenStdVecVector7d &vec, int idx_end, int idx_start,
EigenMatrixFiltered &Y)
{
Y = EigenMatrixFiltered::Zero(idx_end - idx_start + 1, 7);
for(size_t i = 0; i < (idx_end - idx_start + 1); i++)
{
Y.row(i) = vec[idx_end - i];
}
}
// L should be odd
std::vector<double> filtfilt::FIR_LPF_LeastSquares(size_t L, const double deltaT)
{
if(deltaT > 1.0)
std::cerr << "deltaT is too large, sample faster!!!" << std::endl;
std::vector<double> F = {0.0, deltaT/2.0, deltaT/2.0, 0.5},
dF = {deltaT/2.0, 0.0, 0.5 - deltaT/2.0},
M = {1,1,0,0},
W = {1,1};
// size_t fullBand = 1, constantWeights = 1;
size_t N = L;
L = (N-1)/2;
// k=m=(0:L); // Type-I
double b0 = 0.0;
std::vector<double> b(L, 0.0);
std::vector<size_t> m(L+1), k(L);
for(size_t i = 0; i < m.size(); i++)
m[i] = i;
for(size_t i = 0; i < k.size(); i++)
k[i] = m[i+1];
for(size_t s = 0; s < 3; s += 2)
{
// m=(M(s+1)-M(s))/(F(s+1)-F(s)); % slope
// b1=M(s)-m*F(s); % y-intercept
//double m_ = (M[s+1] - M[s])/(F[s+1] - F[s]);
double b1 = M[s];// - m_*F[s];
//b0 = b0 + (b1*(F(s+1)-F(s)) + m/2*(F(s+1)*F(s+1)-F(s)*F(s)))* abs(W((s+1)/2)^2) ;
//b0 += ( b1*(F[s+1]-F[s]) + m_/2.0*(F[s+1]*F[s+1]-F[s]*F[s]) );//* pow(W[(s+1)/2],2); W = 1 anyways
b0 += b1*(F[s+1]-F[s]);
//b = b+(m/(4*pi*pi)*(cos(2*pi*k*F(s+1))-cos(2*pi*k*F(s)))./(k.*k))...
// * abs(W((s+1)/2)^2);
//b = b + (F(s+1)*(m*F(s+1)+b1)*sinc(2*k*F(s+1)) ...
// - F(s)*(m*F(s)+b1)*sinc(2*k*F(s))) ...
// * abs(W((s+1)/2)^2);
// sinc(x) = sin(pi*x)/(pi*x); ->> (sin(pi*2.0*k[i]*F[s+1])/(pi*2.0*k[i]*F[s+1]))
for(size_t i = 0; i < b.size(); i++)
{
double sinc_ = boost::math::sinc_pi(pi*2.0*k[i]*F[s+1]);
//b[i] += (m_/(4.0*pi*pi)*(cos(2.0*pi*k[i]*F[s+1])-cos(2.0*pi*k[i]*F[s]))/(1.0*k[i]*k[i]));//* pow(W[(s+1)/2],2);
//b[i] += (F[s+1]*(m_*F[s+1]+b1)*sinc_ - F[s]*(m_*F[s]+b1)*sinc_);// * pow(W[(s+1)/2],2);
b[i] += (F[s+1]*b1*sinc_ - F[s]*b1*sinc_);
}
}
b.insert(b.begin(),b0);
// a=(W(1)^2)*4*b;
std::vector<double> a(b.size());
for(size_t i = 0; i < a.size(); i++)
{
//a[i] = 4.0*b[i];
a[i] = 2.0*b[i];
}
//a[0] /= 2.0;
// h=[a(L+1:-1:2)/2; a(1); a(2:L+1)/2].';
std::vector<double> h;// size N
h.insert(h.end(), a.rbegin(), a.rend());
h.insert(h.end(), a.begin()+1, a.end());
// return h;
// b = hh.*Wind(:)';
// a = 1;
// generate the Hamming window coefficients
std::vector<double> Wind = genHammingWindow(N);
// reuse b
b.clear(); b.resize(N);
for(size_t i = 0; i < b.size(); i++)
{
b[i] = h[i] * Wind[i];
}
// scale filter
// b = b / sum(b);
double sumb = std::accumulate(b.begin(),b.end(),0.0);
for(size_t i = 0; i < b.size(); i++)
{
b[i] /= sumb;
}
return b;
}
std::vector<double> filtfilt::genHammingWindow(const size_t L)
{
std::vector<double> w;
if(L % 2 > 0)
{
// Odd length window
size_t half = (L+1)/2;
w = calcWindow(half, L);
}
else
{
// Even length window
size_t half = L/2;
w = calcWindow(half, L);
}
return w;
}
std::vector<double> filtfilt::calcWindow(size_t m, size_t n)
{
// x = (0:m-1)'/(n-1);
double x = 0.0;
std::vector<double> w;
w.resize(m);
// compute coefficients of the Hamming windows
for(size_t i = 0; i < m; i++)
{
x = i/(n-1.0); // between 0.00 and 0.50
w[i] = 0.54 - 0.46*cos(2*pi*x);
}
// w = [w; w(end-1:-1:1)]; // make symmetric
w.insert(w.end(), w.rbegin()+1, w.rend());
return w;
}
| 18,811 | C++ | 32.592857 | 126 | 0.542714 |
adegirmenci/HBL-ICEbot/HeartRateWidget/heartratewidget.cpp | #include "heartratewidget.h"
#include "ui_heartratewidget.h"
HeartRateWidget::HeartRateWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::HeartRateWidget)
{
ui->setupUi(this);
m_time.resize(VEC_SIZE, 0.0);
m_voltage.resize(VEC_SIZE, 0.0);
m_HR = 0.0, m_stdHR = 0.0, m_phaseHR = 0.0;
minPeakDist = 60./120./2.;
minPeakHei = 0.2;
m_counter = 0;
// Initialize MATLAB DLL
ECGgating_initialize();
// qDebug() << "HR Widget Thread ID: " << reinterpret_cast<int>(QThread::currentThreadId()) << ".";
}
HeartRateWidget::~HeartRateWidget()
{
// Terminate MATLAB DLL
ECGgating_terminate();
delete ui;
}
void HeartRateWidget::receiveECG(qint64 timeStamp, std::vector<double> data)
{
// remove first element
m_time.erase(m_time.begin());
m_voltage.erase(m_voltage.begin());
// add new reading
m_time.push_back((double)timeStamp/1000.);
m_voltage.push_back(data[0]);
// peak detection
ECGgating(&m_voltage[0], &m_time[0], minPeakDist, minPeakHei,
ECGpeakVals_data, ECGpeakVals_size,
ECGpeakTimes_data, ECGpeakTimes_size, &m_HR, &m_stdHR, &m_phaseHR);
m_counter = (m_counter + 1) % 60;
if(m_counter == 0)
{
ui->HRlineEdit->setText(QString::number(m_HR,'f',1));
ui->phaseLineEdit->setText(QString::number(m_phaseHR,'f',3));
}
emit reportPhase(timeStamp, m_phaseHR);
}
| 1,425 | C++ | 23.586206 | 103 | 0.625263 |
adegirmenci/HBL-ICEbot/HeartRateWidget/heartratewidget.h | #ifndef HEARTRATEWIDGET_H
#define HEARTRATEWIDGET_H
#include <QWidget>
#include <QTime>
#include <QString>
#include <QDebug>
#include <QThread>
#include <cmath>
#include <math.h>
#include <iostream>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include "rt_nonfinite.h"
#include "rtwtypes.h"
#include "ECGgating_types.h"
#include "ECGgating.h"
#include "ECGgating_terminate.h"
#include "ECGgating_initialize.h"
#define VEC_SIZE 3000 // 3000 sample points
namespace Ui {
class HeartRateWidget;
}
class HeartRateWidget : public QWidget
{
Q_OBJECT
public:
explicit HeartRateWidget(QWidget *parent = 0);
~HeartRateWidget();
signals:
void reportPhase(qint64 timeStamp, double phase);
public slots:
void receiveECG(qint64 timeStamp,
std::vector<double> data);
private:
Ui::HeartRateWidget *ui;
std::vector<double> m_time;
std::vector<double> m_voltage;
double m_HR, m_stdHR, m_phaseHR;
double ECGpeakVals_data[6000];
int ECGpeakVals_size[1];
double ECGpeakTimes_data[6000];
int ECGpeakTimes_size[2];
unsigned __int8 m_counter;
double minPeakDist;
double minPeakHei;
};
#endif // HEARTRATEWIDGET_H
| 1,205 | C | 17.84375 | 53 | 0.700415 |
adegirmenci/HBL-ICEbot/OmniWidget/omnithread.cpp | #include "omnithread.h"
omniThread::omniThread(QObject *parent) :
QThread(parent)
{
// moveToThread(this);
m_hUpdateHandle = 0;
HDErrorInfo error;
/* Initialize the device, must be done before attempting to call any hd
functions. */
m_hHD = hdInitDevice(HD_DEFAULT_DEVICE);
if (HD_DEVICE_ERROR(error = hdGetError()))
{
hduPrintError(stderr, &error, "Failed to initialize the device");
//throw exception
}
m_sphereRadius = 40.0;
/* Schedule the main scheduler callback that updates the device state. */
m_hUpdateHandle = hdScheduleAsynchronous(updateDeviceCallback, this, HD_MAX_SCHEDULER_PRIORITY);
open();
init();
// updateTimer = new QTimer();
// updateTimer->setInterval(1);
// connect(updateTimer, SIGNAL(timeout()), this, SLOT(run()));
// updateTimer->start();
}
void omniThread::getDevicePosRot(hduVector3Dd &pos, hduVector3Dd &rot)
{
pos = m_currentData.m_devicePosition;
//rot = m_currentData.m_deviceRotation;
rot = m_currentData.m_stylusHeading;
}
void omniThread::open()
{
HDErrorInfo error;
/* Start the servo loop scheduler. */
hdEnable(HD_FORCE_OUTPUT);
hdStartScheduler();
if (HD_DEVICE_ERROR(error = hdGetError()))
{
hduPrintError(stderr, &error, "Failed to start the scheduler");
//throw exception
}
if(fopen_s(&pFile, "omniPositionRec.txt","w") == 0)
fprintf(stdout, "Opened log file.\n");
}
void omniThread::init()
{
/* Perform a synchronous call to copy the most current device state. */
hdScheduleSynchronous(copyDeviceDataCallback, this, HD_MIN_SCHEDULER_PRIORITY);
memcpy(&m_prevData, &m_currentData, sizeof(DeviceData));
}
void omniThread::close()
{
/* For cleanup, unschedule callbacks and stop the servo loop. */
hdStopScheduler();
hdUnschedule(m_hUpdateHandle);
hdDisableDevice(m_hHD);
fclose(pFile);
}
void omniThread::setSphereRad(double radius)
{
if((1.0 < radius) && (radius < 80.0))
m_sphereRadius = radius;
}
void omniThread::run()
{
// QElapsedTimer elTimer;
// elTimer.start();
// qint64 ctr = 0;
// qint64 elapsedT = 0;
// qint64 avgTime = 0;
while(isRunning())
{
/* Perform a synchronous call to copy the most current device state.
This synchronous scheduler call ensures that the device state
is obtained in a thread-safe manner. */
hdScheduleSynchronous(copyDeviceDataCallback,
this,
HD_MIN_SCHEDULER_PRIORITY);
// // Filter noise
// hduVector3Dd diffPos, diffRot;
// for(int i = 0; i < 3; i++)
// {
// diffPos[i] = fabs(m_currentData.m_devicePosition[i] - m_prevData.m_devicePosition[i]);
// diffRot[i] = fabs(m_currentData.m_deviceRotation[i] - m_prevData.m_deviceRotation[i]);
// if(diffPos[i] < 0.001)
// m_currentData.m_devicePosition[i] = m_prevData.m_devicePosition[i];
// if(diffRot[i] < 0.001)
// m_currentData.m_deviceRotation[i] = m_prevData.m_deviceRotation[i];
// }
/* If the user depresses the gimbal button, display the current
location information. */
if (m_currentData.m_buttonState && !m_prevData.m_buttonState)
{
/*fprintf(stdout, "Current position: (%g, %g, %g)\n",
m_currentData.m_devicePosition[0],
m_currentData.m_devicePosition[1],
m_currentData.m_devicePosition[2]);*/
//fprintf(stdout, "Roll, pitch, yaw: (%g, %g, %g)\n", roll_, pitch_, yaw_);
//fprintf(stdout, "Send A3200 to: (%g, %g, %g)\n", axis01, axis02, axis00);
//close gripper
//*************** FIX THIS - need to use signals?
//ui->outputText->append(QString("Current position: (%1, %2, %3)").arg(ui->xLCD->value()).arg(ui->yLCD->value()).arg(ui->zLCD->value()));
emit button1pressed(true);
}
else if (m_currentData.m_buttonState && m_prevData.m_buttonState)
{
/* Button is held pressed down. */
// Gripper remains closed
// write other code
}
else if (!m_currentData.m_buttonState && m_prevData.m_buttonState)
{
/* Button released. */
// Open gripper
emit button1pressed(false);
}
/* Check if an error occurred. */
if (HD_DEVICE_ERROR(m_currentData.m_error))
{
hduPrintError(stderr, &m_currentData.m_error, "Device error detected");
if (hduIsSchedulerError(&m_currentData.m_error))
{
/* Quit, since communication with the device was disrupted. */
fprintf(stderr, "Communication with the device was disrupted..\n");
}
}
/* Store off the current data for the next loop. */
memcpy(&m_prevData, &m_currentData, sizeof(DeviceData));
// ctr++;
// elapsedT += elTimer.restart();
// avgTime = elapsedT;
// if( (ctr%1000) == 0)
// printf("Elapsed Omni time: %d msec in %d counts.\n", int(avgTime), int(ctr));
fprintf(pFile,"%lf %lf %lf %lf %lf %lf\n",
m_currentData.m_devicePosition[0],m_currentData.m_devicePosition[1],m_currentData.m_devicePosition[2],
m_currentData.m_stylusHeading[0],m_currentData.m_stylusHeading[1],m_currentData.m_stylusHeading[2]);
}
exec();
}
/*******************************************************************************
Checks the state of the gimbal button and gets the position of the device.
*******************************************************************************/
HDCallbackCode HDCALLBACK updateDeviceCallback(void *ptr) //pUserData
{
omniThread* omniPtr = (omniThread *) ptr;
int nButtons = 0;
hdBeginFrame(hdGetCurrentDevice());
/* Retrieve the current button(s). */
hdGetIntegerv(HD_CURRENT_BUTTONS, &nButtons);
/* In order to get the specific button 1 state, we use a bitmask to
test for the HD_DEVICE_BUTTON_1 bit. */
omniPtr->gServoDeviceData.m_buttonState =
(nButtons & HD_DEVICE_BUTTON_2) ? HD_TRUE : HD_FALSE;
/* Get the current location of the device (HD_GET_CURRENT_POSITION)
We declare a vector of three doubles since hdGetDoublev returns
the information in a vector of size 3. */
hdGetDoublev(HD_CURRENT_POSITION, omniPtr->gServoDeviceData.m_devicePosition);
/* Get the transformation matrix (HD_CURRENT_TRANSFORM)
We declare a vector of three doubles since hdGetDoublev returns
the information in a vector of size 3. */
hdGetDoublev(HD_CURRENT_GIMBAL_ANGLES, omniPtr->gServoDeviceData.m_deviceRotation);
hduVector3Dd temp = omniPtr->gServoDeviceData.m_deviceRotation;
omniPtr->gServoDeviceData.m_deviceRotation[0] = temp[2];
omniPtr->gServoDeviceData.m_deviceRotation[2] = temp[0];
hdGetDoublev(HD_CURRENT_TRANSFORM, omniPtr->gServoDeviceData.m_transform);
// // calculate Roll [=0], Pitch [=1], Yaw [=2]
// omniPtr->gServoDeviceData.m_deviceRotation[0] =
// atan2(omniPtr->gServoDeviceData.m_transform[4], omniPtr->gServoDeviceData.m_transform[0]);
// omniPtr->gServoDeviceData.m_deviceRotation[2] =
// atan2(-1.0*omniPtr->gServoDeviceData.m_transform[8],
// sqrt(pow(omniPtr->gServoDeviceData.m_transform[9],2) + pow(omniPtr->gServoDeviceData.m_transform[10],2)) );
// omniPtr->gServoDeviceData.m_deviceRotation[1] =
// atan2(omniPtr->gServoDeviceData.m_transform[9], omniPtr->gServoDeviceData.m_transform[10]);
// calculate Roll [=0], Pitch [=1], Yaw [=2]
// omni stores transformation matix in a column fashion (0,1,2,3 first column)
omniPtr->gServoDeviceData.m_stylusHeading[0] = -omniPtr->gServoDeviceData.m_transform[8];//2
omniPtr->gServoDeviceData.m_stylusHeading[1] = -omniPtr->gServoDeviceData.m_transform[9];//6
omniPtr->gServoDeviceData.m_stylusHeading[2] = -omniPtr->gServoDeviceData.m_transform[10];
/* Also check the error state of HDAPI. */
omniPtr->gServoDeviceData.m_error = hdGetError();
const hduVector3Dd spherePosition(0,0,0);
const double sphereStiffness = .25;
// Find the distance between the device and the center of the
// sphere.
double distance = (omniPtr->gServoDeviceData.m_devicePosition - spherePosition).magnitude();
// If the user is outside the sphere -- i.e. if the distance from the user to
// the center of the sphere is greater than the sphere radius -- then the user
// is penetrating the sphere and a force should be commanded to repel him
// towards the center.
if (distance > omniPtr->getSphereRad())
{
// Calculate the penetration distance.
double penetrationDistance = distance - omniPtr->getSphereRad();
// Create a unit vector in the direction of the force, this will always
// be inward to the center of the sphere through the user's
// position.
hduVector3Dd forceDirection = (spherePosition - omniPtr->gServoDeviceData.m_devicePosition)/distance;
// Use F=kx to create a force vector that is towards the center of
// the sphere and proportional to the penetration distance, and scaled
// by the object stiffness.
// Hooke's law explicitly:
double k = sphereStiffness;
hduVector3Dd x = penetrationDistance*forceDirection;
hduVector3Dd f = k*x;
hdSetDoublev(HD_CURRENT_FORCE, f);
}
/* Copy the position into our device_data tructure. */
hdEndFrame(hdGetCurrentDevice());
return HD_CALLBACK_CONTINUE;
}
/*******************************************************************************
Checks the state of the gimbal button and gets the position of the device.
*******************************************************************************/
HDCallbackCode HDCALLBACK copyDeviceDataCallback(void *ptr) //pUserData
{
omniThread* omniPtr = (omniThread *) ptr;
DeviceData *pDeviceData = &(omniPtr->m_currentData); //(DeviceData *) pUserData;
memcpy(pDeviceData, &(omniPtr->gServoDeviceData), sizeof(DeviceData));
return HD_CALLBACK_DONE;
}
| 10,315 | C++ | 36.787546 | 149 | 0.618905 |
adegirmenci/HBL-ICEbot/OmniWidget/omni.h | #ifndef OMNI_H
#define OMNI_H
#include <QWidget>
#include <QTimer>
//#include <QThread>
#include <stdio.h>
#include <assert.h>
#include <windows.h>
#include <conio.h>
//#include <HDU/hduVector.h>
#include "omnithread.h"
namespace Ui {
class Omni;
}
class Omni : public QWidget
{
Q_OBJECT
public:
explicit Omni(QWidget *parent = 0);
omniThread *m_omnithread;
~Omni();
public slots:
void updateLCD();
private slots:
void on_sphSizeSpinBox_valueChanged(double arg1);
private:
Ui::Omni *ui;
// QTimer *omniTimer;
QTimer *updateTimer;
//QThread momniThread;
};
#endif // OMNI_H
| 631 | C | 13.363636 | 53 | 0.657686 |
adegirmenci/HBL-ICEbot/OmniWidget/omni.cpp | #include "omni.h"
#include "ui_omni.h"
/** Use to init the clock */
//#define TIMER_INIT LARGE_INTEGER frequency;LARGE_INTEGER t1,t2;double elapsedTime;QueryPerformanceFrequency(&frequency);
/** Use to start the performance timer */
//#define TIMER_START QueryPerformanceCounter(&t1);
/** Use to stop the performance timer and output the result to the standard stream. Less verbose than \c TIMER_STOP_VERBOSE */
//#define TIMER_STOP QueryPerformanceCounter(&t2);elapsedTime=(float)(t2.QuadPart-t1.QuadPart)/frequency.QuadPart;printf("%g sec\n",elapsedTime);
Omni::Omni(QWidget *parent) :
QWidget(parent),
ui(new Ui::Omni)
{
ui->setupUi(this);
// omniTimer = new QTimer();
// omniTimer->setInterval(1);
// connect(omniTimer, SIGNAL(timeout()), this, SLOT(mainLoop()));
// //connect(omniTimer, SIGNAL(timeout()), ui->omniWidget, SLOT(mainLoop()));
// omniTimer->start();
m_omnithread = new omniThread();
//m_omnithread->moveToThread(&momniThread);
m_omnithread->start();
updateTimer = new QTimer();
updateTimer->setInterval(150);
connect(updateTimer, SIGNAL(timeout()), this, SLOT(updateLCD()));
updateTimer->start();
}
Omni::~Omni()
{
//omniTimer->stop();
updateTimer->stop();
if(m_omnithread->isRunning())
{
m_omnithread->close();
m_omnithread->exit();
}
delete ui;
}
void Omni::updateLCD()
{
hduVector3Dd pos;
hduVector3Dd rot;
m_omnithread->getDevicePosRot(pos, rot);
ui->xLCD->display(pos[0]);
ui->yLCD->display(pos[1]);
ui->zLCD->display(pos[2]);
ui->rollLCD->display(rot[0]);
ui->pitchLCD->display(rot[1]);
ui->yawLCD->display(rot[2]);
}
void Omni::on_sphSizeSpinBox_valueChanged(double arg1)
{
m_omnithread->setSphereRad(arg1);
}
| 1,782 | C++ | 26.430769 | 145 | 0.662177 |
adegirmenci/HBL-ICEbot/OmniWidget/omnithread.h | #ifndef OMNITHREAD_H
#define OMNITHREAD_H
#include <QThread>
#include <QTimer>
#include <QElapsedTimer>
#include <stdio.h>
#include <assert.h>
#include <windows.h>
#include <conio.h>
#include <HD/hd.h>
#include <HD/hdDefines.h>
#include <HD/hdScheduler.h>
#include <HDU/hduError.h>
#include <HDU/hduVector.h>
/* Holds data retrieved from HDAPI. */
typedef struct
{
HDboolean m_buttonState; /* Has the device button has been pressed. */
hduVector3Dd m_devicePosition; /* Current device coordinates. */
HDdouble m_transform[16]; // Transformation matrix
HDErrorInfo m_error;
hduVector3Dd m_deviceRotation;
hduVector3Dd m_stylusHeading;
} DeviceData;
class omniThread : public QThread
{
Q_OBJECT
public:
explicit omniThread(QObject *parent = 0);
DeviceData m_currentData;
DeviceData m_prevData;
DeviceData gServoDeviceData;
void open();
void init();
void close();
void getDevicePosRot(hduVector3Dd &pos, hduVector3Dd &rot);
double getSphereRad() {return m_sphereRadius;}
void setSphereRad(double radius);
signals:
void button1pressed(bool pressed);
public slots:
void run();
private:
HDSchedulerHandle m_hUpdateHandle;
HHD m_hHD;
double m_sphereRadius;
FILE *pFile;
//QTimer *updateTimer;
};
HDCallbackCode HDCALLBACK updateDeviceCallback(void *ptr);
HDCallbackCode HDCALLBACK copyDeviceDataCallback(void *ptr);
#endif // OMNITHREAD_H
| 1,455 | C | 19.8 | 80 | 0.710653 |
adegirmenci/HBL-ICEbot/LabJackWidget/labjackwidget.cpp | #include "labjackwidget.h"
#include "ui_labjackwidget.h"
LabJackWidget::LabJackWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::LabJackWidget)
{
ui->setupUi(this);
m_worker = new LabJackThread;
m_worker->moveToThread(&m_thread);
connect(&m_thread, &QThread::finished, m_worker, &QObject::deleteLater);
m_thread.start();
// connect widget signals to worker slots
connect(this, SIGNAL(connectLabJack()), m_worker, SLOT(connectLabJack()));
connect(this, SIGNAL(initializeLabJack(uint, QVector<ushort>, QVector<QString>)),
m_worker, SLOT(initializeLabJack(uint, QVector<ushort>, QVector<QString>)));
connect(this, SIGNAL(disconnectLabJack()), m_worker, SLOT(disconnectLabJack()));
connect(this, SIGNAL(startAcquisition()), m_worker, SLOT(startAcquisition()));
connect(this, SIGNAL(stopAcquisition()), m_worker, SLOT(stopAcquisition()));
// connect worker signals to widget slots
connect(m_worker, SIGNAL(statusChanged(int)), this, SLOT(workerStatusChanged(int)));
// QCustomPlot
// include this section to fully disable antialiasing for higher performance:
ui->plotWidget->setNotAntialiasedElements(QCP::aeAll);
QFont font;
font.setStyleStrategy(QFont::NoAntialias);
ui->plotWidget->xAxis->setTickLabelFont(font);
ui->plotWidget->yAxis->setTickLabelFont(font);
ui->plotWidget->legend->setFont(font);
ui->plotWidget->addGraph(); // blue line
ui->plotWidget->graph(0)->setPen(QPen(Qt::blue));
//ui->plotWidget->graph(0)->setBrush(QBrush(QColor(240, 255, 200)));
ui->plotWidget->graph(0)->setAntialiasedFill(false);
ui->plotWidget->xAxis->setTickLabelType(QCPAxis::ltDateTime);
ui->plotWidget->xAxis->setDateTimeFormat("hh:mm:ss");
ui->plotWidget->xAxis->setAutoTickStep(false);
ui->plotWidget->xAxis->setTickStep(2);
ui->plotWidget->axisRect()->setupFullAxesBox();
// make left and bottom axes transfer their ranges to right and top axes:
connect(ui->plotWidget->xAxis, SIGNAL(rangeChanged(QCPRange)), ui->plotWidget->xAxis2, SLOT(setRange(QCPRange)));
connect(ui->plotWidget->yAxis, SIGNAL(rangeChanged(QCPRange)), ui->plotWidget->yAxis2, SLOT(setRange(QCPRange)));
// setup a timer that repeatedly calls MainWindow::realtimeDataSlot:
connect(m_worker, SIGNAL(logData(qint64,std::vector<double>)), this, SLOT(addDataToPlot(qint64,std::vector<double>)));
// Heart Rate Widget
connect(m_worker, SIGNAL(logData(qint64,std::vector<double>)), ui->HRwidget, SLOT(receiveECG(qint64,std::vector<double>)));
// qDebug() << "LabJack Widget Thread ID: " << reinterpret_cast<int>(QThread::currentThreadId()) << ".";
m_hrWidget = ui->HRwidget;
}
LabJackWidget::~LabJackWidget()
{
m_thread.quit();
m_thread.wait();
qDebug() << "LabJack thread quit.";
delete ui;
}
void LabJackWidget::addDataToPlot(qint64 timeStamp, std::vector<double> data)
{
//TODO : automatically add more lines depending on the size of 'data'
double key = timeStamp/1000.0;
static double lastPointKey = 0;
if( (key - lastPointKey) > 0.010) // at most add point every 10 ms
{
// add data to lines:
ui->plotWidget->graph(0)->addData(key, data[0]);
// remove data of lines that's outside visible range:
ui->plotWidget->graph(0)->removeDataBefore(key-8);
// rescale value (vertical) axis to fit the current data:
ui->plotWidget->graph(0)->rescaleValueAxis();
lastPointKey = key;
// make key axis range scroll with the data (at a constant range size of 8):
ui->plotWidget->xAxis->setRange(key+0.25, 8, Qt::AlignRight);
ui->plotWidget->replot();
}
}
void LabJackWidget::workerStatusChanged(int status)
{
switch(status)
{
case LABJACK_CONNECT_BEGIN:
ui->connectButton->setEnabled(false);
ui->disconnectButton->setEnabled(true);
ui->samplesPsecSpinBox->setEnabled(false);
ui->statusLineEdit->setText("Connecting.");
ui->initializeLJbutton->setEnabled(true);
ui->startRecordButton->setEnabled(false);
ui->stopRecordButton->setEnabled(false);
break;
case LABJACK_CONNECT_FAILED:
ui->connectButton->setEnabled(true);
ui->disconnectButton->setEnabled(false);
ui->samplesPsecSpinBox->setEnabled(true);
ui->statusLineEdit->setText("Connection failed.");
ui->initializeLJbutton->setEnabled(false);
ui->startRecordButton->setEnabled(false);
ui->stopRecordButton->setEnabled(false);
break;
case LABJACK_CONNECTED:
ui->connectButton->setEnabled(false);
ui->disconnectButton->setEnabled(true);
ui->samplesPsecSpinBox->setEnabled(false);
ui->statusLineEdit->setText("Connected.");
ui->initializeLJbutton->setEnabled(true);
ui->startRecordButton->setEnabled(false);
ui->stopRecordButton->setEnabled(false);
break;
case LABJACK_INITIALIZE_BEGIN:
ui->connectButton->setEnabled(false);
ui->disconnectButton->setEnabled(true);
ui->samplesPsecSpinBox->setEnabled(false);
ui->statusLineEdit->setText("Initializing.");
ui->initializeLJbutton->setEnabled(false);
ui->startRecordButton->setEnabled(true);
ui->stopRecordButton->setEnabled(false);
break;
case LABJACK_INITIALIZE_FAILED:
ui->connectButton->setEnabled(false);
ui->disconnectButton->setEnabled(true);
ui->samplesPsecSpinBox->setEnabled(false);
ui->statusLineEdit->setText("Initialization failed.");
ui->initializeLJbutton->setEnabled(true);
ui->startRecordButton->setEnabled(false);
ui->stopRecordButton->setEnabled(false);
break;
case LABJACK_INITIALIZED:
ui->connectButton->setEnabled(false);
ui->disconnectButton->setEnabled(true);
ui->samplesPsecSpinBox->setEnabled(false);
ui->statusLineEdit->setText("Initialized.");
ui->initializeLJbutton->setEnabled(false);
ui->startRecordButton->setEnabled(true);
ui->stopRecordButton->setEnabled(false);
break;
case LABJACK_LOOP_STARTED:
ui->connectButton->setEnabled(false);
ui->disconnectButton->setEnabled(true);
ui->samplesPsecSpinBox->setEnabled(false);
ui->statusLineEdit->setText("Acquiring.");
ui->initializeLJbutton->setEnabled(false);
ui->startRecordButton->setEnabled(false);
ui->stopRecordButton->setEnabled(true);
break;
case LABJACK_LOOP_STOPPED:
ui->connectButton->setEnabled(false);
ui->disconnectButton->setEnabled(true);
ui->samplesPsecSpinBox->setEnabled(false);
ui->statusLineEdit->setText("Acquisition stopped.");
ui->initializeLJbutton->setEnabled(false);
ui->startRecordButton->setEnabled(true);
ui->stopRecordButton->setEnabled(false);
break;
case LABJACK_EPOCH_SET:
ui->statusLineEdit->setText("Epoch set.");
break;
case LABJACK_EPOCH_SET_FAILED:
ui->statusLineEdit->setText("Epoch set failed.");
break;
case LABJACK_DISCONNECTED:
ui->connectButton->setEnabled(true);
ui->disconnectButton->setEnabled(false);
ui->samplesPsecSpinBox->setEnabled(true);
ui->statusLineEdit->setText("Disconnected.");
ui->initializeLJbutton->setEnabled(false);
ui->startRecordButton->setEnabled(false);
ui->stopRecordButton->setEnabled(false);
break;
case LABJACK_DISCONNECT_FAILED:
ui->connectButton->setEnabled(false);
ui->disconnectButton->setEnabled(true);
ui->samplesPsecSpinBox->setEnabled(false);
ui->statusLineEdit->setText("Disconnection failed.");
ui->initializeLJbutton->setEnabled(false);
ui->startRecordButton->setEnabled(true);
ui->stopRecordButton->setEnabled(false);
break;
default:
ui->statusLineEdit->setText("Unknown state.");
break;
}
}
void LabJackWidget::on_connectButton_clicked()
{
emit connectLabJack();
}
void LabJackWidget::on_disconnectButton_clicked()
{
emit disconnectLabJack();
}
void LabJackWidget::on_initializeLJbutton_clicked()
{
int samplesPsec = ui->samplesPsecSpinBox->value();
QVector<ushort> channelIdx;
QVector<QString> channelNames;
// TODO: figure out which channels are desired by the user
channelIdx.push_back(0);
channelNames.push_back("ECG");
emit initializeLabJack(samplesPsec,channelIdx,channelNames);
}
void LabJackWidget::on_startRecordButton_clicked()
{
emit startAcquisition();
}
void LabJackWidget::on_stopRecordButton_clicked()
{
emit stopAcquisition();
}
| 8,745 | C++ | 37.026087 | 127 | 0.67673 |
adegirmenci/HBL-ICEbot/LabJackWidget/labjackwidget.h | #ifndef LABJACKWIDGET_H
#define LABJACKWIDGET_H
#include <QWidget>
#include <QThread>
#include "labjackthread.h"
#include "HeartRateWidget/heartratewidget.h"
namespace Ui {
class LabJackWidget;
}
class LabJackWidget : public QWidget
{
Q_OBJECT
public:
explicit LabJackWidget(QWidget *parent = 0);
~LabJackWidget();
LabJackThread *m_worker;
HeartRateWidget *m_hrWidget;
signals:
void connectLabJack(); // open connection
void initializeLabJack(const uint samplesPerSec, const QVector<ushort> channelIdx, const QVector<QString> channelNames); // initialize settings
void startAcquisition(); // start timer
void stopAcquisition(); // stop timer
void disconnectLabJack(); // disconnect
private slots:
void workerStatusChanged(int status);
void addDataToPlot(qint64 timeStamp, std::vector<double> data);
void on_connectButton_clicked();
void on_disconnectButton_clicked();
void on_initializeLJbutton_clicked();
void on_startRecordButton_clicked();
void on_stopRecordButton_clicked();
private:
Ui::LabJackWidget *ui;
QThread m_thread; // LabJack Thread will live in here
};
#endif // LABJACKWIDGET_H
| 1,188 | C | 20.618181 | 147 | 0.727273 |
adegirmenci/HBL-ICEbot/LabJackWidget/labjackthread.cpp | #include "labjackthread.h"
LabJackThread::LabJackThread(QObject *parent) : QObject(parent)
{
qRegisterMetaType< QVector<ushort> >("QVector<ushort>");
qRegisterMetaType< QVector<QString> >("QVector<QString>");
qRegisterMetaType< std::vector<double> >("std::vector<double>");
m_isEpochSet = false;
m_isReady = false;
m_keepAcquiring = false;
m_abort = false;
m_mutex = new QMutex(QMutex::Recursive);
m_lngErrorcode = 0;
m_lngHandle = 0;
m_i = 0;
m_k = 0;
m_lngIOType = 0;
m_lngChannel = 0;
m_dblValue = 0;
m_dblCommBacklog = 0;
m_dblUDBacklog = 0;
m_numChannels = 1;
m_channelNames.push_back(tr("ECG"));
m_scanRate = 1000; //scan rate = sample rate / #channels
m_delayms = 1000; // 1 seconds per 1000 samples
m_numScans = 2*m_scanRate*m_delayms/1000; //Max number of scans per read. 2x the expected # of scans (2*scanRate*delayms/1000).
//m_adblData = (double *)calloc( m_numScans, sizeof(double)); //Max buffer size (#channels*numScansRequested)
//m_padblData = (long)&m_adblData[0];
}
LabJackThread::~LabJackThread()
{
disconnectLabJack();
m_mutex->lock();
m_abort = true;
qDebug() << "Ending LabJackThread - ID: " << reinterpret_cast<int>(QThread::currentThreadId()) << ".";
m_mutex->unlock();
delete m_mutex;
emit finished();
}
void LabJackThread::connectLabJack()
{
QMutexLocker locker(m_mutex); // lock mutex
bool success = true;
emit statusChanged(LABJACK_CONNECT_BEGIN);
//Open the first found LabJack U6.
m_lngErrorcode = OpenLabJack(LJ_dtU6, LJ_ctUSB, "1", 1, &m_lngHandle);
success = ErrorHandler(m_lngErrorcode, __LINE__, 0);
//Read and display the hardware version of this U6.
m_lngErrorcode = eGet(m_lngHandle, LJ_ioGET_CONFIG, LJ_chHARDWARE_VERSION, &m_dblValue, 0);
success = success && ErrorHandler(m_lngErrorcode, __LINE__, 0);
emit logEventWithMessage(SRC_LABJACK, LOG_INFO, QTime::currentTime(), LABJACK_CONNECTED,
QString("U6 Hardware Version = %1\n")
.arg(QString::number(m_dblValue,'f',3)) );
qDebug() << "U6 Hardware Version = " << m_dblValue;
//Read and display the firmware version of this U6.
m_lngErrorcode = eGet(m_lngHandle, LJ_ioGET_CONFIG, LJ_chFIRMWARE_VERSION, &m_dblValue, 0);
success = success && ErrorHandler(m_lngErrorcode, __LINE__, 0);
emit logEventWithMessage(SRC_LABJACK, LOG_INFO, QTime::currentTime(), LABJACK_CONNECTED,
QString("U6 Firmware Version = %1\n")
.arg(QString::number(m_dblValue,'f',3)) );
qDebug() << "U6 Firmware Version = " << m_dblValue;
if(success)
emit statusChanged(LABJACK_CONNECTED);
else
emit statusChanged(LABJACK_CONNECT_FAILED);
//ResetLabJack(m_lngHandle);
}
void LabJackThread::initializeLabJack(const uint samplesPerSec, const QVector<ushort> channelIdx, const QVector<QString> channelNames)
{
QMutexLocker locker(m_mutex);
emit statusChanged(LABJACK_INITIALIZE_BEGIN);
m_scanRate = samplesPerSec;
qDebug() << "LabJack samples per sec: " << m_scanRate;
m_numChannels = channelIdx.size();
if(m_numChannels < 1)
qDebug() << "LabJack should have at least one channel enabled!";
m_channelNames = channelNames;
m_numScans = 2*m_scanRate*m_delayms/1000; //Max number of scans per read. 2x the expected # of scans (2*scanRate*delayms/1000).
m_adblData = (double *)calloc( m_numChannels*m_numScans, sizeof(double)); //Max buffer size (#channels*numScansRequested)
m_padblData = (long)&m_adblData[0];
bool success = true;
//Configure the stream:
//Configure resolution of the analog inputs (pass a non-zero value for quick sampling).
//See section 2.6 / 3.1 for more information.
m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_CONFIG, LJ_chAIN_RESOLUTION, 0, 0, 0);
ErrorHandler(m_lngErrorcode, __LINE__, 0);
// Configure the analog input range on channel 0 for bipolar + -10 volts.
m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_AIN_RANGE, 0, LJ_rgBIP10V, 0, 0);
ErrorHandler(m_lngErrorcode, __LINE__, 0);
// Configure the analog input resolution on channel 0 to index 3, 17bit resolution, 0.08 ms/sample
m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_CONFIG, LJ_chAIN_RESOLUTION, 3, 0, 0);
ErrorHandler(m_lngErrorcode, __LINE__, 0);
// //Set the scan rate.
// m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_CONFIG, LJ_chSTREAM_SCAN_FREQUENCY, m_scanRate, 0, 0);
// ErrorHandler(m_lngErrorcode, __LINE__, 0);
// //Give the driver a 5 second buffer (scanRate * 1 channels * 5 seconds).
// m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_CONFIG, LJ_chSTREAM_BUFFER_SIZE, m_scanRate * 1 * 5, 0, 0);
// ErrorHandler(m_lngErrorcode, __LINE__, 0);
// //Configure reads to retrieve whatever data is available without waiting (wait mode LJ_swNONE).
// m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_CONFIG, LJ_chSTREAM_WAIT_MODE, LJ_swNONE, 0, 0);
// ErrorHandler(m_lngErrorcode, __LINE__, 0);
// //Define the scan list as AIN0.
// m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioCLEAR_STREAM_CHANNELS, 0, 0, 0, 0);
// ErrorHandler(m_lngErrorcode, __LINE__, 0);
// m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioADD_STREAM_CHANNEL, 0, 0, 0, 0); // first method for single ended reading - AIN0
// ErrorHandler(m_lngErrorcode, __LINE__, 0);
//Request AIN0.
m_lngErrorcode = AddRequest (m_lngHandle, LJ_ioGET_AIN, 2, 0, 0, 0);
ErrorHandler(m_lngErrorcode, __LINE__, 0);
//Execute the list of requests.
m_lngErrorcode = GoOne(m_lngHandle);
success = ErrorHandler(m_lngErrorcode, __LINE__, 0);
//Get all the results just to check for errors.
m_lngErrorcode = GetFirstResult(m_lngHandle, &m_lngIOType, &m_lngChannel, &m_dblValue, 0, 0);
success = success && ErrorHandler(m_lngErrorcode, __LINE__, 0);
m_lngGetNextIteration = 0; //Used by the error handling function.
while (m_lngErrorcode < LJE_MIN_GROUP_ERROR)
{
m_lngErrorcode = GetNextResult(m_lngHandle, &m_lngIOType, &m_lngChannel, &m_dblValue, 0, 0);
if (m_lngErrorcode != LJE_NO_MORE_DATA_AVAILABLE)
{
success = success && ErrorHandler(m_lngErrorcode, __LINE__, m_lngGetNextIteration);
}
m_lngGetNextIteration++;
}
m_isReady = success;
if(success)
emit statusChanged(LABJACK_INITIALIZED);
else
emit statusChanged(LABJACK_INITIALIZE_FAILED);
}
void LabJackThread::startAcquisition()
{
QMutexLocker locker(m_mutex);
if(m_isReady && !m_keepAcquiring) // ready to read data
{
//Start the stream.
// m_lngErrorcode = eGet(m_lngHandle, LJ_ioSTART_STREAM, 0, &m_dblValue, 0);
// ErrorHandler(m_lngErrorcode, __LINE__, 0);
m_keepAcquiring = true;
m_timer = new QTimer(this);
connect(m_timer, SIGNAL(timeout()), this, SLOT(ReadStream()));
//m_timer->start(m_delayms);
m_timer->start(1);
if(m_timer->isActive())
{
qDebug() << "Timer started.";
emit statusChanged(LABJACK_LOOP_STARTED);
emit logEvent(SRC_LABJACK, LOG_INFO, QTime::currentTime(), LABJACK_LOOP_STARTED);
}
else
{
qDebug() << "Timer is not active.";
emit statusChanged(LABJACK_LOOP_STOPPED);
emit logError(SRC_LABJACK, LOG_ERROR, QTime::currentTime(), LJE_TIMER_INVALID_MODE, QString("Timer is not active."));
}
}
else
{
qDebug() << "LabJack is not ready.";
emit statusChanged(LABJACK_INITIALIZE_FAILED);
emit logError(SRC_LABJACK, LOG_ERROR, QTime::currentTime(), LJE_DEVICE_NOT_OPEN, QString("LabJack is not ready."));
}
}
void LabJackThread::stopAcquisition()
{
QMutexLocker locker(m_mutex);
if(m_keepAcquiring)
{
m_keepAcquiring = false;
m_timer->stop();
disconnect(m_timer, SIGNAL(timeout()), 0, 0);
delete m_timer;
emit logEvent(SRC_LABJACK, LOG_INFO, QTime::currentTime(), LABJACK_LOOP_STOPPED);
emit statusChanged(LABJACK_LOOP_STOPPED);
// m_lngErrorcode = eGet(m_lngHandle, LJ_ioSTOP_STREAM, 0, 0, 0);
// ErrorHandler(m_lngErrorcode, __LINE__, 0);
qDebug() << "Timer stopped.";
}
else
{
qDebug() << "Timer already stopped.";
}
}
void LabJackThread::disconnectLabJack()
{
QMutexLocker locker(m_mutex);
stopAcquisition();
if(m_lngHandle != 0)
{// Reset LabJack
//m_lngErrorcode = ResetLabJack(m_lngHandle);
//ErrorHandler(m_lngErrorcode, __LINE__, 0);
}
emit statusChanged(LABJACK_DISCONNECTED);
}
void LabJackThread::setEpoch(const QDateTime &epoch)
{
QMutexLocker locker(m_mutex);
if(!m_keepAcquiring)
{
m_epoch = epoch;
m_isEpochSet = true;
emit logEventWithMessage(SRC_LABJACK, LOG_INFO, QTime::currentTime(), LABJACK_EPOCH_SET,
m_epoch.toString("yyyy/MM/dd - hh:mm:ss.zzz"));
}
else
emit logEvent(SRC_LABJACK, LOG_INFO, QTime::currentTime(), LABJACK_EPOCH_SET_FAILED);
}
void LabJackThread::ReadStream()
{
QMutexLocker locker(m_mutex);
if(m_isReady)
{
// for (m_k = 0; m_k < m_numScans; m_k++)
// {
// m_adblData[m_k] = 9999.0;
// }
//Read the data. We will request twice the number we expect, to
//make sure we get everything that is available.
//Note that the array we pass must be sized to hold enough SAMPLES, and
//the Value we pass specifies the number of SCANS to read.
// m_numScansRequested = m_numScans;
// m_lngErrorcode = eGet(m_lngHandle, LJ_ioGET_STREAM_DATA, LJ_chALL_CHANNELS,
// &m_numScansRequested, m_padblData);
std::vector<double> newData;
newData.resize(m_numChannels, 99.0);
m_lngErrorcode = eGet (m_lngHandle, LJ_ioGET_AIN, 0, &newData[0], 0); // single read
ErrorHandler(m_lngErrorcode, __LINE__, 0);
// emit logData(QTime::currentTime(), m_adblData[0]);
emit logData(QDateTime::currentMSecsSinceEpoch(), newData);
}
}
bool LabJackThread::ErrorHandler(LJ_ERROR lngErrorcode,
long lngLineNumber,
long lngIteration)
{
char err[255];
if (lngErrorcode != LJE_NOERROR)
{
ErrorToString(lngErrorcode, err);
QString msg = QString("Error string = ").append(err);
msg.append(QString(" Source line number = %1. ").arg(lngLineNumber));
msg.append(QString("Iteration = %1").arg(lngIteration));
if (lngErrorcode > LJE_MIN_GROUP_ERROR)
{
qDebug() << "FATAL ERROR!" << msg;
logError(SRC_LABJACK, LOG_FATAL,
QTime::currentTime(),
lngErrorcode,
msg);
}
else
{
qDebug() << msg;
logError(SRC_LABJACK, LOG_ERROR, QTime::currentTime(), lngErrorcode,
msg);
}
return false; // there was an error
}
else
return true; // no errors - success
}
| 11,392 | C++ | 33.524242 | 134 | 0.617363 |
adegirmenci/HBL-ICEbot/LabJackWidget/labjackthread.h | #ifndef LABJACKTHREAD_H
#define LABJACKTHREAD_H
#include <QObject>
#include <QMutex>
#include <QMutexLocker>
#include <QThread>
#include <QString>
#include <QTime>
#include <QDateTime>
#include <QTimer>
#include <QDebug>
#include <QSharedPointer>
#include <vector>
#include <memory>
#include "../icebot_definitions.h"
#include "LabJackLibs/LabJackUD.h"
Q_DECLARE_METATYPE( QVector<ushort> )
Q_DECLARE_METATYPE( QVector<QString> )
Q_DECLARE_METATYPE( std::vector<double> )
class LabJackThread : public QObject
{
Q_OBJECT
public:
explicit LabJackThread(QObject *parent = 0);
~LabJackThread();
signals:
void statusChanged(int status);
//void EM_Ready(bool status); // tells the widget that the EM tracker is ready
void logData(qint64 timeStamp,
std::vector<double> data);
void logEvent(int source, // LOG_SOURCE
int logType, // LOG_TYPES
QTime timeStamp,
int eventID); // LABJACK_EVENT_IDS
void logEventWithMessage(int source, // LOG_SOURCE
int logType, // LOG_TYPES
QTime timeStamp,
int eventID, // LABJACK_EVENT_IDS
QString &message);
void logError(int source, // LOG_SOURCE
int logType, // LOG_TYPES
QTime timeStamp,
int errorCode, // LJ_ERROR
QString message);
//void sendDataToGUI(int sensorID, const QString &output);
void finished(); // emit upon termination
public slots:
void connectLabJack(); // open connection
void initializeLabJack(const uint samplesPerSec, const QVector<ushort> channelIdx, const QVector<QString> channelNames); // initialize settings
void startAcquisition(); // start timer
void stopAcquisition(); // stop timer
void disconnectLabJack(); // disconnect
void setEpoch(const QDateTime &epoch);
private slots:
void ReadStream();
private:
// Instead of using "m_mutex.lock()"
// use "QMutexLocker locker(&m_mutex);"
// this will unlock the mutex when the locker goes out of scope
mutable QMutex *m_mutex;
// Timer for calling acquireData every xxx msecs
QTimer *m_timer;
// Epoch for time stamps
// During initializeLabJack(), check 'isEpochSet' flag
// If Epoch is set externally from MainWindow, the flag will be true
// Otherwise, Epoch will be set internally
QDateTime m_epoch;
bool m_isEpochSet;
// Flag to indicate if LabJack is ready
// True if InitializeLabJack was successful
bool m_isReady;
// Flag to tell that we are still acquiring data
bool m_keepAcquiring;
// Flag to abort actions (e.g. initialize, acquire, etc.)
bool m_abort;
// LabJack specific variables
LJ_ERROR m_lngErrorcode;
LJ_HANDLE m_lngHandle;
long m_lngGetNextIteration;
unsigned long long int m_i, m_k;
long m_lngIOType, m_lngChannel;
double m_dblValue, m_dblCommBacklog, m_dblUDBacklog;
double m_scanRate; //scan rate = sample rate / #channels
int m_delayms;
unsigned int m_numChannels;
QVector<QString> m_channelNames;
double m_numScans; //Max number of scans per read. 2x the expected # of scans (2*scanRate*delayms/1000).
double m_numScansRequested;
double *m_adblData;
long m_padblData;
// LabJack specific variables \\
bool ErrorHandler(LJ_ERROR lngErrorcode, long lngLineNumber, long lngIteration);
};
#endif // LABJACKTHREAD_H
| 3,489 | C | 29.884955 | 147 | 0.665807 |
adegirmenci/HBL-ICEbot/LabJackWidget/LabJackLibs/LabJackUD.h | #ifndef LJHEADER_H
#define LJHEADER_H
// The version of this driver. Call GetDriverVersion() to determine the version of the DLL you have.
// It should match this number, otherwise your .h and DLL's are from different versions.
#define DRIVER_VERSION 3.46
#define LJ_HANDLE long
#define LJ_ERROR long
#ifdef __cplusplus
extern "C"
{
#endif
// **************************************************
// Functions
// **************************************************
// The S form of these functions (the ones with S at the end) take strings instead of numerics for places where constants
// would normally be used. This allows languages that can't include this header file to still use defined constants rather
// than hard coded numbers.
// The Ptr form of these functions (the ones with Ptr at the end) take a void * instead of a long for the x1 parameter.
// This allows the x1 parameter to be 64-bit pointer address safe, and is required in 64-bit applications when passing an
// pointer/array to x1.
void _stdcall Close();
// Closes all LabJack device handles.
LJ_ERROR _stdcall ListAll(long DeviceType, long ConnectionType, long *pNumFound, long *pSerialNumbers, long *pIDs, double *pAddresses);
LJ_ERROR _stdcall ListAllS(const char *pDeviceType, const char *pConnectionType, long *pNumFound, long *pSerialNumbers, long *pIDs, double *pAddresses);
// Returns all the devices found of a given device type and connection type. pSerialNumbers, pIDs and
// pAddresses must be arrays of the given type at least 128 elements in size. pNumFound is a single element and will tell you how many
// of those 128 elements have valid data (and therefore the number of units found. With pAddresses you'll probably want
// to use the DoubleToStringAddress() function below to convert.
LJ_ERROR _stdcall OpenLabJack(long DeviceType, long ConnectionType, const char *pAddress, long FirstFound, LJ_HANDLE *pHandle);
LJ_ERROR _stdcall OpenLabJackS(const char *pDeviceType, const char *pConnectionType, const char *pAddress, long FirstFound, LJ_HANDLE *pHandle);
// Must be called before working with a device.
// DeviceType = The type of LabJack device to open (see device types constants).
// ConnectionType = How to connect to the device, USB or Ethernet presently.
// Ethernet only currently supported on the UE9.
// Address = Either the ID or serial number (if USB), or the IP address. Note this is a string for either.
// FirstFound = If true, then ignore Address and find the first available LabJack.
// pHandle = The handle to use for subsequent functions on this device, or 0 if failed.
//
// This function returns 0 if success and a handle to the open labjack, or an errorcode if failed.
LJ_ERROR _stdcall AddRequest(LJ_HANDLE Handle, long IOType, long Channel, double Value, long x1, double UserData);
LJ_ERROR _stdcall AddRequestS(LJ_HANDLE Handle, const char *pIOType, long Channel, double Value, long x1, double UserData);
LJ_ERROR _stdcall AddRequestSS(LJ_HANDLE Handle, const char *pIOType, const char *pChannel, double Value, long x1, double UserData);
LJ_ERROR _stdcall AddRequestPtr(LJ_HANDLE Handle, long IOType, long Channel, double Value, void *x1, double UserData);
// Function to add to the list of things to do with the next call to Go/GoOne().
// Handle: A handle returned by OpenLabJack().
// IOType: The type of data request (see IO type constants).
// Channel: The channel # on the particular IOType.
// Value: For output channels, the value to set to.
// X1: Optional parameters used by some IOTypes.
// UserData: Data that is kept with the request and returned with the GetFirst and GetNextResult() functions.
// Returns 0 if success, errorcode if not (most likely handle not found).
// NOTE: When you call AddRequest on a particular Handle, all previous data is erased and cannot be retrieved
// by GetResult() until read again. This is on a device by device basis, so you can call AddRequest() with a different
// handle while a device is busy performing its I/O.
// The long version is used by languages that can't cast a pointer into a double and should only be used in such situations.
LJ_ERROR _stdcall Go(void);
// Called once AddRequest has specified all the items to do. This function actually does all those things on all devices.
// takes no parameters. Returns 0 if success, errorcode if not (currently never returns an error, as errors in reading
// individual items are returned when GetResult() is called.
LJ_ERROR _stdcall GoOne(LJ_HANDLE Handle);
// Same as above, but only does requests on the given handle.
LJ_ERROR _stdcall eGet(LJ_HANDLE Handle, long IOType, long Channel, double *pValue, long x1);
LJ_ERROR _stdcall eGetPtr(LJ_HANDLE Handle, long IOType, long Channel, double *pValue, void *x1);
LJ_ERROR _stdcall eGetS(LJ_HANDLE Handle, const char *pIOType, long Channel, double *pValue, long x1);
LJ_ERROR _stdcall eGetSS(LJ_HANDLE Handle, const char *pIOType, const char *pChannel, double *pValue, long x1);
LJ_ERROR _stdcall ePut(LJ_HANDLE Handle, long IOType, long Channel, double Value, long x1);
LJ_ERROR _stdcall ePutS(LJ_HANDLE Handle, const char *pIOType, long Channel, double Value, long x1);
LJ_ERROR _stdcall ePutSS(LJ_HANDLE Handle, const char *pIOType, const char *pChannel, double Value, long x1);
LJ_ERROR _stdcall eGet_DblArray(LJ_HANDLE Handle, long IOType, long Channel, double *pValue, double *x1);
LJ_ERROR _stdcall eGet_U8Array(LJ_HANDLE Handle, long IOType, long Channel, double *pValue, unsigned char *x1);
LJ_ERROR _stdcall eGetS_DblArray(LJ_HANDLE Handle, const char *pIOType, long Channel, double *pValue, double *x1);
LJ_ERROR _stdcall eGetS_U8Array(LJ_HANDLE Handle, const char *pIOType, long Channel, double *pValue, unsigned char *x1);
LJ_ERROR _stdcall eGetSS_DblArray(LJ_HANDLE Handle, const char *pIOType, const char *pChannel, double *pValue, double *x1);
LJ_ERROR _stdcall eGetSS_U8Array(LJ_HANDLE Handle, const char *pIOType, const char *pChannel, double *pValue, unsigned char *x1);
// These functions do AddRequest, Go, and GetResult in one step. The Get versions are designed for inputs or retrieving parameters
// as it takes a pointer to a double where the result is placed, but can be used for outputs if pValue is preset to the
// desired value. This is also useful for things like StreamRead where a value is required to be input and a value is
// returned. The Put versions are designed for outputs or setting configuration parameters and won't return anything but the error code.
// Internally, all the put versions do is call the get function with a pointer set for you.
// You can repetitively call Go() and GoOne() along with GetResult() to repeat the same requests. Once you call AddRequest()
// once on a particular device, it will clear out the requests on that particular device.
// NOTE: Be careful when using multiple devices and Go(): AddRequest() only clears out the request list on the device handle
// provided. If, for example, you perform run two requests, one on each of two different devices, and then add a new request on
// one device but not the other and then call Go(), the original request on the second device will be performed again.
LJ_ERROR _stdcall GetResult(LJ_HANDLE Handle, long IOType, long Channel, double *pValue);
LJ_ERROR _stdcall GetResultS(LJ_HANDLE Handle, const char *pIOType, long Channel, double *pValue);
LJ_ERROR _stdcall GetResultSS(LJ_HANDLE Handle, const char *pIOType, const char *pChannel, double *pValue);
// Called to retrieve data and error codes for the things done in Go(). Typically this should be called
// for each element passed with AddRequest, but outputs can be skipped if errorcodes not needed.
// Handle, IOType, Channel: these should match the parameters passed in AddRequest to retrieve the result for
// that particular item.
// pValue = Value retrieved for that item.
// Returns 0 if success, LJE_NODATA if no data available for the particular Handle, IOType, and Channel specified,
// or the error code for the particular action performed.
// The long version is used by languages that can't cast a pointer into a double and should only be used in such situations.
LJ_ERROR _stdcall GetFirstResult(LJ_HANDLE Handle, long *pIOType, long *pChannel, double *pValue, long *px1, double *pUserData);
LJ_ERROR _stdcall GetNextResult(LJ_HANDLE Handle, long *pIOType, long *pChannel, double *pValue, long *px1, double *pUserData);
// These GetResult() type functions are designed for situations when you want to get all the results in order. Call GetFirstResult()
// first to get the first result avialable for the given handle and the error code. Then call GetNextResult() repeditively for
// subsequent requests. When either function returns LJE_NO_MORE_DATA_AVAILABLE, you're done. Note that x1 and UserData are always
// returned as well. You can therefore use UserData as space for your own tracking information, or whatever else you may need.
// Here's a sample of how a loop might work:
// err = GetFirstResult(..)
// while (!err)
// {
// process result...
// err = GetNextResult(..)
// }
LJ_ERROR _stdcall eAIN(LJ_HANDLE Handle, long ChannelP, long ChannelN, double *Voltage, long Range, long Resolution, long Settling, long Binary, long Reserved1, long Reserved2);
LJ_ERROR _stdcall eDAC(LJ_HANDLE Handle, long Channel, double Voltage, long Binary, long Reserved1, long Reserved2);
LJ_ERROR _stdcall eDI(LJ_HANDLE Handle, long Channel, long *State);
LJ_ERROR _stdcall eDO(LJ_HANDLE Handle, long Channel, long State);
LJ_ERROR _stdcall eAddGoGet(LJ_HANDLE Handle, long NumRequests, long *aIOTypes, long *aChannels, double *aValues, long *ax1s, long *aRequestErrors, long *GoError, long *aResultErrors);
LJ_ERROR _stdcall eTCConfig(LJ_HANDLE Handle, long *aEnableTimers, long *aEnableCounters, long TCPinOffset, long TimerClockBaseIndex, long TimerClockDivisor, long *aTimerModes, double *aTimerValues, long Reserved1, long Reserved2);
LJ_ERROR _stdcall eTCValues(LJ_HANDLE Handle, long *aReadTimers, long *aUpdateResetTimers, long *aReadCounters, long *aResetCounters, double *aTimerValues, double *aCounterValues, long Reserved1, long Reserved2);
LJ_ERROR _stdcall eModbus(LJ_HANDLE Handle, long readwrite, long addr, long size, unsigned char *value);
// Prototypes for beta version of easy functions to make simple tasks easier.
// *************************************************
// NOTE: This driver is completely thread safe. With some very minor exceptions, you can call all these functions from
// multiple threads at the same time and the driver will keep everything straight. Because of this, you must call Add...(),
// Go...() and Get...() from the same thread for a particular set of requests. Internally the list of things to do and
// results are split by thread. This allows you to use multiple threads to make requests without accidently getting
// data from one thread into another. If you are Adding requests and then getting NO_DATA_AVAILABlE or similar error when
// Getting the results, then chances are you are running in different threads and don't realize this.
// SubNote: The driver tracks which thread a request is made in by the thread ID. If you kill a thread and then create a new one
// it is possible for the new thread to have the same ID. Its not really a problem if you call AddRequest first, but if you
// did GetFirstResult on a new thread you may actually get data from the thread that already ended.
// SubNote: As mentioned, the list of requests and results is kept on a thread by thread basis. Since the driver can't tell
// when a thread has ended, the results are kept in memory for that thread even though the thread is done (thus the reason for the
// above mentioned subnote). This is not a problem in general as the driver will clean it all up when its unloaded. When it can
// be a problem is in situations where you are creating and destorying threads continuously. This will result in the slow consumption
// of memory as requests on old threads are left behind. Since each request only uses 44 bytes and as mentioned the ID's will
// eventually get recycled, it won't be a huge memory loss, but it will be there. In general, even without this issue, we strongly
// recommend against creating and destroying a lot of threads. Its terribly slow and inefficient. Use thread pools and other
// techniques to keep new thread creation to a minimum. This is what is done internally,
// **************************************************
// NOTE: Continuing on the thread safety issue, the one big exception to the thread safety of this driver is in the use of
// the windows TerminateThread() function. As it warns in the MSDN documentation, using TerminateThread() will kill the thread
// without releasing any resources, and more importantly, releasing any synchronization objects. If you TerminateThread() on a
// thread that is currently in the middle of a call to this driver, you will more than likely leave a synchronization object open
// on the particular device and you will no longer be able to access the device from you application until you restart. On some
// devices, it can be worse. On devices that have interprocess synchonization, such as the U12, calling TerminateThread() may
// kill all access to the device through this driver no matter which process is using it and even if you restart your application.
// Just avoid using TerminateThread()! All device calls have a timeout, which defaults to 1 second, but is changeable. Make sure
// when you are waiting for the driver that you wait at least as long as the timeout for it to finish.
// **************************************************
LJ_ERROR _stdcall ResetLabJack(LJ_HANDLE Handle);
// Error functions:
LJ_ERROR _stdcall GetNextError(LJ_HANDLE Handle, long *pIOType, long *pChannel);
// Instead of having to check every GetResult for errors, you can instead repetitively call GetNextError to retrieve all the errors
// from a particular Go. This includes eGet, ePut, etc if you want to use the same error handling routine. This function will
// return an error with each call along with the IOType and channel that caused the error. If there are no errors or no errors left
// it will return LJE_NOERROR.
LJ_ERROR _stdcall GetStreamError(LJ_HANDLE Handle);
// This function allows you to quickly determine if there is a stream error on a particular device. It only applies when
// stream is running. This is especially useful if you are using a StreamCallback function, which will pass -1 in as scansavailable
// if there is an error.
// Useful functions:
// Some config functions require IP address in a double instead of a string. Here are some helpful functions:
LJ_ERROR _stdcall DoubleToStringAddress(double Number, char *pString, long HexDot);
// Takes the given IP address in number notation (32 bit), and puts it into the String. String should be
// preallocated to at least 16 bytes (255.255.255.255\0).
LJ_ERROR _stdcall StringToDoubleAddress(const char *pString, double *pNumber, long HexDot);
// Does the opposite, takes an IP address in dot notation and puts it into the given double.
long _stdcall StringToConstant(const char *pString);
// Converts the given string to the appropriate constant. Used internally by the S functions, but could be useful if
// you wanted to use the GetFirst/Next functions and couldn't use this header. Then you could do a comparison on the
// returned values:
//
// if (IOType == StringToConstant("LJ_ioGET_AIN"))
//
// This function returns LJ_INVALID_CONSTANT if an invalid constant.
void _stdcall ErrorToString(LJ_ERROR ErrorCode, char *pString);
// Returns a string describing the given error code or an empty string if not found. pString must be at least 256 chars in length.
double _stdcall GetDriverVersion(void);
// Returns the version number of this driver, the resultant number should match the number at the top of this header file.
unsigned long _stdcall GetThreadID(void);
// Returns the ID of the current thread.
LJ_ERROR _stdcall TCVoltsToTemp( long TCType, double TCVolts, double CJTempK, double *pTCTempK);
// Utility function to convert voltage readings from thermocouples to temperatures. Use the LJ_tt constants
// to specify a thermocouple type. Types B, E, J, K, N, R, S and T are supported. TC voltes is the
// measured voltage. CJTempK is the cold junction temperature in kelvin and the output is placed into pTCTempK.
// **************************************************
// Constants
// **************************************************
// Device types:
const long LJ_dtUE9 = 9;
const long LJ_dtU3 = 3;
const long LJ_dtU6 = 6;
const long LJ_dtSMB = 1000;
// Connection types:
const long LJ_ctUSB = 1; // UE9 + U3 + U6
const long LJ_ctETHERNET = 2; // UE9 only
const long LJ_ctETHERNET_MB = 3; // Modbus over Ethernet. UE9 only.
const long LJ_ctETHERNET_DATA_ONLY = 4; // Opens data port but not stream port. UE9 only.
// Raw connection types are used to open a device but not communicate with it
// should only be used if the normal connection types fail and for testing.
// If a device is opened with the raw connection types, only LJ_ioRAW_OUT
// and LJ_ioRAW_IN io types should be used.
const long LJ_ctUSB_RAW = 101; // UE9 + U3 + U6
const long LJ_ctETHERNET_RAW = 102; // UE9 only
// IO types:
const long LJ_ioGET_AIN = 10; // UE9 + U3 + U6. This is single ended version.
const long LJ_ioGET_AIN_DIFF = 15; // U3/U6 only. Put negative channel in x1. If 32 is passed as x1, Vref will be added to the result.
const long LJ_ioGET_AIN_ADVANCED = 16; // For testing purposes.
const long LJ_ioPUT_AIN_RANGE = 2000; // UE9 + U6
const long LJ_ioGET_AIN_RANGE = 2001; // UE9 only
// Sets or reads the analog or digital mode of the FIO and EIO pins. FIO is Channel 0-7, EIO 8-15.
const long LJ_ioPUT_ANALOG_ENABLE_BIT = 2013; // U3 only
const long LJ_ioGET_ANALOG_ENABLE_BIT = 2014; // U3 only
// Sets or reads the analog or digital mode of the FIO and EIO pins. Channel is starting
// bit #, x1 is number of bits to read. The pins are set by passing a bitmask as a double
// for the value. The first bit of the int that the double represents will be the setting
// for the pin number sent into the channel variable.
const long LJ_ioPUT_ANALOG_ENABLE_PORT = 2015; // U3 only
const long LJ_ioGET_ANALOG_ENABLE_PORT = 2016; // U3 only
const long LJ_ioPUT_DAC = 20; // UE9 + U3 + U6
const long LJ_ioPUT_DAC_ENABLE = 2002; // UE9 + U3 (U3 on Channel 1 only)
const long LJ_ioGET_DAC_ENABLE = 2003; // UE9 + U3 (U3 on Channel 1 only)
const long LJ_ioGET_DIGITAL_BIT = 30; // UE9 + U3 + U6. Changes direction of bit to input as well.
const long LJ_ioGET_DIGITAL_BIT_DIR = 31; // UE9 + U3 + U6
const long LJ_ioGET_DIGITAL_BIT_STATE = 32; // UE9 + U3 + U6. Does not change direction of bit, allowing readback of output.
// Channel is starting bit #, x1 is number of bits to read.
const long LJ_ioGET_DIGITAL_PORT = 35; // UE9 + U3 + U6 // changes direction of bits to input as well.
const long LJ_ioGET_DIGITAL_PORT_DIR = 36; // UE9 + U3 + U6
const long LJ_ioGET_DIGITAL_PORT_STATE = 37; //UE9 + U3 + U6 // does not change direction of bits, allowing readback of output.
// Digital put commands will set the specified digital line(s) to output.
const long LJ_ioPUT_DIGITAL_BIT = 40; // UE9 + U3 + U6
// Channel is starting bit #, value is output value, x1 is bits to write.
const long LJ_ioPUT_DIGITAL_PORT = 45; // UE9 + U3 + U6
// Used to create a pause between two events in a U3 low-level feedback
// command. For example, to create a 100 ms positive pulse on FIO0, add a
// request to set FIO0 high, add a request for a wait of 100000, add a
// request to set FIO0 low, then Go. Channel is ignored. Value is
// microseconds to wait and should range from 0 to 8388480. The actual
// resolution of the wait is 128 microseconds. On U3 hardware version
// 1.20 the resolution and delay times are doubled.
const long LJ_ioPUT_WAIT = 70; // U3 + U6
// Counter. Input only.
const long LJ_ioGET_COUNTER = 50; // UE9 + U3 + U6
const long LJ_ioPUT_COUNTER_ENABLE = 2008; // UE9 + U3 + U6
const long LJ_ioGET_COUNTER_ENABLE = 2009; // UE9 + U3 + U6
// This will cause the designated counter to reset. If you want to reset the counter with
// every read, you have to use this command every time.
const long LJ_ioPUT_COUNTER_RESET = 2012; // UE9 + U3 + U6
// On UE9: timer only used for input. Output Timers don't use these. Only Channel used.
// On U3/U6: Channel used (0 or 1).
const long LJ_ioGET_TIMER = 60; // UE9 + U3 + U6
const long LJ_ioPUT_TIMER_VALUE = 2006; // UE9 + U3 + U6. Value gets new value.
const long LJ_ioPUT_TIMER_MODE = 2004; // UE9 + U3 + U6. On both Value gets new mode.
const long LJ_ioGET_TIMER_MODE = 2005; // UE9 + U3 + U6
// IOType for use with SHT sensor. For LJ_ioSHT_GET_READING, a channel of LJ_chSHT_TEMP (5000) will
// read temperature, and LJ_chSHT_RH (5001) will read humidity.
const long LJ_ioSHT_GET_READING = 500; // UE9 + U3 + U6
// Uses settings from LJ_chSPI special channels (set with LJ_ioPUT_CONFIG) to communcaite with
// something using an SPI interface. The value parameter is the number of bytes to transfer
// and x1 is the address of the buffer. The data from the buffer will be sent, then overwritten
// with the data read. The channel parameter is ignored.
const long LJ_ioSPI_COMMUNICATION = 503; // UE9 + U3 + U6
const long LJ_ioI2C_COMMUNICATION = 504; // UE9 + U3 + U6
const long LJ_ioASYNCH_COMMUNICATION = 505; // UE9 + U3 + U6
const long LJ_ioTDAC_COMMUNICATION = 506; // UE9 + U3 + U6
// Sets the original configuration.
// On U3: This means sending the following to the ConfigIO and TimerClockConfig low level
// functions.
//
// ConfigIO
// Byte #
// 6 WriteMask 15 Write all parameters.
// 8 TimerCounterConfig 0 No timers/counters. Offset=0.
// 9 DAC1Enable 0 DAC1 disabled.
// 10 FIOAnalog 0 FIO all digital.
// 11 EIOAnalog 0 EIO all digital.
//
//
// TimerClockConfig
// Byte #
// 8 TimerClockConfig 130 Set clock to 48 MHz. (24 MHz for U3 hardware version 1.20 or less)
// 9 TimerClockDivisor 0 Divisor = 0.
//
// On UE9/U6: This means disabling all timers and counters, setting the TimerClockConfig to
// default (750 kHZ for UE9, 48 MHz for U6) and the offset to 0 (U6).
//
const long LJ_ioPIN_CONFIGURATION_RESET = 2017; // UE9 + U3 + U6
// The raw in/out are unusual, channel number corresponds to the particular comm port, which
// depends on the device. For example, on the UE9, 0 is main comm port, and 1 is the streaming comm.
// Make sure and pass a porter to a char buffer in x1, and the number of bytes desired in value. A call
// to GetResult will return the number of bytes actually read/written. The max you can send out in one call
// is 512 bytes to the UE9 and 16384 bytes to the U3.
const long LJ_ioRAW_OUT = 100; // UE9 + U3 + U6
const long LJ_ioRAW_IN = 101; // UE9 + U3 + U6
const long LJ_ioRAWMB_OUT = 104; // UE9 Only. Used with LJ_ctETHERNET_MB to send raw modbus commands to the modbus TCP/IP Socket.
const long LJ_ioRAWMB_IN = 105; // UE9 only. Used with LJ_ctETHERNET_MB to receive raw modbus responses from the modbus TCP/IP Socket.
// Sets the default power up settings based on the current settings of the device AS THIS DLL KNOWS. This last part
// basically means that you should set all parameters directly through this driver before calling this. This writes
// to flash which has a limited lifetime, so do not do this too often. Rated endurance is 20,000 writes.
const long LJ_ioSET_DEFAULTS = 103; // U3 + U6
// Requests to create the list of channels to stream. Usually you will use the CLEAR_STREAM_CHANNELS request first, which
// will clear any existing channels, then use ADD_STREAM_CHANNEL multiple times to add your desired channels. Note that
// you can do CLEAR, and then all your ADDs in a single Go() as long as you add the requests in order.
const long LJ_ioADD_STREAM_CHANNEL = 200; // UE9 + U3 + U6
// Put negative channel in x1. If 32 is passed as x1, Vref will be added to the result.
const long LJ_ioADD_STREAM_CHANNEL_DIFF = 206; // U3 + U6
const long LJ_ioCLEAR_STREAM_CHANNELS = 201; // UE9 + U3 + U6
const long LJ_ioSTART_STREAM = 202; // UE9 + U3 + U6
const long LJ_ioSTOP_STREAM = 203; // UE9 + U3 + U6
const long LJ_ioADD_STREAM_DAC = 207; //UE9 only
// Get stream data has several options. If you just want to get a single channel's data (if streaming multiple channels), you
// can pass in the desired channel #, then the number of data points desired in Value, and a pointer to an array to put the
// data into as X1. This array needs to be an array of doubles. Therefore, the array needs to be 8 * number of
// requested data points in byte length. What is returned depends on the StreamWaitMode. If None, this function will only return
// data available at the time of the call. You therefore must call GetResult() for this function to retrieve the actually number
// of points retreived. If Pump or Sleep, it will return only when the appropriate number of points have been read or no
// new points arrive within 100ms. Since there is this timeout, you still need to use GetResult() to determine if the timeout
// occured. If AllOrNone, you again need to check GetResult.
//
// You can also retreive the entire scan by passing LJ_chALL_CHANNELS. In this case, the Value determines the number of SCANS
// returned, and therefore, the array must be 8 * number of scans requested * number of channels in each scan. Likewise
// GetResult() will return the number of scans, not the number of data points returned.
//
// Note: data is stored interleaved across all streaming channels. In other words, if you are streaming two channels, 0 and 1,
// and you request LJ_chALL_CHANNELS, you will get, Channel0, Channel1, Channel0, Channel1, etc. Once you have requested the
// data, any data returned is removed from the internal buffer, and the next request will give new data.
//
// Note: if reading the data channel by channel and not using LJ_chALL_CHANNELS, the data is not removed from the internal buffer
// until the data from the last channel in the scan is requested. This means that if you are streaming three channels, 0, 1 and 2,
// and you request data from channel 0, then channel 1, then channel 0 again, the request for channel 0 the second time will
// return the exact same data. Also note, that the amount of data that will be returned for each channel request will be
// the same until you've read the last channel in the scan, at which point your next block may be a different size.
//
// Note: although more convenient, requesting individual channels is slightly slower then using LJ_chALL_CHANNELS. Since you
// are probably going to have to split the data out anyway, we have saved you the trouble with this option.
//
// Note: if you are only scanning one channel, the Channel parameter is ignored.
const long LJ_ioGET_STREAM_DATA = 204; // UE9 + U3 + U6
// Since this driver has to start a thread to poll the hardware in stream mode, we give you the option of having this thread
// call a user defined function after a block of data has been read. To use, pass a pointer to the following function type as
// Channel. Pass 0 to turn this feature off. X1 is a user definable value that is passed when the callback function is called.
// Value is the number of scans before the callback occurs. If 0, then the default is used, which varies depending on the
// device and scan rate but typically results in the callback being called about every 10ms.
/* example:
void StreamCallback(long ScansAvailable, long UserValue)
{
... do stuff when a callback occurs (retrieve data for example)
}
...
tStreamCallback pCallback = StreamCallback;
AddRequest(Handle,LJ_ioSET_STREAM_CALLBACK,(long)pCallback,0,0,0);
...
*/
// NOTE: the callback function is called from a secondary worker thread that has no message pump. Do not directly update any
// windows controls from your callback as there is no message pump to do so. On the same note, the driver stream buffer is locked
// during the callback function. This means that while your callback function is running, you cannot do a GetStreamData or any
// other stream function from a DIFFERENT thread. You can of course do getstreamdata from the callback function. You don't really
// have to worry about this much as any other thread trying to do GetStreamData or other function will simply stall until your
// callback is complete and the lock released. Where you will run into trouble is if your callback function waits on another thread
// that is trying to do a stream function. Note this applies on a device by device basis.
typedef void (*tStreamCallback)(long ScansAvailable, long UserValue);
const long LJ_ioSET_STREAM_CALLBACK = 205; // UE9 + U3 + U6
const long LJ_ioSET_STREAM_CALLBACK_PTR = 260; // UE9 + U3 + U6. This is for 64-bit compatibility. The tStreamCallback function is passed as X1 and channel is the User Variable.
// Channel = 0 buzz for a count, Channel = 1 buzz continuous.
// Value is the Period.
// X1 is the toggle count when channel = 0.
const long LJ_ioBUZZER = 300; // U3 only
// There are a number of things that happen asynchronously inside the UD driver and so don't directly associate with a Add, Go, or
// Get function. To allow the UD to tell your code when these events occur, you can pass it a callback function that will
// be called whenever this occurs. For an example of how to use the callback, look at the StreamCallback above. Like the
// streamcallback, the function may be called from any thread, maybe one with a message pump, maybe not, so you should make
// your function fast and don't do anything with windows or on screen controls.
typedef void (*tEventCallback)(long EventCode, long Data1, long Data2, long Data3, long UserValue);
// Pass pointer to function as Channel, and userdata as x1. Value not used, but should be set to 0 for forward
// compatibility. If more events are required with future LabJacks, we may use this to allow you to specify which
// events you wish to receive notifcation of and 0 will mean All.
const long LJ_ioSET_EVENT_CALLBACK = 400; // UE9 + U3 + U6
// These are the possible EventCodes that will be passed:
const long LJ_ecDISCONNECT = 1; // Called when the device is unplugged from USB. No Data is passed.
const long LJ_ecRECONNECT = 2; // Called when the device is reconnected to USB. No Data is passed.
const long LJ_ecSTREAMERROR = 4; // Called when a stream error occurs. Data1 is errorcode, Data2 and Data3 are not used.
// Future events will be power of 2.
// Config iotypes:
const long LJ_ioPUT_CONFIG = 1000; // UE9 + U3 + U6
const long LJ_ioGET_CONFIG = 1001; // UE9 + U3 + U6
// Channel numbers used for CONFIG types:
const long LJ_chLOCALID = 0; // UE9 + U3 + U6
const long LJ_chHARDWARE_VERSION = 10; // UE9 + U3 + U6 (Read Only)
const long LJ_chSERIAL_NUMBER = 12; // UE9 + U3 + U6 (Read Only)
const long LJ_chFIRMWARE_VERSION = 11; // UE9 + U3 + U6 (Read Only)
const long LJ_chBOOTLOADER_VERSION = 15; // UE9 + U3 + U6 (Read Only)
const long LJ_chPRODUCTID = 8; // UE9 + U3 + U6 (Read Only)
// UE9 specific:
const long LJ_chCOMM_POWER_LEVEL = 1; // UE9
const long LJ_chIP_ADDRESS = 2; // UE9
const long LJ_chGATEWAY = 3; // UE9
const long LJ_chSUBNET = 4; // UE9
const long LJ_chPORTA = 5; // UE9
const long LJ_chPORTB = 6; // UE9
const long LJ_chDHCP = 7; // UE9
const long LJ_chMACADDRESS = 9; // UE9
const long LJ_chCOMM_FIRMWARE_VERSION = 11; // UE9
const long LJ_chCONTROL_POWER_LEVEL = 13; // UE9
const long LJ_chCONTROL_FIRMWARE_VERSION = 14; // UE9 (Read Only)
const long LJ_chCONTROL_BOOTLOADER_VERSION = 15; // UE9 (Read Only)
const long LJ_chCONTROL_RESET_SOURCE = 16; // UE9 (Read Only)
const long LJ_chUE9_PRO = 19; // UE9 (Read Only)
const long LJ_chLED_STATE = 17; // U3 + U6. Sets the state of the LED. Value = LED state.
const long LJ_chSDA_SCL = 18; // U3 + U6. Enable/disable SDA/SCL as digital I/O.
const long LJ_chU3HV = 22; // U3 only (Read Only). Value will be 1 for a U3-HV and 0 for a U3-LV or a U3 with hardware version < 1.30.
const long LJ_chU6_PRO = 23; // U6 only.
// Driver related:
// Number of milliseconds that the driver will wait for communication to complete.
const long LJ_chCOMMUNICATION_TIMEOUT = 20;
const long LJ_chSTREAM_COMMUNICATION_TIMEOUT = 21;
// Used to access calibration and user data. The address of an array is passed in as x1.
// For the UE9, a 1024-element buffer of bytes is passed for user data and a 128-element
// buffer of doubles is passed for cal constants.
// For the U3/U3-LV, a 256-element buffer of bytes is passed for user data and a 12-element
// buffer of doubles is passed for cal constants.
// For the U3-HV, a 256-element buffer of bytes is passed for user data and a 20-element
// buffer of doubles is passed for cal constants.
// For the U6, a 256-element buffer of bytes is passed for user data and a 64-element
// buffer of doubles is passed for cal constants.
// The layout of cal constants are defined in the users guide for each device.
// When the LJ_chCAL_CONSTANTS special channel is used with PUT_CONFIG, a
// special value (0x4C6C) must be passed in to the Value parameter. This makes it
// more difficult to accidently erase the cal constants. In all other cases the Value
// parameter is ignored.
const long LJ_chCAL_CONSTANTS = 400; // UE9 + U3 + U6
const long LJ_chUSER_MEM = 402; // UE9 + U3 + U6
// Used to write and read the USB descriptor strings. This is generally for OEMs
// who wish to change the strings.
// Pass the address of an array in x1. Value parameter is ignored.
// The array should be 128 elements of bytes. The first 64 bytes are for the
// iManufacturer string, and the 2nd 64 bytes are for the iProduct string.
// The first byte of each 64 byte block (bytes 0 and 64) contains the number
// of bytes in the string. The second byte (bytes 1 and 65) is the USB spec
// value for a string descriptor (0x03). Bytes 2-63 and 66-127 contain unicode
// encoded strings (up to 31 characters each).
const long LJ_chUSB_STRINGS = 404; // U3 + U6
// Timer/counter related:
const long LJ_chNUMBER_TIMERS_ENABLED = 1000; // UE9 + U3 + U6
const long LJ_chTIMER_CLOCK_BASE = 1001; // UE9 + U3 + U6
const long LJ_chTIMER_CLOCK_DIVISOR = 1002; // UE9 + U3 + U6
const long LJ_chTIMER_COUNTER_PIN_OFFSET = 1003; // U3 + U6
// AIn related:
const long LJ_chAIN_RESOLUTION = 2000; // UE9 + U3 + U6
const long LJ_chAIN_SETTLING_TIME = 2001; // UE9 + U3 + U6
const long LJ_chAIN_BINARY = 2002; // UE9 + U3 + U6
// DAC related:
const long LJ_chDAC_BINARY = 3000; // UE9 + U3
// SHT related:
// LJ_chSHT_TEMP and LJ_chSHT_RH are used with LJ_ioSHT_GET_READING to read those values.
// The LJ_chSHT_DATA_CHANNEL and LJ_chSHT_SCK_CHANNEL constants use the passed value
// to set the appropriate channel for the data and SCK lines for the SHT sensor.
// Default digital channels are FIO0 for the data channel and FIO1 for the clock channel.
const long LJ_chSHT_TEMP = 5000; // UE9 + U3 + U6
const long LJ_chSHT_RH = 5001; // UE9 + U3 + U6
const long LJ_chSHT_DATA_CHANNEL = 5002; // UE9 + U3 + U6. Default is FIO0
const long LJ_chSHT_CLOCK_CHANNEL = 5003; // UE9 + U3 + U6. Default is FIO1
// SPI related:
const long LJ_chSPI_AUTO_CS = 5100; // UE9 + U3 + U6
const long LJ_chSPI_DISABLE_DIR_CONFIG = 5101; // UE9 + U3 + U6
const long LJ_chSPI_MODE = 5102; // UE9 + U3 + U6
const long LJ_chSPI_CLOCK_FACTOR = 5103; // UE9 + U3 + U6
const long LJ_chSPI_MOSI_PIN_NUM = 5104; // UE9 + U3 + U6
const long LJ_chSPI_MISO_PIN_NUM = 5105; // UE9 + U3 + U6
const long LJ_chSPI_CLK_PIN_NUM = 5106; // UE9 + U3 + U6
const long LJ_chSPI_CS_PIN_NUM = 5107; // UE9 + U3 + U6
// I2C related:
// Used with LJ_ioPUT_CONFIG
const long LJ_chI2C_ADDRESS_BYTE = 5108; // UE9 + U3 + U6
const long LJ_chI2C_SCL_PIN_NUM = 5109; // UE9 + U3 + U6
const long LJ_chI2C_SDA_PIN_NUM = 5110; // UE9 + U3 + U6
const long LJ_chI2C_OPTIONS = 5111; // UE9 + U3 + U6
const long LJ_chI2C_SPEED_ADJUST = 5112; // UE9 + U3 + U6
// Used with LJ_ioI2C_COMMUNICATION:
const long LJ_chI2C_READ = 5113; // UE9 + U3 + U6
const long LJ_chI2C_WRITE = 5114; // UE9 + U3 + U6
const long LJ_chI2C_GET_ACKS = 5115; // UE9 + U3 + U6
const long LJ_chI2C_WRITE_READ = 5130; // UE9 + U3 + U6
// ASYNCH related:
// Used with LJ_ioASYNCH_COMMUNICATION
const long LJ_chASYNCH_RX = 5117; // UE9 + U3 + U6
const long LJ_chASYNCH_TX = 5118; // UE9 + U3 + U6
const long LJ_chASYNCH_FLUSH = 5128; // UE9 + U3 + U6
const long LJ_chASYNCH_ENABLE = 5129; // UE9 + U3 + U6
// Used with LJ_ioPUT_CONFIG and LJ_ioGET_CONFIG
const long LJ_chASYNCH_BAUDFACTOR = 5127; // UE9 + U3 + U6
// LJ TickDAC related:
const long LJ_chTDAC_SCL_PIN_NUM = 5119; // UE9 + U3 + U6: Used with LJ_ioPUT_CONFIG.
// Used with LJ_ioTDAC_COMMUNICATION
const long LJ_chTDAC_SERIAL_NUMBER = 5120; // UE9 + U3 + U6: Read only.
const long LJ_chTDAC_READ_USER_MEM = 5121; // UE9 + U3 + U6
const long LJ_chTDAC_WRITE_USER_MEM = 5122; // UE9 + U3 + U6
const long LJ_chTDAC_READ_CAL_CONSTANTS = 5123; // UE9 + U3 + U6
const long LJ_chTDAC_WRITE_CAL_CONSTANTS = 5124; // UE9 + U3 + U6
const long LJ_chTDAC_UPDATE_DACA = 5125; // UE9 + U3 + U6
const long LJ_chTDAC_UPDATE_DACB = 5126; // UE9 + U3 + U6
// Stream related. Note: Putting to any of these values will stop any running streams.
const long LJ_chSTREAM_SCAN_FREQUENCY = 4000; // UE9 + U3 + U6
const long LJ_chSTREAM_BUFFER_SIZE = 4001;
const long LJ_chSTREAM_CLOCK_OUTPUT = 4002; // UE9 only
const long LJ_chSTREAM_EXTERNAL_TRIGGER = 4003; // UE9 only
const long LJ_chSTREAM_WAIT_MODE = 4004;
const long LJ_chSTREAM_DISABLE_AUTORECOVERY = 4005; // U3 + U6
const long LJ_chSTREAM_SAMPLES_PER_PACKET = 4108; // UE9 + U3 + U6. Read only for UE9.
const long LJ_chSTREAM_READS_PER_SECOND = 4109;
const long LJ_chAIN_STREAM_SETTLING_TIME = 4110; // U6 only
// Read only stream related
const long LJ_chSTREAM_BACKLOG_COMM = 4105; // UE9 + U3 + U6
const long LJ_chSTREAM_BACKLOG_CONTROL = 4106; // UE9 only
const long LJ_chSTREAM_BACKLOG_UD = 4107;
// Special channel numbers
const long LJ_chALL_CHANNELS = -1;
const long LJ_INVALID_CONSTANT = -999;
//Thermocouple Type constants.
const long LJ_ttB = 6001;
const long LJ_ttE = 6002;
const long LJ_ttJ = 6003;
const long LJ_ttK = 6004;
const long LJ_ttN = 6005;
const long LJ_ttR = 6006;
const long LJ_ttS = 6007;
const long LJ_ttT = 6008;
// Other constants:
// Ranges (not all are supported by all devices):
const long LJ_rgBIP20V = 1; // -20V to +20V
const long LJ_rgBIP10V = 2; // -10V to +10V
const long LJ_rgBIP5V = 3; // -5V to +5V
const long LJ_rgBIP4V = 4; // -4V to +4V
const long LJ_rgBIP2P5V = 5; // -2.5V to +2.5V
const long LJ_rgBIP2V = 6; // -2V to +2V
const long LJ_rgBIP1P25V = 7; // -1.25V to +1.25V
const long LJ_rgBIP1V = 8; // -1V to +1V
const long LJ_rgBIPP625V = 9; // -0.625V to +0.625V
const long LJ_rgBIPP1V = 10; // -0.1V to +0.1V
const long LJ_rgBIPP01V = 11; // -0.01V to +0.01V
const long LJ_rgUNI20V = 101; // 0V to +20V
const long LJ_rgUNI10V = 102; // 0V to +10V
const long LJ_rgUNI5V = 103; // 0V to +5V
const long LJ_rgUNI4V = 104; // 0V to +4V
const long LJ_rgUNI2P5V = 105; // 0V to +2.5V
const long LJ_rgUNI2V = 106; // 0V to +2V
const long LJ_rgUNI1P25V = 107; // 0V to +1.25V
const long LJ_rgUNI1V = 108; // 0V to +1V
const long LJ_rgUNIP625V = 109; // 0V to +0.625V
const long LJ_rgUNIP5V = 110; // 0V to +0.500V
const long LJ_rgUNIP25V = 112; // 0V to +0.25V
const long LJ_rgUNIP3125V = 111; // 0V to +0.3125V
const long LJ_rgUNIP025V = 113; // 0V to +0.025V
const long LJ_rgUNIP0025V = 114; // 0V to +0.0025V
// Timer modes:
const long LJ_tmPWM16 = 0; // 16 bit PWM
const long LJ_tmPWM8 = 1; // 8 bit PWM
const long LJ_tmRISINGEDGES32 = 2; // 32-bit rising to rising edge measurement
const long LJ_tmFALLINGEDGES32 = 3; // 32-bit falling to falling edge measurement
const long LJ_tmDUTYCYCLE = 4; // Duty cycle measurement
const long LJ_tmFIRMCOUNTER = 5; // Firmware based rising edge counter
const long LJ_tmFIRMCOUNTERDEBOUNCE = 6; // Firmware counter with debounce
const long LJ_tmFREQOUT = 7; // Frequency output
const long LJ_tmQUAD = 8; // Quadrature
const long LJ_tmTIMERSTOP = 9; // Stops another timer after n pulses
const long LJ_tmSYSTIMERLOW = 10; // Read lower 32-bits of system timer
const long LJ_tmSYSTIMERHIGH = 11; // Read upper 32-bits of system timer
const long LJ_tmRISINGEDGES16 = 12; // 16-bit rising to rising edge measurement
const long LJ_tmFALLINGEDGES16 = 13; // 16-bit falling to falling edge measurement
const long LJ_tmLINETOLINE = 14; // Line to Line measurement
// Timer clocks:
const long LJ_tc750KHZ = 0; // UE9: 750 kHz
const long LJ_tcSYS = 1; // UE9 + U3 + U6: System clock
const long LJ_tc2MHZ = 10; // U3: Hardware Version 1.20 or lower
const long LJ_tc6MHZ = 11; // U3: Hardware Version 1.20 or lower
const long LJ_tc24MHZ = 12; // U3: Hardware Version 1.20 or lower
const long LJ_tc500KHZ_DIV = 13; // U3: Hardware Version 1.20 or lower
const long LJ_tc2MHZ_DIV = 14; // U3: Hardware Version 1.20 or lower
const long LJ_tc6MHZ_DIV = 15; // U3: Hardware Version 1.20 or lower
const long LJ_tc24MHZ_DIV = 16; // U3: Hardware Version 1.20 or lower
const long LJ_tc4MHZ = 20; // U3: Hardware Version 1.21 or higher, + U6
const long LJ_tc12MHZ = 21; // U3: Hardware Version 1.21 or higher, + U6
const long LJ_tc48MHZ = 22; // U3: Hardware Version 1.21 or higher, + U6
const long LJ_tc1MHZ_DIV = 23; // U3: Hardware Version 1.21 or higher, + U6
const long LJ_tc4MHZ_DIV = 24; // U3: Hardware Version 1.21 or higher, + U6
const long LJ_tc12MHZ_DIV = 25; // U3: Hardware Version 1.21 or higher, + U6
const long LJ_tc48MHZ_DIV = 26; // U3: Hardware Version 1.21 or higher, + U6
// Stream wait modes:
const long LJ_swNONE = 1; // No wait, return whatever is available.
const long LJ_swALL_OR_NONE = 2; // No wait, but if all points requested aren't available, return none.
const long LJ_swPUMP = 11; // Wait and pump the message pump. Preferred when called from primary thread (if you don't know
// if you are in the primary thread of your app then you probably are. Do not use in worker
// secondary threads (i.e. ones without a message pump).
const long LJ_swSLEEP = 12; // Wait by sleeping (don't do this in the primary thread of your app, or it will temporarily
// hang). This is usually used in worker secondary threads.
// BETA CONSTANTS:
// Please note that specific usage of these constants and their values might change.
// SWDT:
// Sets parameters used to control the software watchdog option. The device is only
// communicated with and updated when LJ_ioSWDT_CONFIG is used with LJ_chSWDT_ENABLE
// or LJ_chSWDT_DISABLE. Thus, to change a value, you must use LJ_io_PUT_CONFIG
// with the appropriate channel constant so set the value inside the driver, then call
// LJ_ioSWDT_CONFIG to enable that change.
const long LJ_ioSWDT_CONFIG = 507; // UE9 + U3 + U6: Use with LJ_chSWDT_ENABLE or LJ_chSWDT_DISABLE.
const long LJ_ioSWDT_STROKE = 508; // UE9 only: Used when SWDT_STRICT_ENABLE is turned on to renew the watchdog.
const long LJ_chSWDT_ENABLE = 5200; // UE9 + U3 + U6: Used with LJ_ioSWDT_CONFIG to enable watchdog. Value paramter is number of seconds to trigger.
const long LJ_chSWDT_DISABLE = 5201; // UE9 + U3 + U6: Used with LJ_ioSWDT_CONFIG to disable watchdog.
// Used with LJ_io_PUT_CONFIG
const long LJ_chSWDT_RESET_DEVICE = 5202; // U3 + U6: Reset U3 on watchdog reset. Write only.
const long LJ_chSWDT_RESET_COMM = 5203; // UE9 only: Reset Comm on watchdog reset. Write only.
const long LJ_chSWDT_RESET_CONTROL = 5204; // UE9 only: Reset Control on watchdog trigger. Write only.
const long LJ_chSWDT_UPDATE_DIOA = 5205; // UE9 + U3 + U6: Update DIO0 settings after reset. Write only.
const long LJ_chSWDT_UPDATE_DIOB = 5206; // UE9 only: Update DIO1 settings after reset. Write only.
const long LJ_chSWDT_DIOA_CHANNEL = 5207; // UE9 + U3 + U6: DIO0 channel to be set after reset. Write only.
const long LJ_chSWDT_DIOA_STATE = 5208; // UE9 + U3 + U6: DIO0 state to be set after reset. Write only.
const long LJ_chSWDT_DIOB_CHANNEL = 5209; // UE9: DIO1 channel to be set after reset. Write only.
const long LJ_chSWDT_DIOB_STATE = 5210; // UE9: DIO1 state to be set after reset. Write only.
const long LJ_chSWDT_UPDATE_DAC0 = 5211; // UE9 only: Update DAC0 settings after reset. Write only.
const long LJ_chSWDT_UPDATE_DAC1 = 5212; // UE9 only: Update DAC1 settings after reset. Write only.
const long LJ_chSWDT_DAC0 = 5213; // UE9 only: Voltage to set DAC0 at on watchdog reset. Write only.
const long LJ_chSWDT_DAC1 = 5214; // UE9 only: Voltage to set DAC1 at on watchdog reset. Write only.
const long LJ_chSWDT_DAC_ENABLE = 5215; // UE9 only: Enable DACs on watchdog reset. Default is true. Both DACs are enabled or disabled togeather. Write only.
const long LJ_chSWDT_STRICT_ENABLE = 5216; // UE9 only: Watchdog will only renew with LJ_ioSWDT_STROKE command.
const long LJ_chSWDT_INITIAL_ROLL_TIME = 5217; // UE9 only: Watchdog timer for the first cycle when powered on, after watchdog triggers a reset the normal value is used. Set to 0 to disable.
// END BETA CONSTANTS
// Error codes: These will always be in the range of -1000 to 3999 for labView compatibility (+6000).
const LJ_ERROR LJE_NOERROR = 0;
const LJ_ERROR LJE_COMMAND_LIST_ERROR = 1;
const LJ_ERROR LJE_INVALID_CHANNEL_NUMBER = 2; // Cccurs when a channel that doesn't exist is specified (i.e. DAC #2 on a UE9), or data from streaming is requested on a channel that isn't streaming.
const LJ_ERROR LJE_INVALID_RAW_INOUT_PARAMETER = 3;
const LJ_ERROR LJE_UNABLE_TO_START_STREAM = 4;
const LJ_ERROR LJE_UNABLE_TO_STOP_STREAM = 5;
const LJ_ERROR LJE_NOTHING_TO_STREAM = 6;
const LJ_ERROR LJE_UNABLE_TO_CONFIG_STREAM = 7;
const LJ_ERROR LJE_BUFFER_OVERRUN = 8; // Cccurs when stream buffer overruns (this is the driver buffer not the hardware buffer). Stream is stopped.
const LJ_ERROR LJE_STREAM_NOT_RUNNING = 9;
const LJ_ERROR LJE_INVALID_PARAMETER = 10;
const LJ_ERROR LJE_INVALID_STREAM_FREQUENCY = 11;
const LJ_ERROR LJE_INVALID_AIN_RANGE = 12;
const LJ_ERROR LJE_STREAM_CHECKSUM_ERROR = 13; // Occurs when a stream packet fails checksum. Stream is stopped.
const LJ_ERROR LJE_STREAM_COMMAND_ERROR = 14; // Occurs when a stream packet has invalid command values. Stream is stopped.
const LJ_ERROR LJE_STREAM_ORDER_ERROR = 15; // Occurs when a stream packet is received out of order (typically one is missing). Stream is stopped.
const LJ_ERROR LJE_AD_PIN_CONFIGURATION_ERROR = 16; // Occurs when an analog or digital request was made on a pin that isn't configured for that type of request.
const LJ_ERROR LJE_REQUEST_NOT_PROCESSED = 17; // When a LJE_AD_PIN_CONFIGURATION_ERROR occurs, all other IO requests after the request that caused the error won't be processed. Those requests will return this error.
// U3 & U6 Specific Errors
const LJ_ERROR LJE_SCRATCH_ERROR = 19;
const LJ_ERROR LJE_DATA_BUFFER_OVERFLOW = 20;
const LJ_ERROR LJE_ADC0_BUFFER_OVERFLOW = 21;
const LJ_ERROR LJE_FUNCTION_INVALID = 22;
const LJ_ERROR LJE_SWDT_TIME_INVALID = 23;
const LJ_ERROR LJE_FLASH_ERROR = 24;
const LJ_ERROR LJE_STREAM_IS_ACTIVE = 25;
const LJ_ERROR LJE_STREAM_TABLE_INVALID = 26;
const LJ_ERROR LJE_STREAM_CONFIG_INVALID = 27;
const LJ_ERROR LJE_STREAM_BAD_TRIGGER_SOURCE = 28;
const LJ_ERROR LJE_STREAM_INVALID_TRIGGER = 30;
const LJ_ERROR LJE_STREAM_ADC0_BUFFER_OVERFLOW = 31;
const LJ_ERROR LJE_STREAM_SAMPLE_NUM_INVALID = 33;
const LJ_ERROR LJE_STREAM_BIPOLAR_GAIN_INVALID = 34;
const LJ_ERROR LJE_STREAM_SCAN_RATE_INVALID = 35;
const LJ_ERROR LJE_TIMER_INVALID_MODE = 36;
const LJ_ERROR LJE_TIMER_QUADRATURE_AB_ERROR = 37;
const LJ_ERROR LJE_TIMER_QUAD_PULSE_SEQUENCE = 38;
const LJ_ERROR LJE_TIMER_BAD_CLOCK_SOURCE = 39;
const LJ_ERROR LJE_TIMER_STREAM_ACTIVE = 40;
const LJ_ERROR LJE_TIMER_PWMSTOP_MODULE_ERROR = 41;
const LJ_ERROR LJE_TIMER_SEQUENCE_ERROR = 42;
const LJ_ERROR LJE_TIMER_SHARING_ERROR = 43;
const LJ_ERROR LJE_TIMER_LINE_SEQUENCE_ERROR = 44;
const LJ_ERROR LJE_EXT_OSC_NOT_STABLE = 45;
const LJ_ERROR LJE_INVALID_POWER_SETTING = 46;
const LJ_ERROR LJE_PLL_NOT_LOCKED = 47;
const LJ_ERROR LJE_INVALID_PIN = 48;
const LJ_ERROR LJE_IOTYPE_SYNCH_ERROR = 49;
const LJ_ERROR LJE_INVALID_OFFSET = 50;
const LJ_ERROR LJE_FEEDBACK_IOTYPE_NOT_VALID = 51;
const LJ_ERROR LJE_CANT_CONFIGURE_PIN_FOR_ANALOG = 67;
const LJ_ERROR LJE_CANT_CONFIGURE_PIN_FOR_DIGITAL = 68;
const LJ_ERROR LJE_TC_PIN_OFFSET_MUST_BE_4_TO_8 = 70;
const LJ_ERROR LJE_INVALID_DIFFERENTIAL_CHANNEL = 71;
const LJ_ERROR LJE_DSP_SIGNAL_OUT_OF_RANGE = 72;
// Other errors
const LJ_ERROR LJE_SHT_CRC = 52;
const LJ_ERROR LJE_SHT_MEASREADY = 53;
const LJ_ERROR LJE_SHT_ACK = 54;
const LJ_ERROR LJE_SHT_SERIAL_RESET = 55;
const LJ_ERROR LJE_SHT_COMMUNICATION = 56;
const LJ_ERROR LJE_AIN_WHILE_STREAMING = 57;
const LJ_ERROR LJE_STREAM_TIMEOUT = 58;
const LJ_ERROR LJE_STREAM_CONTROL_BUFFER_OVERFLOW = 59;
const LJ_ERROR LJE_STREAM_SCAN_OVERLAP = 60;
const LJ_ERROR LJE_FIRMWARE_VERSION_IOTYPE = 61;
const LJ_ERROR LJE_FIRMWARE_VERSION_CHANNEL = 62;
const LJ_ERROR LJE_FIRMWARE_VERSION_VALUE = 63;
const LJ_ERROR LJE_HARDWARE_VERSION_IOTYPE = 64;
const LJ_ERROR LJE_HARDWARE_VERSION_CHANNEL = 65;
const LJ_ERROR LJE_HARDWARE_VERSION_VALUE = 66;
const LJ_ERROR LJE_LJTDAC_ACK_ERROR = 69;
const LJ_ERROR LJE_STREAM_INVALID_CONNECTION = 73;
const LJ_ERROR LJE_MIN_GROUP_ERROR = 1000; // All errors above this number will stop all requests, below this number are request level errors.
const LJ_ERROR LJE_UNKNOWN_ERROR = 1001; // Occurs when an unknown error occurs that is caught, but still unknown.
const LJ_ERROR LJE_INVALID_DEVICE_TYPE = 1002; // Occurs when devicetype is not a valid device type.
const LJ_ERROR LJE_INVALID_HANDLE = 1003; // Occurs when invalid handle used.
const LJ_ERROR LJE_DEVICE_NOT_OPEN = 1004; // Occurs when Open() fails and AppendRead called despite.
const LJ_ERROR LJE_NO_DATA_AVAILABLE = 1005; // This is cause when GetResult() called without calling Go/GoOne(), or when GetResult() passed a channel that wasn't read.
const LJ_ERROR LJE_NO_MORE_DATA_AVAILABLE = 1006;
const LJ_ERROR LJE_LABJACK_NOT_FOUND = 1007; // Occurs when the LabJack is not found at the given id or address.
const LJ_ERROR LJE_COMM_FAILURE = 1008; // Occurs when unable to send or receive the correct number of bytes.
const LJ_ERROR LJE_CHECKSUM_ERROR = 1009;
const LJ_ERROR LJE_DEVICE_ALREADY_OPEN = 1010; // Occurs when LabJack is already open via USB in another program or process.
const LJ_ERROR LJE_COMM_TIMEOUT = 1011;
const LJ_ERROR LJE_USB_DRIVER_NOT_FOUND = 1012;
const LJ_ERROR LJE_INVALID_CONNECTION_TYPE = 1013;
const LJ_ERROR LJE_INVALID_MODE = 1014;
const LJ_ERROR LJE_DEVICE_NOT_CONNECTED = 1015; // Occurs when a LabJack that was opened is no longer connected to the system.
// These errors aren't actually generated by the UD, but could be handy in your code to indicate an event as an error code without
// conflicting with LabJack error codes.
const LJ_ERROR LJE_DISCONNECT = 2000;
const LJ_ERROR LJE_RECONNECT = 2001;
// and an area for your own codes. This area won't ever be used for LabJack codes.
const LJ_ERROR LJE_MIN_USER_ERROR = 3000;
const LJ_ERROR LJE_MAX_USER_ERROR = 3999;
// Warning are negative
const LJ_ERROR LJE_DEVICE_NOT_CALIBRATED = -1; // Defaults used instead
const LJ_ERROR LJE_UNABLE_TO_READ_CALDATA = -2; // Defaults used instead
/* Version History:
2.02: ain_binary fixed for non-streaming.
Adjusted for new streaming usb firmware (64-byte packets).
New streaming errors- stop the stream and error is returned with next GetData.
Fixed resolution setting while streaming (was fixed to 12, now follows poll setting).
2.03: Added callback option for streaming.
2.04: Changed warnings to be negative.
Renamed POWER_LEVEL to COMM_POWER_LEVEL.
2.05: Updated timer/counter stuff. Added CounterReset, TimerClockDivisor.
2.06: Fixed problem when unplugging USB UE9 and plugging it into a different USB port.
Renamed LJ_chCOUNTERTIMER_CLOCK to LJ_chTIMER_CLOCK_CONFIG.
2.08: Fixed two UE9 USB unplug issue.
Driver now uses high temp calibration for Control power level zero.
Added new timer modes to header.
Fixed LJ_tcSYS constant in header.
2.09: New timer constants for new modes.
Timer/counter update bits auto-setting updated.
put_counter_reset will execute with the next go, not only with the next read.
2.10: Timer/counter update bits auto-setting updated again.
Fixed MIO bits as outputs.
listall().
Fixed control power level and reset source.
Added ioDIGITAL_PORT_IN and ioDIGITAL_PORT_OUT.
2.11: Fixed problem with ListAll when performed without prior opening of devices.
2.12: Added initial raw U3 support.
2.13: Fixed issues with streaming backlog and applying cals to extended channels.
2.14: Fixed issue with U3 raw support.
2.15: Fixed driver issue with stream clock output and stream external triggering.
2.16: Fixed problem with listall after changing local id.
2.17: Fixed issues with streaming backlog and applying cals to extended channels.
Fixed problem with usb reset.
Added timer mode 6 to header file.
2.18: Fixed issue with rollover on counter/timer.
Fixed reset issues.
2.21: UE9 changed to use feedbackalt instead of feedback. Allows for multiple internal
channels to be called from same call to feedback.
Fixed internal channel numbers 14/128 and 15/136 and extended channels to return
proper values.
2.22: Fixed problem with ioGET_TIMER when passed as a string.
Added support for make unlimited number of requests for analog input channels for a
single call to a go function.
2.23:
2.24: Fixed bug sometimes causing errors when a pointer was passed into the Raw io
functions that caused a communication error.
2.25: Improved U3 support.
2.26: Fixed U3 bugs with timer/counter values, DAC rounding and set analog enabled port functions.
2.46: Various U3 fixes and support added.
2.47: Fixed threading issue.
2.48: Added LJ_ioPUT_WAIT.
2.56: Fixed bug with EAIN.
2.57: Added Thermocouple conversion functions.
2.58: Added SWDT functionality for UE9 (BETA).
2.59: Fixed bug causing some U3 timer values to report incorrectly.
Added support for OEMs to change USB string descriptors on the U3.
2.60: Added beta support for timer values for U3s with hardware version >= 1.21.
2.61: Fixed bug causing U3 streaming to sometimes hang.
2.62: Added ability to open devices over USB using the serial number.
2.63: Added new stream error codes and fixed bug with opening multiple U3s.
2.64: Fixed bug when streaming with differential channels on U3.
2.65: Improved eAin to work properly with special all special channels.
2.66: LJ_chSTREAM_ENABLE_AUTORECOVER renamed to LJ_chSTREAM_DISABLE_AUTORECOVERY.
2.67: Fixed bug with eTCConfig and eTCValues on U3.
2.68: Added internal function for factory use.
2.69: Added Ethernet support for ListAll() for UE9.
2.70: Added I2C support for U3 and UE9.
2.72: Fixed problem with using trigger mode when streaming.
2.73: Added detection for reads from Timers/Counters that weren't enabled on UE9.
2.74: Fixed bug that sometimes occurs when requesting version numbers.
2.75: Fixed issue with reopening U3 after a device reset.
2.76: Fixed bug with the proper range not always being used when streaming on a UE9.
Fixed bug with UE9 Ethernet ListAll() returning wrong values for IP addresses.
2.77: Fixed bug with special channel readings while streaming.
Added Asynch support for U3.
2.78: Fixed bug when doing SPI communication with an odd number of bytes.
2.79: LJ_chI2C_WRITE_READ support.
3.00: Added support for U3-HV and U3-LV.
3.01: Fixed bug with U3-HV applying wrong calibration constants when streaming.
3.02: Fixed bugs with U3-HV and U3-LV and a delay with StopStream.
3.03: Added initial support for U6.
3.04: Fixed bug with Asynch communication on U3-HVs and U3-LVs.
3.05: Fixed calibration bug with eAIN on the U3-HV and U3-LV.
3.06: Fixed bug with SWDT functionality for U3.
3.10: Added support for new USB driver that works with 64-bit OS versions.
3.11: Fixed a memory leak when devices were kept open via USB.
3.12: Fixed various U6 bugs.
3.13: Added LJE_DEVICE_ALREADY_OPEN error to occur when another program/process has the
LabJack open.
3.14: Various minor bug fixes.
3.15: Added full support for Asynch communication on the U6.
3.16: Fixed bug causing a delay when the LabJackUD driver was unloaded in a program.
3.17: Added support for SWDT settings for initial roll time and strict mode.
3.18: Fixed a bug with negative timer values when using ETCConfig with LJ_tmQUAD on the
U3 and U6.
Fixed bug causing a delay when stream on U3/U6 was stopped.
3.19: Fixed bug that caused LJ_ioPUT_TIMER_VALUE to corrupt other results when done in
the same Go or GoOne call.
3.22: Fixed bug in the U6 and U3 that caused excessive delays when com buffer started to fill.
3.23: Added GetThreadID function.
3.26: Fixed bug with U6 reading channels 200-224 not returning proper values.
3.27: Fixed bug with setting calibration constants for LJTickDAC.
3.28: Fixed bug with U3s reading internal temperature using LJ_ioGET_AIN_DIFF.
Added LJ_ctETHERNET_DATA_ONLY support.
3.32: Various bug fixes.
3.38: Added AddRequestPtr, ePutPtr and LJ_ioSET_STREAM_CALLBACK_PTR for better
64-bit compatibility.
3.40: Added LJ_chSTREAM_COMMUNICATION_TIMEOUT support for U3/U6.
3.41: Fixed compatibility for Ptr functions and raw read/write support.
3.42: Fixed error in values of streaming extended channels on U6.
3.43: Fixed bug with eAin high resolution readings on Pro devices.
Fixed bug with IC2 and *Ptr functions.
3.44: Changed eAddGoGet() to return LJE_COMMAND_LIST_ERROR if an error is detected.
Error arrays are also defaulted to zero.
3.45: Fixed a bug which would sometimes cause a critcal error if the LabJackUD.dll was
unloaded after streaming.
3.46: Updated internal reconnect routine to help prevent deadlocks.
Fixed a bug when disabling UE9 DACs.
Added the ability to set multiple timer values in a single Go/GoOne call for the U6.
Updated LJ_chASYNCH_TX's result so the Value is the number of bytes in the RX buffer.
Fixed LJ_chCAL_CONSTANTS, LJ_chUSER_MEM, LJ_chUSB_STRINGS and LJ_ioSPI_COMMUNICATION
functionality when using Array and Ptr functions.
Fixed writing calibration constants, LJ_chCAL_CONSTANTS, for the U3 and U6.
Fixed eTCValues U6 bug.
*/
// Depreciated constants:
const long LJ_ioANALOG_INPUT = 10;
const long LJ_ioANALOG_OUTPUT = 20; // UE9 + U3
const long LJ_ioDIGITAL_BIT_IN = 30; // UE9 + U3
const long LJ_ioDIGITAL_PORT_IN = 35; // UE9 + U3
const long LJ_ioDIGITAL_BIT_OUT = 40; // UE9 + U3
const long LJ_ioDIGITAL_PORT_OUT = 45; // UE9 + U3
const long LJ_ioCOUNTER = 50; // UE9 + U3
const long LJ_ioTIMER = 60; // UE9 + U3
const long LJ_ioPUT_COUNTER_MODE = 2010; // UE9
const long LJ_ioGET_COUNTER_MODE = 2011; // UE9
const long LJ_ioGET_TIMER_VALUE = 2007; // UE9
const long LJ_ioCYCLE_PORT = 102; // UE9
const long LJ_chTIMER_CLOCK_CONFIG = 1001; // UE9 + U3
const long LJ_ioPUT_CAL_CONSTANTS = 400;
const long LJ_ioGET_CAL_CONSTANTS = 401;
const long LJ_ioPUT_USER_MEM = 402;
const long LJ_ioGET_USER_MEM = 403;
const long LJ_ioPUT_USB_STRINGS = 404;
const long LJ_ioGET_USB_STRINGS = 405;
const long LJ_ioSHT_DATA_CHANNEL = 501; // UE9 + U3
const long LJ_ioSHT_CLOCK_CHANNEL = 502; // UE9 + U3
const long LJ_chI2C_ADDRESS = 5108; // UE9 + U3
const long LJ_chASYNCH_CONFIG = 5116; // UE9 + U3
const long LJ_rgUNIP500V = 110; // 0V to +0.500V
const long LJ_ioENABLE_POS_PULLDOWN = 2018; // U6
const long LJ_ioENABLE_NEG_PULLDOWN = 2019; // U6
const long LJ_rgAUTO = 0;
const long LJ_chSWDT_UDPATE_DIOA = 5205;
#ifdef __cplusplus
} // extern C
#endif
#endif
| 60,335 | C | 57.921875 | 231 | 0.732195 |
adegirmenci/HBL-ICEbot/LabJackWidget/LabJackLibs/LabJackM.h | /**
* Name: LabJackM.h
* Desc: Header file describing C-style exposed
* API functions for the LabJackM Library
* Auth: LabJack Corp.
**/
#ifndef LAB_JACK_M_HEADER
#define LAB_JACK_M_HEADER
#define LJM_VERSION 1.0806
// Format: xx.yyzz
// xx is the major version (left of the decimal).
// yy is the minor version (the two places to the right of the decimal).
// zz is the revision version (the two places to the right of the minor
// version).
/******************************************************************************
* How To Use This Library:
*
* See the LJM User's Guide: labjack.com/support/ljm/users-guide
*
* Check out the example files for examples of workflow
*
* To write/read other Modbus addresses, check out labjack.com/support/modbus
*
*****************************************************************************/
#define LJM_ERROR_CODE static const int
#ifdef __cplusplus
extern "C" {
#endif
#ifdef WIN32
#define LJM_ERROR_RETURN int __stdcall
#define LJM_VOID_RETURN void __stdcall
#define LJM_ERROR_STRING const char * __stdcall
#define LJM_DOUBLE_RETURN double __stdcall
#else
#define LJM_ERROR_RETURN int
#define LJM_VOID_RETURN void
#define LJM_ERROR_STRING const char *
#define LJM_DOUBLE_RETURN double
#endif
/*************
* Constants *
*************/
// Read/Write direction constants:
static const int LJM_READ = 0;
static const int LJM_WRITE = 1;
// Data Types:
// These do automatic endianness conversion, if needed by the local machine's
// processor.
static const int LJM_UINT16 = 0; // C type of unsigned short
static const int LJM_UINT32 = 1; // C type of unsigned int
static const int LJM_INT32 = 2; // C type of int
static const int LJM_FLOAT32 = 3; // C type of float
// Advanced users data types:
// These do not do any endianness conversion.
static const int LJM_BYTE = 99; // Contiguous bytes. If the number of LJM_BYTEs is
// odd, the last, (least significant) byte is 0x00.
// For example, for 3 LJM_BYTES of values
// [0x01, 0x02, 0x03], LJM sends the contiguous byte
// array [0x01, 0x02, 0x03, 0x00]
static const int LJM_STRING = 98; // Same as LJM_BYTE, but LJM automatically appends
// a null-terminator.
static const unsigned int LJM_STRING_MAX_SIZE = 49;
// Max LJM_STRING size not including the automatic null-terminator
// Max LJM_STRING size with the null-terminator
enum { LJM_STRING_ALLOCATION_SIZE = 50 };
// LJM_NamesToAddresses uses this when a register name is not found
static const int LJM_INVALID_NAME_ADDRESS = -1;
enum { LJM_MAX_NAME_SIZE = 256 };
// 18 = 6 * 2 (number of byte chars) + 5 (number of colons) + 1 (null-terminator)
enum { LJM_MAC_STRING_SIZE = 18 };
// 16 is INET_ADDRSTRLEN
enum { LJM_IPv4_STRING_SIZE = 16 };
static const int LJM_BYTES_PER_REGISTER = 2;
// Device types:
static const int LJM_dtANY = 0;
static const int LJM_dtT7 = 7;
static const int LJM_dtDIGIT = 200;
// Connection types:
static const int LJM_ctANY = 0;
static const int LJM_ctUSB = 1;
static const int LJM_ctTCP = 2;
static const int LJM_ctETHERNET = 3;
static const int LJM_ctWIFI = 4;
// TCP/Ethernet constants:
static const int LJM_NO_IP_ADDRESS = 0;
static const int LJM_NO_PORT = 0;
static const int LJM_DEFAULT_PORT = 502;
// Identifier types:
static const char * const LJM_DEMO_MODE = "-2";
static const int LJM_idANY = 0;
// LJM_AddressesToMBFB Constants
enum { LJM_DEFAULT_FEEDBACK_ALLOCATION_SIZE = 62 };
static const int LJM_USE_DEFAULT_MAXBYTESPERMBFB = 0;
// LJM_MBFBComm Constants;
static const int LJM_DEFAULT_UNIT_ID = 1;
// LJM_ListAll Constants
enum { LJM_LIST_ALL_SIZE = 128 };
// Please note that some devices must append 2 bytes to certain packets.
// Please check the docs for the device you are using.
static const int LJM_MAX_USB_PACKET_NUM_BYTES = 64;
static const int LJM_MAX_TCP_PACKET_NUM_BYTES_T7 = 1040; // Deprecated
static const int LJM_MAX_ETHERNET_PACKET_NUM_BYTES_T7 = 1040;
static const int LJM_MAX_WIFI_PACKET_NUM_BYTES_T7 = 500;
// Timeout Constants. Times in milliseconds.
static const int LJM_NO_TIMEOUT = 0;
static const int LJM_DEFAULT_USB_SEND_RECEIVE_TIMEOUT_MS = 2600;
static const int LJM_DEFAULT_ETHERNET_OPEN_TIMEOUT_MS = 1000;
static const int LJM_DEFAULT_ETHERNET_SEND_RECEIVE_TIMEOUT_MS = 2600;
static const int LJM_DEFAULT_WIFI_OPEN_TIMEOUT_MS = 1000;
static const int LJM_DEFAULT_WIFI_SEND_RECEIVE_TIMEOUT_MS = 4000;
// Stream Constants
static const int LJM_DUMMY_VALUE = -9999;
static const int LJM_SCAN_NOT_READ = -8888;
static const int LJM_GND = 199;
/*****************************************************************************
* Return Values *
* Success: *
* Constant: LJME_NOERROR *
* Description: The function executed without error. *
* Range: 0 *
* *
* Warnings: *
* Prefix: LJME_ *
* Description: Some or all outputs might be valid. *
* Range: 200-399 *
* *
* Modbus Errors: *
* Prefix: LJME_MBE *
* Description: Errors corresponding to official Modbus errors which are *
* returned from the device. *
* Note: To find the original Modbus error in base 10, subtract 1200. *
* Ranges: 1200-1216 *
* *
* Library Errors: *
* Prefix: LJME_ *
* Description: Errors where all outputs are null, invalid, 0, or 9999. *
* Range: 1220-1399 *
* *
* Device Errors: *
* Description: Errors returned from the firmware on the device. *
* Range: 2000-2999 *
* *
* User Area: *
* Description: Errors defined by users. *
* Range: 3900-3999 *
* */
// Success
LJM_ERROR_CODE LJME_NOERROR = 0;
// Warnings:
LJM_ERROR_CODE LJME_WARNINGS_BEGIN = 200;
LJM_ERROR_CODE LJME_WARNINGS_END = 399;
LJM_ERROR_CODE LJME_FRAMES_OMITTED_DUE_TO_PACKET_SIZE = 201;
// Functions:
// LJM_AddressesToMBFB:
// Problem: This indicates that the length (in bytes) of the Feedback
// command being created was greater than the value passed as
// MaxBytesPerMBFB. As a result, the command returned is a valid
// Feedback command that includes some of the frames originally
// specified, but not all of them. You can check the NumFrames
// pointer to find out how many frames were included.
// Solutions:
// 1) Pass a larger value for MaxBytesPerMBFB and make sure
// aMBFBCommand has memory allocated of size MaxBytesPerMBFB.
// The default size for MaxBytesPerMBFB is 64.
// 2) Split the command into multiple commands.
// Any other function that creates a Feedback command:
// Problem: The Feedback command being created was too large for
// the device to handle on this connection type.
// Solution: Split the command into multiple commands.
LJM_ERROR_CODE LJME_DEBUG_LOG_FAILURE = 202;
LJM_ERROR_CODE LJME_USING_DEFAULT_CALIBRATION = 203;
// Problem: LJM has detected the device has one or more invalid calibration
// constants and is using the default calibration constants. Readings may
// inaccurate.
// Solution: Contact LabJack support.
LJM_ERROR_CODE LJME_DEBUG_LOG_FILE_NOT_OPEN = 204;
// Modbus Errors:
LJM_ERROR_CODE LJME_MODBUS_ERRORS_BEGIN = 1200;
LJM_ERROR_CODE LJME_MODBUS_ERRORS_END = 1216;
LJM_ERROR_CODE LJME_MBE1_ILLEGAL_FUNCTION = 1201;
LJM_ERROR_CODE LJME_MBE2_ILLEGAL_DATA_ADDRESS = 1202;
LJM_ERROR_CODE LJME_MBE3_ILLEGAL_DATA_VALUE = 1203;
LJM_ERROR_CODE LJME_MBE4_SLAVE_DEVICE_FAILURE = 1204;
LJM_ERROR_CODE LJME_MBE5_ACKNOWLEDGE = 1205;
LJM_ERROR_CODE LJME_MBE6_SLAVE_DEVICE_BUSY = 1206;
LJM_ERROR_CODE LJME_MBE8_MEMORY_PARITY_ERROR = 1208;
LJM_ERROR_CODE LJME_MBE10_GATEWAY_PATH_UNAVAILABLE = 1210;
LJM_ERROR_CODE LJME_MBE11_GATEWAY_TARGET_NO_RESPONSE = 1211;
// Library Errors:
LJM_ERROR_CODE LJME_LIBRARY_ERRORS_BEGIN = 1220;
LJM_ERROR_CODE LJME_LIBRARY_ERRORS_END = 1399;
LJM_ERROR_CODE LJME_UNKNOWN_ERROR = 1221;
LJM_ERROR_CODE LJME_INVALID_DEVICE_TYPE = 1222;
LJM_ERROR_CODE LJME_INVALID_HANDLE = 1223;
LJM_ERROR_CODE LJME_DEVICE_NOT_OPEN = 1224;
LJM_ERROR_CODE LJME_STREAM_NOT_INITIALIZED = 1225;
LJM_ERROR_CODE LJME_DEVICE_DISCONNECTED = 1226;
LJM_ERROR_CODE LJME_DEVICE_NOT_FOUND = 1227;
LJM_ERROR_CODE LJME_DEVICE_ALREADY_OPEN = 1229;
LJM_ERROR_CODE LJME_COULD_NOT_CLAIM_DEVICE = 1230;
LJM_ERROR_CODE LJME_CANNOT_CONNECT = 1231;
LJM_ERROR_CODE LJME_SOCKET_LEVEL_ERROR = 1233;
LJM_ERROR_CODE LJME_CANNOT_OPEN_DEVICE = 1236;
LJM_ERROR_CODE LJME_CANNOT_DISCONNECT = 1237;
LJM_ERROR_CODE LJME_WINSOCK_FAILURE = 1238;
LJM_ERROR_CODE LJME_RECONNECT_FAILED = 1239;
LJM_ERROR_CODE LJME_U3_CANNOT_BE_OPENED_BY_LJM = 1243;
LJM_ERROR_CODE LJME_U6_CANNOT_BE_OPENED_BY_LJM = 1246;
LJM_ERROR_CODE LJME_UE9_CANNOT_BE_OPENED_BY_LJM = 1249;
LJM_ERROR_CODE LJME_INVALID_ADDRESS = 1250;
LJM_ERROR_CODE LJME_INVALID_CONNECTION_TYPE = 1251;
LJM_ERROR_CODE LJME_INVALID_DIRECTION = 1252;
LJM_ERROR_CODE LJME_INVALID_FUNCTION = 1253;
// Function: LJM_MBFBComm
// Problem: The aMBFB buffer passed as an input parameter
// did not have a function number corresponding to Feedback.
// Solution: Make sure the 8th byte of your buffer is 76 (base 10).
// (For example, aMBFB[7] == 76 should evaluate to true.)
LJM_ERROR_CODE LJME_INVALID_NUM_REGISTERS = 1254;
LJM_ERROR_CODE LJME_INVALID_PARAMETER = 1255;
LJM_ERROR_CODE LJME_INVALID_PROTOCOL_ID = 1256;
// Problem: The Protocol ID was not in the proper range.
LJM_ERROR_CODE LJME_INVALID_TRANSACTION_ID = 1257;
// Problem: The Transaction ID was not in the proper range.
LJM_ERROR_CODE LJME_INVALID_VALUE_TYPE = 1259;
LJM_ERROR_CODE LJME_MEMORY_ALLOCATION_FAILURE = 1260;
// Problem: A memory allocation attempt has failed, probably due to a
// lack of available memory.
LJM_ERROR_CODE LJME_NO_COMMAND_BYTES_SENT = 1261;
// Problem: No bytes could be sent to the device.
// Possibilities:
// * The device was previously connected, but was suddenly
// disconnected.
LJM_ERROR_CODE LJME_INCORRECT_NUM_COMMAND_BYTES_SENT = 1262;
// Problem: The expected number of bytes could not be sent to the device.
// Possibilities:
// * The device was disconnected while bytes were being sent.
LJM_ERROR_CODE LJME_NO_RESPONSE_BYTES_RECEIVED = 1263;
// Problem: No bytes could be received from the device.
// Possibilities:
// * The device was previously connected, but was suddenly
// disconnected.
// * The timeout length was too short for the device to respond.
LJM_ERROR_CODE LJME_INCORRECT_NUM_RESPONSE_BYTES_RECEIVED = 1264;
// Problem: The expected number of bytes could not be received from the
// device.
// Possibilities:
// * The device was previously connected, but was suddenly
// disconnected.
// * The device needs a firmware update.
LJM_ERROR_CODE LJME_MIXED_FORMAT_IP_ADDRESS = 1265;
// Functions: LJM_OpenS and LJM_Open
// Problem: The string passed as an identifier contained an IP address
// that was ambiguous.
// Solution: Make sure the IP address is in either decimal format
// (i.e. "192.168.1.25") or hex format (i.e. "0xC0.A8.0.19").
LJM_ERROR_CODE LJME_UNKNOWN_IDENTIFIER = 1266;
LJM_ERROR_CODE LJME_NOT_IMPLEMENTED = 1267;
LJM_ERROR_CODE LJME_INVALID_INDEX = 1268;
// Problem: An error internal to the LabJackM Library has occurred.
// Solution: Please report this error to LabJack.
LJM_ERROR_CODE LJME_INVALID_LENGTH = 1269;
LJM_ERROR_CODE LJME_ERROR_BIT_SET = 1270;
LJM_ERROR_CODE LJME_INVALID_MAXBYTESPERMBFB = 1271;
// Functions:
// LJM_AddressesToMBFB:
// Problem: This indicates the MaxBytesPerMBFB value was
// insufficient for any Feedback command.
// Solution: Pass a larger value for MaxBytesPerMBFB and make sure
// aMBFBCommand has memory allocated of size MaxBytesPerMBFB.
// The default size for MaxBytesPerMBFB is 64.
LJM_ERROR_CODE LJME_NULL_POINTER = 1272;
// Problem: The Library has received an invalid pointer.
// Solution: Make sure that any functions that have pointers in their
// parameter list are valid pointers that point to allocated memory.
LJM_ERROR_CODE LJME_NULL_OBJ = 1273;
// Functions:
// LJM_OpenS and LJM_Open:
// Problem: The Library failed to parse the input parameters.
// Solution: Check the validity of your inputs and if the problem
// persists, please contact LabJack support.
LJM_ERROR_CODE LJME_RESERVED_NAME = 1274;
// LJM_OpenS and LJM_Open:
// Problem: The string passed as Identifier was a reserved name.
// Solution: Use a different name for your device. You can also connect
// by passing the device's serial number or IP address, if
// applicable.
LJM_ERROR_CODE LJME_UNPARSABLE_DEVICE_TYPE = 1275;
// LJM_OpenS:
// Problem: This Library could not parse the DeviceType.
// Solution: Check the LJM_OpenS documentation and make sure the
// DeviceType does not contain any unusual characters.
LJM_ERROR_CODE LJME_UNPARSABLE_CONNECTION_TYPE = 1276;
// LJM_OpenS:
// Problem: This Library could not parse the ConnectionType.
// Solution: Check the LJM_OpenS documentation and make sure the
// ConnectionType does not contain any unusual characters.
LJM_ERROR_CODE LJME_UNPARSABLE_IDENTIFIER = 1277;
// LJM_OpenS and LJM_Open:
// Problem: This Library could not parse the Identifier.
// Solution: Check the LJM_OpenS documentation and make sure the
// Identifier does not contain any unusual characters.
LJM_ERROR_CODE LJME_PACKET_SIZE_TOO_LARGE = 1278;
// Problems: The packet being sent to the device contained too many bytes.
// Note: Some LabJack devices need two bytes appended to any Modbus packets
// sent to a device. The packet size plus these two appended bytes
// could have exceeded the packet size limit.
// Solution: Send a smaller packet, i.e. break your packet up into multiple
// packets.
LJM_ERROR_CODE LJME_TRANSACTION_ID_ERR = 1279;
// Problem: LJM received an unexpected Modbus Transaction ID.
LJM_ERROR_CODE LJME_PROTOCOL_ID_ERR = 1280;
// Problem: LJM received an unexpected Modbus Protocol ID.
LJM_ERROR_CODE LJME_LENGTH_ERR = 1281;
// Problem: LJM received a packet with an unexpected Modbus Length.
LJM_ERROR_CODE LJME_UNIT_ID_ERR = 1282;
// Problem: LJM received a packet with an unexpected Modbus Unit ID.
LJM_ERROR_CODE LJME_FUNCTION_ERR = 1283;
// Problem: LJM received a packet with an unexpected Modbus Function.
LJM_ERROR_CODE LJME_STARTING_REG_ERR = 1284;
// Problem: LJM received a packet with an unexpected Modbus address.
LJM_ERROR_CODE LJME_NUM_REGS_ERR = 1285;
// Problem: LJM received a packet with an unexpected Modbus number of
// registers.
LJM_ERROR_CODE LJME_NUM_BYTES_ERR = 1286;
// Problem: LJM received a packet with an unexpected Modbus number of bytes.
LJM_ERROR_CODE LJME_CONFIG_FILE_NOT_FOUND = 1289;
LJM_ERROR_CODE LJME_CONFIG_PARSING_ERROR = 1290;
LJM_ERROR_CODE LJME_INVALID_NUM_VALUES = 1291;
LJM_ERROR_CODE LJME_CONSTANTS_FILE_NOT_FOUND = 1292;
LJM_ERROR_CODE LJME_INVALID_CONSTANTS_FILE = 1293;
LJM_ERROR_CODE LJME_INVALID_NAME = 1294;
// Problem: LJM received a name that was not found/matched in the constants
// file or was otherwise an invalid name.
// Solution: Use LJM_ErrorToString to find the invalid name(s).
LJM_ERROR_CODE LJME_OVERSPECIFIED_PORT = 1296;
// Functions: LJM_Open, LJM_OpenS
// Problem: LJM received an Identifier that specified a port/pipe, but
// connection type was not specified.
LJM_ERROR_CODE LJME_INTENT_NOT_READY = 1297;
// Please contact LabJack support if the problem is not apparent.
LJM_ERROR_CODE LJME_ATTR_LOAD_COMM_FAILURE = 1298;
/**
* Name: LJME_ATTR_LOAD_COMM_FAILURE
* Functions: LJM_Open, LJM_OpenS
* Desc: Indicates that a device was found and opened, but communication with
* that device failed, so the device was closed. The handle returned is
* not a valid handle. This communication failure can mean the device is
* in a non-responsive state or has out-of-date firmware.
* Solutions: a) Power your device off, then back on, i.e. unplug it then plug
* it back in.
* b) Make sure your device(s) have up-to-date firmware.
**/
LJM_ERROR_CODE LJME_INVALID_CONFIG_NAME = 1299;
// Functions: LJM_WriteLibraryConfigS, LJM_WriteLibraryConfigStringS,
// LJM_ReadLibraryConfigS, LJM_ReadLibraryConfigStringS
// Problem: An unknown string has been passed in as Parameter.
// Solution: Please check the documentation in this header file for the
// configuration parameter you are trying to read or write. Not all
// config parameters can be read, nor can all config parameters be
// written.
LJM_ERROR_CODE LJME_ERROR_RETRIEVAL_FAILURE = 1300;
// Problem: A device has reported an error and LJM failed to to retrieve the
// error code from the device.
// Solution: Please make sure the device has current firmware and that this
// is a current of LJM. If the problem persists, please contact LabJack
// support.
LJM_ERROR_CODE LJME_LJM_BUFFER_FULL = 1301;
LJM_ERROR_CODE LJME_COULD_NOT_START_STREAM = 1302;
LJM_ERROR_CODE LJME_STREAM_NOT_RUNNING = 1303;
LJM_ERROR_CODE LJME_UNABLE_TO_STOP_STREAM = 1304;
LJM_ERROR_CODE LJME_INVALID_VALUE = 1305;
LJM_ERROR_CODE LJME_SYNCHRONIZATION_TIMEOUT = 1306;
LJM_ERROR_CODE LJME_OLD_FIRMWARE = 1307;
LJM_ERROR_CODE LJME_CANNOT_READ_OUT_ONLY_STREAM = 1308;
LJM_ERROR_CODE LJME_NO_SCANS_RETURNED = 1309;
LJM_ERROR_CODE LJME_TEMPERATURE_OUT_OF_RANGE = 1310;
LJM_ERROR_CODE LJME_VOLTAGE_OUT_OF_RANGE = 1311;
/*******************************
* Device Management Functions *
*******************************/
/**
* Name: LJM_ListAll, LJM_ListAllS
* Desc: Scans for LabJack devices, returning arrays describing the devices
* found, allowing LJM_dtANY and LJM_ctANY to be used
* Para: DeviceType, filters which devices will be returned (LJM_dtT7,
* LJM_dtDIGIT, etc.). LJM_dtANY is allowed.
* ConnectionType, filters by connection type (LJM_ctUSB or LJM_ctTCP).
* LJM_ctANY is allowed.
* NumFound, a pointer that returns the number of devices found
* aDeviceTypes, an array that must be preallocated to size
* LJM_LIST_ALL_SIZE, returns the device type for each of the
* NumFound devices
* aConnectionTypes, an array that must be preallocated to size
* LJM_LIST_ALL_SIZE, returns the connect type for each of the
* NumFound devices
* aSerialNumbers, an array that must be preallocated to size
* LJM_LIST_ALL_SIZE, returns the serial number for each of the
* NumFound devices
* aIPAddresses, an array that must be preallocated to size
* LJM_LIST_ALL_SIZE, returns the IPAddresses for each of the
* NumFound devices, but only if ConnectionType is TCP-based. For
* each corresponding device for which aConnectionTypes[i] is not
* TCP-based, aIPAddresses[i] will be LJM_NO_IP_ADDRESS.
* Note: These functions only show what devices could be opened. To actually
* open a device, use LJM_Open or LJM_OpenS.
* Note: These functions will ignore NULL pointers, except for NumFound.
**/
LJM_ERROR_RETURN LJM_ListAll(int DeviceType, int ConnectionType,
int * NumFound, int * aDeviceTypes, int * aConnectionTypes,
int * aSerialNumbers, int * aIPAddresses);
LJM_ERROR_RETURN LJM_ListAllS(const char * DeviceType, const char * ConnectionType,
int * NumFound, int * aDeviceTypes, int * aConnectionTypes,
int * aSerialNumbers, int * aIPAddresses);
/**
* Name: LJM_ListAllExtended
* Desc: Advanced version of LJM_ListAll that performs an additional query of
* arbitrary registers on the device.
* Para: DeviceType, filters which devices will be returned (LJM_dtT7,
* LJM_dtDIGIT, etc.). LJM_dtANY is allowed.
* ConnectionType, filters by connection type (LJM_ctUSB or LJM_ctTCP).
* LJM_ctANY is allowed.
* NumAddresses, the number of addresses to query. Also the size of
* aAddresses and aNumRegs.
* aAddresses, the addresses to query for each device that is found.
* aNumRegs, the number of registers to query for each address.
* Each aNumRegs[i] corresponds to aAddresses[i].
* MaxNumFound, the maximum number of devices to find. Also the size of
* aDeviceTypes, aConnectionTypes, aSerialNumbers, and aIPAddresses.
* NumFound, a pointer that returns the number of devices found
* aDeviceTypes, an array that must be preallocated to size
* MaxNumFound, returns the device type for each of the
* NumFound devices
* aConnectionTypes, an array that must be preallocated to size
* MaxNumFound, returns the connect type for each of the
* NumFound devices
* aSerialNumbers, an array that must be preallocated to size
* MaxNumFound, returns the serial number for each of the
* NumFound devices
* aIPAddresses, an array that must be preallocated to size
* MaxNumFound, returns the IPAddresses for each of the
* NumFound devices, but only if ConnectionType is TCP-based. For
* each corresponding device for which aConnectionTypes[i] is not
* TCP-based, aIPAddresses[i] will be LJM_NO_IP_ADDRESS.
* aBytes, an array that must be preallocated to size:
* MaxNumFound * <the sum of aNumRegs> * LJM_BYTES_PER_REGISTER,
* which will contain the query bytes sequentially. A device
* represented by index i would have an aBytes index of:
* (i * <the sum of aNumRegs> * LJM_BYTES_PER_REGISTER).
* Note: These functions only show what devices could be opened. To actually
* open a device, use LJM_Open or LJM_OpenS.
* Note: These functions will ignore NULL pointers, except for NumFound and
* aBytes.
*
*
* TODO: Define error behavior
*
*
**/
LJM_ERROR_RETURN LJM_ListAllExtended(int DeviceType, int ConnectionType,
int NumAddresses, const int * aAddresses, const int * aNumRegs,
int MaxNumFound, int * NumFound, int * aDeviceTypes, int * aConnectionTypes,
int * aSerialNumbers, int * aIPAddresses, unsigned char * aBytes);
/**
* Name: LJM_OpenS
* Desc: Opens a LabJack device.
* Para: DeviceType, a string containing the type of the device to be connected,
* optionally prepended by "LJM_dt". Possible values include "ANY",
* "T7", and "DIGIT".
* ConnectionType, a string containing the type of the connection desired,
* optionally prepended by "LJM_ct". Possible values include "ANY",
* "USB", "TCP", "ETHERNET", and "WIFI".
* Identifier, a string identifying the device to be connected or
* "LJM_idANY"/"ANY". This can be a serial number, IP address, or
* device name. Device names may not contain periods.
* Handle, the new handle that represents a device connection upon success
* Retr: LJME_NOERROR, if a device was successfully opened.
* LJME_ATTR_LOAD_COMM_FAILURE, if a device was found, but there was a
* communication failure.
* Note: Input parameters are not case-sensitive.
* Note: Empty strings passed to DeviceType, ConnectionType, or Identifier
* indicate the same thing as LJM_dtANY, LJM_ctANY, or LJM_idANY,
* respectively.
**/
LJM_ERROR_RETURN LJM_OpenS(const char * DeviceType, const char * ConnectionType,
const char * Identifier, int * Handle);
/**
* Name: LJM_Open
* Desc: See the description for LJM_OpenS. The only difference between
* LJM_Open and LJM_OpenS is the first two parameters.
* Para: DeviceType, a constant corresponding to the type of device to open,
* such as LJM_dtT7, or LJM_dtANY.
* ConnectionType, a constant corresponding to the type of connection to
* open, such as LJM_ctUSB, or LJM_ctANY.
**/
LJM_ERROR_RETURN LJM_Open(int DeviceType, int ConnectionType,
const char * Identifier, int * Handle);
/**
* Name: LJM_GetHandleInfo
* Desc: Takes a device handle as input and returns details about that device.
* Para: Handle, a valid handle to an open device.
* DeviceType, the output device type corresponding to a constant such as
* LJM_dtT7.
* ConnectionType, the output device type corresponding to a constant
* such as LJM_ctUSB.
* SerialNumber, the output serial number of the device.
* IPAddress, the output integer representation of the device's IP
* address when ConnectionType is TCP-based. If ConnectionType is not
* TCP-based, this will be LJM_NO_IP_ADDRESS. Note that this can be
* converted to a human-readable string with the LJM_NumberToIP
* function.
* Port, the output port if the device connection is TCP-based, or the pipe
* if the device connection is USB-based.
* MaxBytesPerMB, the maximum packet size in number of bytes that can be
* sent to or received from this device. Note that this can change
* depending on connection type and device type.
* Note: This function returns device information loaded during an open call
* and therefore does not initiate communications with the device. In
* other words, it is fast but will not represent changes to serial
* number or IP address since the device was opened.
* Warn: This function ignores null pointers
**/
LJM_ERROR_RETURN LJM_GetHandleInfo(int Handle, int * DeviceType,
int * ConnectionType, int * SerialNumber, int * IPAddress, int * Port,
int * MaxBytesPerMB);
/**
* Name: LJM_Close
* Desc: Closes the connection to the device.
* Para: Handle, a valid handle to an open device.
**/
LJM_ERROR_RETURN LJM_Close(int Handle);
/**
* Name: LJM_CloseAll
* Desc: Closes all connections to all devices
**/
LJM_ERROR_RETURN LJM_CloseAll();
/******************************
* Easy Read/Write Functions *
******************************/
// Easy Functions: All type, either reading or writing, single address
/**
* Name: LJM_eReadAddress, LJM_eReadName
* LJM_eWriteAddress, LJM_eWriteName
* Desc: Creates and sends a Modbus operation, then receives and parses the
* response.
* Para: Handle, a valid handle to an open device
* (Address), an address to read/write
* (Type), the type corresponding to Address
* (Name), a name to read/write
* Value, a value to write or read
* Note: These functions may take liberties in deciding what kind of Modbus
* operation to create. For more control of what kind of packets may be
* sent/received, please see the LJM_WriteLibraryConfigS function.
**/
LJM_ERROR_RETURN LJM_eWriteAddress(int Handle, int Address, int Type, double Value);
LJM_ERROR_RETURN LJM_eReadAddress(int Handle, int Address, int Type, double * Value);
LJM_ERROR_RETURN LJM_eWriteName(int Handle, const char * Name, double Value);
LJM_ERROR_RETURN LJM_eReadName(int Handle, const char * Name, double * Value);
// Easy Functions: All type, either reading or writing, multiple addresses
/**
* Name: LJM_eReadAddresses, LJM_eReadNames
* LJM_eWriteAddresses, LJM_eWriteNames
* Desc: Creates and sends a Modbus operation, then receives and parses the
* response.
* Para: Handle, a valid handle to an open device.
* NumFrames, the total number of reads/writes to perform.
* (aAddresses), an array of size NumFrames of the addresses to
* read/write for each frame.
* (aTypes), an array of size NumFrames of the data types corresponding
* to each address in aAddresses.
* (aNames), an array of size NumFrames of the names to read/write for
* each frame.
* aValues, an array of size NumFrames that represents the values to
* write from or read to.
* ErrorAddress, a pointer to an integer, which in the case of a relevant
* error, gets updated to contain the device-reported address that
* caused an error.
* Note: Reads/writes are compressed into arrays for consecutive addresses that
* line up, based on type. See the LJM_ALLOWS_AUTO_CONDENSE_ADDRESSES
* configuration.
* Note: These functions may take liberties in deciding what kind of Modbus
* operation to create. For more control of what kind of packets may be
* sent/received, please see the LJM_WriteLibraryConfigS function.
**/
LJM_ERROR_RETURN LJM_eReadAddresses(int Handle, int NumFrames,
const int * aAddresses, const int * aTypes, double * aValues,
int * ErrorAddress);
LJM_ERROR_RETURN LJM_eReadNames(int Handle, int NumFrames,
const char ** aNames, double * aValues, int * ErrorAddress);
LJM_ERROR_RETURN LJM_eWriteAddresses(int Handle, int NumFrames,
const int * aAddresses, const int * aTypes, const double * aValues,
int * ErrorAddress);
LJM_ERROR_RETURN LJM_eWriteNames(int Handle, int NumFrames,
const char ** aNames, const double * aValues, int * ErrorAddress);
// Easy Functions: All type, reading and writing, multiple values to one address
/**
* Name: LJM_eReadAddressArray, LJM_eReadNameArray
* LJM_eWriteAddressArray, LJM_eWriteNameArray
* Desc: Performs a Modbus operation to either read or write an array.
* Para: Handle, a valid handle to an open device.
* (Address), the address to read an array from or write an array to.
* (Type), the data type of Address.
* (Name), the register name to read an array from or write an array to.
* NumValues, the size of the array to read or write.
* aValues, an array of size NumValues that represents the values to
* write from or read to.
* ErrorAddress, a pointer to an integer, which in the case of a relevant
* error, gets updated to contain the device-reported address that
* caused an error.
* Note: These functions may take liberties in deciding what kind of Modbus
* operation to create. For more control of what kind of packets may be
* sent/received, please see the LJM_WriteLibraryConfigS function.
**/
LJM_ERROR_RETURN LJM_eReadAddressArray(int Handle, int Address, int Type,
int NumValues, double * aValues, int * ErrorAddress);
LJM_ERROR_RETURN LJM_eReadNameArray(int Handle, const char * Name,
int NumValues, double * aValues, int * ErrorAddress);
LJM_ERROR_RETURN LJM_eWriteAddressArray(int Handle, int Address, int Type,
int NumValues, const double * aValues, int * ErrorAddress);
LJM_ERROR_RETURN LJM_eWriteNameArray(int Handle, const char * Name,
int NumValues, const double * aValues, int * ErrorAddress);
// Easy Functions: All type, reading and writing, multiple addresses with
// multiple values for each
/**
* Name: LJM_eAddresses, LJM_eNames
* Desc: Performs Modbus operations that write/read data.
* Para: Handle, a valid handle to an open device.
* NumFrames, the total number of reads/writes frames to perform.
* (aAddresses), an array of size NumFrames of the addresses to
* read/write for each frame.
* (aTypes), an array of size NumFrames of the data types corresponding
* to each address in aAddresses.
* (aNames), an array of size NumFrames of the names to read/write for
* each frame.
* aWrites, an array of size NumFrames of the direction/access type
* (LJM_READ or LJM_WRITE) for each frame.
* aNumValues, an array of size NumFrames giving the number of values to
* read/write for each frame.
* aValues, an array that represents the values to write or read. The
* size of this array must be the sum of aNumValues.
* ErrorAddress, a pointer to an integer, which in the case of a relevant
* error, gets updated to contain the device-reported address that
* caused an error.
* Note: Reads/writes are compressed into arrays for consecutive addresses that
* line up, based on type. See the LJM_ALLOWS_AUTO_CONDENSE_ADDRESSES
* configuration.
* Note: These functions may take liberties in deciding what kind of Modbus
* operation to create. For more control of what kind of packets may be
* sent/received, please see the LJM_WriteLibraryConfigS function.
**/
LJM_ERROR_RETURN LJM_eAddresses(int Handle, int NumFrames,
const int * aAddresses, const int * aTypes, const int * aWrites,
const int * aNumValues, double * aValues, int * ErrorAddress);
LJM_ERROR_RETURN LJM_eNames(int Handle, int NumFrames, const char ** aNames,
const int * aWrites, const int * aNumValues, double * aValues,
int * ErrorAddress);
/**
* Name: LJM_eReadNameString, LJM_eReadAddressString
* Desc: Reads a 50-byte string from a device.
* Para: Handle, a valid handle to an open device.
* (Name), the name of the registers to read, which must be of type
* LJM_STRING.
* (Address), the address of the registers to read an LJM_STRING from.
* String, A string that is updated to contain the result of the read.
* Must be allocated to size LJM_STRING_ALLOCATION_SIZE or
* greater prior to calling this function.
* Note: This is a convenience function for LJM_eNames/LJM_eAddressess.
* Note: LJM_eReadNameString checks to make sure that Name is in the constants
* file and describes registers that have a data type of LJM_STRING,
* but LJM_eReadAddressString does not perform any data type checking.
**/
LJM_ERROR_RETURN LJM_eReadNameString(int Handle, const char * Name,
char * String);
LJM_ERROR_RETURN LJM_eReadAddressString(int Handle, int Address,
char * String);
/**
* Name: LJM_eWriteNameString, LJM_eWriteAddressString
* Desc: Writes a 50-byte string to a device.
* Para: Handle, a valid handle to an open device.
* (Name), the name of the registers to write to, which must be of type
* LJM_STRING
* (Address), the address of the registers to write an LJM_STRING to
* String, The string to write. Must null-terminate at length
* LJM_STRING_ALLOCATION_SIZE or less.
* Note: This is a convenience function for LJM_eNames/LJM_eAddressess
* Note: LJM_eWriteNameString checks to make sure that Name is in the constants
* file and describes registers that have a data type of LJM_STRING,
* but LJM_eWriteAddressString does not perform any data type checking.
**/
LJM_ERROR_RETURN LJM_eWriteNameString(int Handle, const char * Name,
const char * String);
LJM_ERROR_RETURN LJM_eWriteAddressString(int Handle, int Address,
const char * String);
/*********************
* Stream Functions *
*********************/
/**
* Name: LJM_eStreamStart
* Desc: Initializes a stream object and begins streaming. This includes
* creating a buffer in LJM that collects data from the device.
* Para: Handle, a valid handle to an open device.
* ScansPerRead, Number of scans returned by each call to the
* LJM_eStreamRead function. This is not tied to the maximum packet
* size for the device.
* NumAddresses, The size of aScanList. The number of addresses to scan.
* aScanList, Array of Modbus addresses to collect samples from, per scan.
* ScanRate, intput/output pointer. Sets the desired number of scans per
* second. Upon successful return of this function, gets updated to
* the actual scan rate that the device will scan at.
* Note: Address configuration such as range, resolution, and differential
* voltages are handled by writing to the device.
* Note: Check your device's documentation for which addresses are valid for
* aScanList.
**/
LJM_ERROR_RETURN LJM_eStreamStart(int Handle, int ScansPerRead,
int NumAddresses, const int * aScanList, double * ScanRate);
/**
* Name: LJM_eStreamRead
* Desc: Returns data from an initialized and running LJM stream buffer. Waits
* for data to become available, if necessary.
* Para: Handle, a valid handle to an open device.
* aData, Output data array. Returns all addresses interleaved. Must be
* large enough to hold (ScansPerRead * NumAddresses) values.
* ScansPerRead and NumAddresses are set when stream is set up with
* LJM_eStreamStart. The data returned is removed from the LJM stream
* buffer.
* DeviceScanBacklog, The number of scans left in the device buffer, as
* measured from when data was last collected from the device. This
* should usually be near zero and not growing for healthy streams.
* LJMScanBacklog, The number of scans left in the LJM buffer, as
* measured from after the data returned from this function is
* removed from the LJM buffer. This should usually be near zero and
* not growing for healthy streams.
* Note: Returns LJME_NO_SCANS_RETURNED if LJM_STREAM_SCANS_RETURN is
* LJM_STREAM_SCANS_RETURN_ALL_OR_NONE.
**/
LJM_ERROR_RETURN LJM_eStreamRead(int Handle, double * aData,
int * DeviceScanBacklog, int * LJMScanBacklog);
/**
* Name: LJM_SetStreamCallback
* Desc: Sets a callback that is called by LJM when the stream has collected
* ScansPerRead scans.
* Para: Handle, a valid handle to an open device.
* Callback, the callback function for LJM's stream thread to call
* when stream data is ready, which should call LJM_eStreamRead to
* acquire data.
* Arg, the user-defined argument that is passed to Callback when it is
* invoked.
* Note: LJM_SetStreamCallback should be called after LJM_eStreamStart.
* Note: LJM_eStreamStop may be called at any time when using
* LJM_SetStreamCallback, but the Callback function should not try to
* stop stream. If the Callback function detects that stream needs to be
* stopped, it should signal to a different thread that stream should be
* stopped.
* Note: To disable the previous callback for stream reading, pass 0 or NULL as
* Callback.
**/
typedef void (*LJM_StreamReadCallback)(void *);
LJM_ERROR_RETURN LJM_SetStreamCallback(int Handle,
LJM_StreamReadCallback Callback, void * Arg);
/**
* Name: LJM_eStreamStop
* Desc: Stops LJM from streaming any more data from the device, while leaving
* any collected data in the LJM buffer to be read. Stops the device from
* streaming.
* Para: Handle, a valid handle to an open device.
**/
LJM_ERROR_RETURN LJM_eStreamStop(int Handle);
/***************************************
* Byte-oriented Read/Write Functions *
***************************************/
/**
* Name: LJM_WriteRaw
* Desc: Sends an unaltered data packet to a device.
* Para: Handle, a valid handle to an open device.
* Data, the byte array packet to send.
* NumBytes, the size of Data.
**/
LJM_ERROR_RETURN LJM_WriteRaw(int Handle, const unsigned char * Data,
int NumBytes);
/**
* Name: LJM_ReadRaw
* Desc: Reads an unaltered data packet from a device.
* Para: Handle, a valid handle to an open device.
* Data, the allocated byte array to receive the data packet.
* NumBytes, the number of bytes to receive.
**/
LJM_ERROR_RETURN LJM_ReadRaw(int Handle, unsigned char * Data, int NumBytes);
/**
* Name: LJM_AddressesToMBFB
* Desc: Takes in arrays that together represent operations to be performed on a
* device and outputs a byte array representing a valid Feedback command,
* which can be used as input to the LJM_MBFBComm function.
* Para: MaxBytesPerMBFB, the maximum number of bytes that the Feedback command
* is allowed to consist of. It is highly recommended to pass the size
* of the aMBFBCommand buffer as MaxBytesPerMBFB to prevent buffer
* overflow. See LJM_DEFAULT_FEEDBACK_ALLOCATION_SIZE.
* aAddresses, an array of size NumFrames representing the register
* addresses to read from or write to for each frame.
* aTypes, an array of size NumFrames representing the data types to read
* or write. See the Data Type constants in this header file.
* aWrites, an array of size NumFrames of the direction/access type
* (LJM_READ or LJM_WRITE) for each frame.
* aNumValues, an array of size NumFrames giving the number of values to
* read/write for each frame.
* aValues, for every entry in aWrites[i] that is LJM_WRITE, this contains
* aNumValues[i] values to write and for every entry in aWrites that
* is LJM_READ, this contains aNumValues[i] values that can later be
* updated in the LJM_UpdateValues function. aValues values must be
* in the same order as the rest of the arrays. For example, if aWrite is
* {LJM_WRITE, LJM_READ, LJM_WRITE},
* and aNumValues is
* {1, 4, 2}
* aValues would have one value to be written, then 4 blank/garbage
* values to later be updated, and then 2 values to be written.
* NumFrames, A pointer to the number of frames being created, which is
* also the size of aAddresses, aTypes, aWrites, and aNumValues. Once
* this function returns, NumFrames will be updated to the number of
* frames aMBFBCommand contains.
* aMBFBCommand, the output parameter that contains the valid Feedback
* command. Transaction ID and Unit ID will be blanks that
* LJM_MBFBComm will fill in.
* Warn: aMBFBCommand must be an allocated array of size large enough to hold
* the Feedback command (including its frames). You can use
* MaxBytesPerMBFB to limit the size of the Feedback command.
* Note: If this function returns LJME_FRAMES_OMITTED_DUE_TO_PACKET_SIZE,
* aMBFBCommand is still valid, but does not contain all of the frames
* that were intended and NumFrames is updated to contain the number of
* frames that were included.
**/
LJM_ERROR_RETURN LJM_AddressesToMBFB(int MaxBytesPerMBFB, const int * aAddresses,
const int * aTypes, const int * aWrites, const int * aNumValues,
const double * aValues, int * NumFrames, unsigned char * aMBFBCommand);
/**
* Name: LJM_MBFBComm
* Desc: Sends a Feedback command and receives a Feedback response, parsing the
* response for obvious errors. This function adds its own Transaction ID
* to the command. The Feedback response may be parsed with the
* LJM_UpdateValues function.
* Para: Handle, a valid handle to an open device.
* UnitID, the ID of the specific unit that the Feedback command should
* be sent to. Use LJM_DEFAULT_UNIT_ID unless the device
* documentation instructs otherwise.
* aMBFB, both an input parameter and an output parameter. As an input
* parameter, it is a valid Feedback command. As an output parameter,
* it is a Feedback response, which may be an error response.
* ErrorAddress, a pointer to an integer, which in the case of a relevant
* error, gets updated to contain the device-reported
* address that caused an error.
* Note: aMBFB must be an allocated array of size large enough to hold the
* Feedback response.
**/
LJM_ERROR_RETURN LJM_MBFBComm(int Handle, unsigned char UnitID,
unsigned char * aMBFB, int * ErrorAddress);
/**
* Name: LJM_UpdateValues
* Desc: Takes a Feedback response named aMBFBResponse from a device and the
* arrays corresponding to the Feedback command for which aMBFBResponse
* is a response and updates the aValues array based on the read data in
* aMBFBResponse.
* Para: aMBFBResponse, a valid Feedback response.
* aTypes, an array of size NumFrames representing the data types to read
* or write. See the Data Type constants in this header file.
* aWrites, the array of constants from LabJackM.h - either LJM_WRITE or
* LJM_READ.
* aNumValues, the array representing how many values were read or written.
* NumFrames, the number of frames in aTypes, aWrites, and aNumValues.
* aValues, for every entry in aWrites[i] that is LJM_WRITE, this contains
* aNumValues[i] values that were written and for every entry in
* aWrites that is LJM_READ, this contains aNumValues[i] values
* that will now be updated. aValues values must be in the same
* order as the rest of the arrays. For example, if aWrite is
* {LJM_WRITE, LJM_READ, LJM_WRITE},
* and aNumValues is
* {1, 4, 2}
* LJM_UpdateValues would skip one value, then update 4 values with
* the data in aMBFBResponse, then do nothing with the last 2 values.
**/
LJM_ERROR_RETURN LJM_UpdateValues(unsigned char * aMBFBResponse,
const int * aTypes, const int * aWrites, const int * aNumValues,
int NumFrames, double * aValues);
/****************************
* Constants File Functions *
****************************/
/**
* Name: LJM_NamesToAddresses
* Desc: Takes a list of Modbus register names as input and produces two lists
* as output - the corresponding Modbus addresses and types. These two
* lists can serve as input to functions that have Address/aAddresses and
* Type/aTypes as input parameters.
* Para: NumFrames, the number of names in aNames and the allocated size of
* aAddresses and aTypes.
* aNames, an array of null-terminated C-string register identifiers.
* These register identifiers can be register names or register
* alternate names.
* aAddresses, output parameter containing the addresses described by
* aNames in the same order, must be allocated to the size NumFrames
* before calling LJM_NamesToAddresses.
* aTypes, output parameter containing the types described by aNames in
* the same order, must be allocated to the size NumFrames before
* calling LJM_NamesToAddresses.
* Note: For each register identifier in aNames that is invalid, the
* corresponding aAddresses value will be set to LJM_INVALID_NAME_ADDRESS.
**/
LJM_ERROR_RETURN LJM_NamesToAddresses(int NumFrames, const char ** aNames,
int * aAddresses, int * aTypes);
/**
* Name: LJM_NameToAddress
* Desc: Takes a Modbus register name as input and produces the corresponding
* Modbus address and type. These two values can serve as input to
* functions that have Address/aAddresses and Type/aTypes as input
* parameters.
* Para: Name, a null-terminated C-string register identifier. These register
* identifiers can be register names or register alternate names.
* Address, output parameter containing the address described by Name.
* Type, output parameter containing the type described by Names.
* Note: If Name is not a valid register identifier, Address will be set to
* LJM_INVALID_NAME_ADDRESS.
**/
LJM_ERROR_RETURN LJM_NameToAddress(const char * Name, int * Address, int * Type);
/**
* Name: LJM_AddressesToTypes
* Desc: Retrieves multiple data types for given Modbus register addresses.
* Para: NumAddresses, the number of addresses to convert to data types.
* aAddresses, an array of size NumAddresses of Modbus register addresses.
* aType, a pre-allocated array of size NumAddresses which gets updated
* to the data type for each corresponding entry in Addresses.
* Note: For each aAddresses[i] that is not found, the corresponding entry
* aTypes[i] will be set to LJM_INVALID_NAME_ADDRESS and this function
* will return LJME_INVALID_ADDRESS.
**/
LJM_ERROR_RETURN LJM_AddressesToTypes(int NumAddresses, int * aAddresses,
int * aTypes);
/**
* Name: LJM_AddressToType
* Desc: Retrieves the data type for a given Modbus register address.
* Para: Address, the Modbus register address to look up.
* Type, an integer pointer which gets updated to the data type of
* Address.
**/
LJM_ERROR_RETURN LJM_AddressToType(int Address, int * Type);
/**
* Name: LJM_LookupConstantValue
* Desc: Takes a register name or other scope and a constant name, and returns
* the constant value.
* Para: Scope, the register name or other scope to search within. Must be of
* size LJM_MAX_NAME_SIZE or less.
* ConstantName, the name of the constant to search for. Must be of size
* LJM_MAX_NAME_SIZE or less.
* ConstantValue, the returned value of ConstantName within the scope
* of Scope, if found.
**/
LJM_ERROR_RETURN LJM_LookupConstantValue(const char * Scope,
const char * ConstantName, double * ConstantValue);
/**
* Name: LJM_LookupConstantName
* Desc: Takes a register name or other scope and a value, and returns the
* name of that value, if found within the given scope.
* Para: Scope, the register name or other scope to search within. Must be of
* size LJM_MAX_NAME_SIZE or less.
* ConstantValue, the constant value to search for.
* ConstantName, a pointer to a char array allocated to size
* LJM_MAX_NAME_SIZE, used to return the null-terminated constant
* name.
**/
LJM_ERROR_RETURN LJM_LookupConstantName(const char * Scope,
double ConstantValue, char * ConstantName);
/**
* Name: LJM_ErrorToString
* Desc: Gets the name of an error code.
* Para: ErrorCode, the error code to look up.
* ErrorString, a pointer to a char array allocated to size
* LJM_MAX_NAME_SIZE, used to return the null-terminated error name.
* Note: If the constants file that has been loaded does not contain
* ErrorCode, this returns a null-terminated message saying so.
* If the constants file could not be opened, this returns a
* null-terminated string saying so and where that constants file was
* expected to be.
**/
LJM_VOID_RETURN LJM_ErrorToString(int ErrorCode, char * ErrorString);
/**
* Name: LJM_LoadConstants
* Desc: Manually loads or reloads the constants files associated with
* the LJM_ErrorToString and LJM_NamesToAddresses functions.
* Note: This step is handled automatically. This function does not need to be
* called before either LJM_ErrorToString or LJM_NamesToAddresses.
**/
LJM_VOID_RETURN LJM_LoadConstants();
/**
* Name: LJM_LoadConstantsFromFile
* Desc: Alias for executing:
* LJM_WriteLibraryConfigStringS(LJM_CONSTANTS_FILE, FileName)
* Para: FileName, the absolute or relative file path string to pass to
* LJM_WriteLibraryConfigStringS as the String parameter. Must
* null-terminate.
**/
LJM_ERROR_RETURN LJM_LoadConstantsFromFile(const char * FileName);
/**
* Name: LJM_LoadConstantsFromString
* Desc: Parses JsonString as the constants file and loads it.
* Para: JsonString, A JSON string containing a "registers" array and/or an "errors"
* array.
* Note: If the JSON string does not contain a "registers" array, the Modbus-related
* constants are not affected. Similarly, if the JSON string does not contain
* an "errors" array, the errorcode-related constants are not affected.
**/
LJM_ERROR_RETURN LJM_LoadConstantsFromString(const char * JsonString);
/******************************
* Type Conversion Functions *
******************************/
// Thermocouple conversion
// Thermocouple Type constants
static const long LJM_ttB = 6001;
static const long LJM_ttE = 6002;
static const long LJM_ttJ = 6003;
static const long LJM_ttK = 6004;
static const long LJM_ttN = 6005;
static const long LJM_ttR = 6006;
static const long LJM_ttS = 6007;
static const long LJM_ttT = 6008;
static const long LJM_ttC = 6009;
/**
* Desc: Converts thermocouple voltage to temperature.
* Para: TCType, the thermocouple type. See "Thermocouple Type constants".
* TCVolts, the voltage reported by the thermocouple.
* CJTempK, the cold junction temperature in degrees Kelvin.
* pTCTempK, outputs the calculated temperature in degrees Kelvin.
**/
LJM_ERROR_RETURN LJM_TCVoltsToTemp(int TCType, double TCVolts, double CJTempK,
double * pTCTempK);
/**
* Name: LJM_TYPE#BitsToByteArray
* Desc: Converts an array of values from C-types to bytes, performing automatic
* endian conversions if necessary.
* Para: aTYPE#Bits (such as aFLOAT32), the array of values to be converted.
* RegisterOffset, the register offset to put the converted values in aBytes.
* The actual offset depends on how many bits the type is.
* NumTYPE#Bits (such as NumFLOAT32), the number of values to convert.
* aBytes, the converted values in byte form.
**/
/**
* Name: LJM_ByteArrayToTYPE#Bits
* Desc: Converts an array of values from bytes to C-types, performing automatic
* endian conversions if necessary.
* Para: aBytes, the bytes to be converted.
* RegisterOffset, the register offset to get the values from in aBytes.
* The actual offset depends on how many bits the type is.
* NumTYPE#Bits (such as NumFLOAT32), the number of values to convert.
* aTYPE#Bits (such as aFLOAT32), the converted values in C-type form.
**/
// Single precision float, 32 bits
// (the C type "float")
LJM_VOID_RETURN LJM_FLOAT32ToByteArray(const float * aFLOAT32, int RegisterOffset, int NumFLOAT32, unsigned char * aBytes);
LJM_VOID_RETURN LJM_ByteArrayToFLOAT32(const unsigned char * aBytes, int RegisterOffset, int NumFLOAT32, float * aFLOAT32);
// Unsigned 16 bit integer
// (the C type "unsigned short" or similar)
LJM_VOID_RETURN LJM_UINT16ToByteArray(const unsigned short * aUINT16, int RegisterOffset, int NumUINT16, unsigned char * aBytes);
LJM_VOID_RETURN LJM_ByteArrayToUINT16(const unsigned char * aBytes, int RegisterOffset, int NumUINT16, unsigned short * aUINT16);
// Unsigned 32 bit integer
// (the C type "unsigned int" or similar)
LJM_VOID_RETURN LJM_UINT32ToByteArray(const unsigned int * aUINT32, int RegisterOffset, int NumUINT32, unsigned char * aBytes);
LJM_VOID_RETURN LJM_ByteArrayToUINT32(const unsigned char * aBytes, int RegisterOffset, int NumUINT32, unsigned int * aUINT32);
// Signed 32 bit integer
// (the C type "int" or similar)
LJM_VOID_RETURN LJM_INT32ToByteArray(const int * aINT32, int RegisterOffset, int NumINT32, unsigned char * aBytes);
LJM_VOID_RETURN LJM_ByteArrayToINT32(const unsigned char * aBytes, int RegisterOffset, int NumINT32, int * aINT32);
/**
* Name: LJM_NumberToIP
* Desc: Takes an integer representing an IPv4 address and outputs the corresponding
* decimal-dot IPv4 address as a null-terminated string.
* Para: Number, the numerical representation of an IP address to be converted to
* a string representation.
* IPv4String, a char array that must be allocated to size LJM_IPv4_STRING_SIZE
* which will be set to contain the null-terminated string representation
* of the IP address after the completion of this function.
* Retr: LJME_NOERROR for no detected errors,
* LJME_NULL_POINTER if IPv4String is NULL.
**/
LJM_ERROR_RETURN LJM_NumberToIP(unsigned int Number, char * IPv4String);
/**
* Name: LJM_IPToNumber
* Desc: Takes a decimal-dot IPv4 string representing an IPv4 address and outputs the
* corresponding integer version of the address.
* Para: IPv4String, the string representation of the IP address to be converted to
* a numerical representation.
* Number, the output parameter that will be updated to contain the numerical
* representation of IPv4String after the completion of this function.
* Retr: LJME_NOERROR for no detected errors,
* LJME_NULL_POINTER if IPv4String or Number is NULL,
* LJME_INVALID_PARAMETER if IPv4String could not be parsed as a IPv4 address.
**/
LJM_ERROR_RETURN LJM_IPToNumber(const char * IPv4String, unsigned int * Number);
/**
* Name: LJM_NumberToMAC
* Desc: Takes an integer representing a MAC address and outputs the corresponding
* hex-colon MAC address as a string.
* Para: Number, the numerical representation of a MAC address to be converted to
* a string representation.
* MACString, a char array that must be allocated to size LJM_MAC_STRING_SIZE
* which will be set to contain the string representation of the MAC
* address after the completion of this function.
* Retr: LJME_NOERROR for no detected errors,
* LJME_NULL_POINTER if MACString is NULL.
**/
LJM_ERROR_RETURN LJM_NumberToMAC(unsigned long long Number, char * MACString);
/**
* Name: LJM_MACToNumber
* Desc: Takes a hex-colon string representing a MAC address and outputs the
* corresponding integer version of the address.
* Para: MACString, the string representation of the MAC address to be converted to
* a numerical representation.
* Number, the output parameter that will be updated to contain the numerical
* representation of MACString after the completion of this function.
* Retr: LJME_NOERROR for no detected errors,
* LJME_NULL_POINTER if MACString or Number is NULL,
* LJME_INVALID_PARAMETER if MACString could not be parsed as a MAC address.
**/
LJM_ERROR_RETURN LJM_MACToNumber(const char * MACString, unsigned long long * Number);
/**********************
* LJM Configuration *
**********************/
// Config Parameters
/**
* Desc: The maximum number of milliseconds that LJM will wait for a packet to
* be sent and also for a packet to be received before timing out. In
* other words, LJM can wait this long for a command to be sent, then
* wait this long again for the response to be received.
**/
static const char * const LJM_USB_SEND_RECEIVE_TIMEOUT_MS = "LJM_USB_SEND_RECEIVE_TIMEOUT_MS";
static const char * const LJM_ETHERNET_SEND_RECEIVE_TIMEOUT_MS = "LJM_ETHERNET_SEND_RECEIVE_TIMEOUT_MS";
static const char * const LJM_WIFI_SEND_RECEIVE_TIMEOUT_MS = "LJM_WIFI_SEND_RECEIVE_TIMEOUT_MS";
/**
* Desc: Sets LJM_USB_SEND_RECEIVE_TIMEOUT_MS, LJM_ETHERNET_SEND_RECEIVE_TIMEOUT_MS,
* and LJM_WIFI_SEND_RECEIVE_TIMEOUT_MS.
* Note: Write-only. May not be read.
**/
static const char * const LJM_SEND_RECEIVE_TIMEOUT_MS = "LJM_SEND_RECEIVE_TIMEOUT_MS";
/**
* Name: LJM_ETHERNET_OPEN_TIMEOUT_MS
* Desc: The maximum number of milliseconds that LJM will wait for a device
* being opened via TCP to respond before timing out.
**/
static const char * const LJM_ETHERNET_OPEN_TIMEOUT_MS = "LJM_ETHERNET_OPEN_TIMEOUT_MS";
/**
* Name: LJM_WIFI_OPEN_TIMEOUT_MS
* Desc: The maximum number of milliseconds that LJM will wait for a device
* being opened via TCP to respond before timing out.
**/
static const char * const LJM_WIFI_OPEN_TIMEOUT_MS = "LJM_WIFI_OPEN_TIMEOUT_MS";
/**
* Name: LJM_OPEN_TCP_DEVICE_TIMEOUT_MS
* Desc: Sets both LJM_ETHERNET_OPEN_TIMEOUT_MS and LJM_WIFI_OPEN_TIMEOUT_MS.
* Note: Write-only. May not be read.
**/
static const char * const LJM_OPEN_TCP_DEVICE_TIMEOUT_MS = "LJM_OPEN_TCP_DEVICE_TIMEOUT_MS";
/**
* Name: LJM_DEBUG_LOG_MODE
* Desc: Any of the following modes:
* Vals: 1 (default) - Never logs anything, regardless of LJM_DEBUG_LOG_LEVEL.
* 2 - Log continuously to the log file according to LJM_DEBUG_LOG_LEVEL (see LJM_DEBUG_LOG_FILE).
* 3 - Continuously stores a finite number of log messages, writes them to file upon error.
**/
static const char * const LJM_DEBUG_LOG_MODE = "LJM_DEBUG_LOG_MODE";
enum {
LJM_DEBUG_LOG_MODE_NEVER = 1,
LJM_DEBUG_LOG_MODE_CONTINUOUS = 2,
LJM_DEBUG_LOG_MODE_ON_ERROR = 3
};
/**
* Name: LJM_DEBUG_LOG_LEVEL
* Desc: The level of priority that LJM will log. Levels that are lower than
* the current LJM_DEBUG_LOG_LEVEL are not logged. For example, if log
* priority is set to LJM_WARNING, messages with priority level
* LJM_WARNING and greater are logged to the debug file.
* Vals: See below.
* Note: LJM_PACKET is the default value.
**/
static const char * const LJM_DEBUG_LOG_LEVEL = "LJM_DEBUG_LOG_LEVEL";
enum {
LJM_STREAM_PACKET = 1,
LJM_TRACE = 2,
LJM_DEBUG = 4,
LJM_INFO = 6,
LJM_PACKET = 7,
LJM_WARNING = 8,
LJM_USER = 9,
LJM_ERROR = 10,
LJM_FATAL = 12
};
/**
* Name: LJM_DEBUG_LOG_BUFFER_MAX_SIZE
* Desc: The number of log messages LJM's logger buffer can hold.
**/
static const char * const LJM_DEBUG_LOG_BUFFER_MAX_SIZE = "LJM_DEBUG_LOG_BUFFER_MAX_SIZE";
/**
* Name: LJM_DEBUG_LOG_SLEEP_TIME_MS
* Desc: The number of milliseconds the logger thread will sleep for between
* flushing the messages in the logger buffer to the log file.
* Note: See also LJM_DEBUG_LOG_BUFFER_MAX_SIZE
**/
static const char * const LJM_DEBUG_LOG_SLEEP_TIME_MS = "LJM_DEBUG_LOG_SLEEP_TIME_MS";
/**
* Name: LJM_LIBRARY_VERSION
* Desc: Returns the current version of LJM. This will match LJM_VERSION (at
* the top of this header file) if you are using the executable LJM that
* corresponds to this header file.
**/
static const char * const LJM_LIBRARY_VERSION = "LJM_LIBRARY_VERSION";
/**
* Name: LJM_ALLOWS_AUTO_MULTIPLE_FEEDBACKS
* Desc: A mode that sets whether or not LJM will automatically send/receive
* multiple Feedback commands when the desired operations would exceed
* the maximum packet length. This mode is relevant to Easy functions
* such as LJM_eReadNames.
* Vals: 0 - Disable
* Anything else - Enable (default)
**/
static const char * const LJM_ALLOWS_AUTO_MULTIPLE_FEEDBACKS = "LJM_ALLOWS_AUTO_MULTIPLE_FEEDBACKS";
/**
* Name: LJM_ALLOWS_AUTO_CONDENSE_ADDRESSES
* Desc: A mode that sets whether or not LJM will automatically condense
* single address reads/writes into array reads/writes, which minimizes
* packet size. This mode is relevant to Easy functions such as
* LJM_eReadNames.
* Vals: 0 - Disable
* Anything else - Enable (default)
**/
static const char * const LJM_ALLOWS_AUTO_CONDENSE_ADDRESSES = "LJM_ALLOWS_AUTO_CONDENSE_ADDRESSES";
/**
* Name: LJM_AUTO_RECONNECT_STICKY_CONNECTION
* Desc: Sets whether or not LJM attempts to reconnect disrupted / disconnected
* connections according to same connection type as the original handle.
* Vals: 0 - Disable
* 1 - Enable (default)
**/
static const char * const LJM_AUTO_RECONNECT_STICKY_CONNECTION = "LJM_AUTO_RECONNECT_STICKY_CONNECTION";
/**
* Name: LJM_AUTO_RECONNECT_STICKY_SERIAL
* Desc: Sets whether or not LJM attempts to reconnect disrupted / disconnected
* connections according to same serial number as the original handle.
* Vals: 0 - Disable
* 1 - Enable (default)
**/
static const char * const LJM_AUTO_RECONNECT_STICKY_SERIAL = "LJM_AUTO_RECONNECT_STICKY_SERIAL";
/**
* Name: LJM_OPEN_MODE
* Desc: Specifies the mode of interaction LJM will use when communicating with
* opened devices.
* Vals: See following values.
* Note: See LJM_KEEP_OPEN and LJM_OPEN_MODE.
**/
static const char * const LJM_OPEN_MODE = "LJM_OPEN_MODE";
enum {
/**
* Name: LJM_KEEP_OPEN
* Desc: A LJM_OPEN_MODE that claims ownership of each opened device until
* the device is explicitly closed. In this mode, LJM maintains a
* connection to each opened device at all times.
* Note: This is a somewhat faster mode, but it is not multi-process friendly.
* If there is another process trying to access a device that is opened
* with LJM using this mode, it will not be able to.
**/
LJM_KEEP_OPEN = 1,
/**
* THIS MODE IS NOT YET IMPLEMENTED
* Name: LJM_KEEP_OPEN
* Desc: A multi-process friendly LJM_OPEN_MODE that does not claim ownership
* of any opened devices except when the device is being communicated
* with. In this mode, LJM will automatically close connection(s) to
* devices that are not actively sending/receiving communications and
* automatically reopen connection(s) when needed.
* Note: This mode is slightly slower, but allows other processes/programs to
* access a LJM-opened device without needing to close the device with
* LJM first.
* When using LJM_KEEP_OPEN mode, LJM_Close or LJM_CloseAll still need
* to be called (to clean up memory).
**/
LJM_OPEN_CLOSE = 2
};
/**
* Name: LJM_MODBUS_MAP_CONSTANTS_FILE
* Desc: Specifies absolute or relative path of the constants file to use for
* functions that use the LJM Name functionality, such as
* LJM_NamesToAddresses and LJM_eReadName.
**/
static const char * const LJM_MODBUS_MAP_CONSTANTS_FILE = "LJM_MODBUS_MAP_CONSTANTS_FILE";
/**
* Name: LJM_ERROR_CONSTANTS_FILE
* Desc: Specifies absolute or relative path of the constants file to use for
* LJM_ErrorToString.
**/
static const char * const LJM_ERROR_CONSTANTS_FILE = "LJM_ERROR_CONSTANTS_FILE";
/**
* Name: LJM_DEBUG_LOG_FILE
* Desc: Describes the absolute or relative path of the file to output log
* messages to.
* Note: See LJM_DEBUG_LOG_MODE and LJM_DEBUG_LOG_LEVEL.
**/
static const char * const LJM_DEBUG_LOG_FILE = "LJM_DEBUG_LOG_FILE";
/**
* Name: LJM_CONSTANTS_FILE
* Desc: Sets LJM_MODBUS_MAP_CONSTANTS_FILE and LJM_ERROR_CONSTANTS_FILE at the same
* time, as an absolute or relative file path.
* Note: Cannot be read, since LJM_MODBUS_MAP_CONSTANTS_FILE and
* LJM_ERROR_CONSTANTS_FILE can be different files.
**/
static const char * const LJM_CONSTANTS_FILE = "LJM_CONSTANTS_FILE";
/**
* Name: LJM_DEBUG_LOG_FILE_MAX_SIZE
* Desc: The maximum size of the log file in number of characters.
* Note: This is an approximate limit.
**/
static const char * const LJM_DEBUG_LOG_FILE_MAX_SIZE = "LJM_DEBUG_LOG_FILE_MAX_SIZE";
/**
* Name: LJM_STREAM_AIN_BINARY
* Desc: Sets whether data returned from LJM_eStreamRead will be
* calibrated or uncalibrated.
* Vals: 0 - Calibrated floating point AIN data (default)
* 1 - Uncalibrated binary AIN data
**/
static const char * const LJM_STREAM_AIN_BINARY = "LJM_STREAM_AIN_BINARY";
/**
* Name: LJM_STREAM_SCANS_RETURN
* Desc: Sets how LJM_eStreamRead will return data.
* Note: Does not affect currently running or already initialized streams.
**/
static const char * const LJM_STREAM_SCANS_RETURN = "LJM_STREAM_SCANS_RETURN";
enum {
/**
* Name: LJM_STREAM_SCANS_RETURN_ALL
* Desc: A mode that will cause LJM_eStreamRead to sleep until the full
* ScansPerRead scans are collected by LJM.
* Note: ScansPerRead is a parameter of LJM_eStreamStart.
* Note: This mode may not be apporpriate for stream types that are not
* consistently timed, such as gate stream mode or external clock stream
* mode.
**/
LJM_STREAM_SCANS_RETURN_ALL = 1,
/**
* Name: LJM_STREAM_SCANS_RETURN_ALL_OR_NONE
* Desc: A mode that will cause LJM_eStreamRead to never sleep, and instead
* either:
* consume ScansPerRead scans and return LJME_NOERROR, or
* consume no scans and return LJME_NO_SCANS_RETURNED.
* LJM_eStreamRead will consume ScansPerRead if the LJM handle has
* received ScansPerRead or more scans, otherwise it will consume none.
* Note: ScansPerRead is a parameter of LJM_eStreamStart.
**/
LJM_STREAM_SCANS_RETURN_ALL_OR_NONE = 2
/**
* Name: LJM_STREAM_SCANS_RETURN_AVAILABLE
* Desc: A mode that will cause LJM_eStreamRead to never sleep, and always
* consume the number of scans that the LJM handle has received, up to
* a maximum of ScansPerRead. Fills the excess scan places in aData
* not read, if any, with LJM_SCAN_NOT_READ.
* Note: ScansPerRead is a parameter of LJM_eStreamStart.
* TODO: LJM_STREAM_SCANS_RETURN_AVAILABLE is not currently implemented.
**/
// LJM_STREAM_SCANS_RETURN_AVAILABLE = 3
};
/**
* Name: LJM_STREAM_RECEIVE_TIMEOUT_MODE
* Desc: Sets how stream should time out.
* Note: Does not affect currently running or already initialized streams.
**/
static const char * const LJM_STREAM_RECEIVE_TIMEOUT_MODE = "LJM_STREAM_RECEIVE_TIMEOUT_MODE";
enum {
/**
* Name: LJM_STREAM_RECEIVE_TIMEOUT_MODE_CALCULATED
* Desc: Calculates how long the stream timeout should be, according to the
* scan rate reported by the device.
* Note: This is the default LJM_STREAM_RECEIVE_TIMEOUT_MODE.
**/
LJM_STREAM_RECEIVE_TIMEOUT_MODE_CALCULATED = 1,
/**
* Name: LJM_STREAM_RECEIVE_TIMEOUT_MODE_MANUAL
* Desc: Manually sets how long the stream timeout should be.
* Note: The actual stream timeout value is set via
* LJM_STREAM_RECEIVE_TIMEOUT_MS.
**/
LJM_STREAM_RECEIVE_TIMEOUT_MODE_MANUAL = 2
};
/**
* Name: LJM_STREAM_RECEIVE_TIMEOUT_MS
* Desc: Manually sets the stream receive timeout in milliseconds. Writing to
* this configuration sets LJM_STREAM_RECEIVE_TIMEOUT_MODE to be
* LJM_STREAM_RECEIVE_TIMEOUT_MODE_MANUAL.
* Note: 0 is never timeout.
* Note: Only affects currently running or already initialized streams if those
* streams were initialized with a LJM_STREAM_RECEIVE_TIMEOUT_MODE of
* LJM_STREAM_RECEIVE_TIMEOUT_MODE_MANUAL.
**/
static const char * const LJM_STREAM_RECEIVE_TIMEOUT_MS = "LJM_STREAM_RECEIVE_TIMEOUT_MS";
/**
* Name: LJM_STREAM_TRANSFERS_PER_SECOND
* Desc: Sets/gets the number of times per second stream threads attempt to
* read from the stream.
* Note: Does not affect currently running or already initialized streams.
**/
static const char * const LJM_STREAM_TRANSFERS_PER_SECOND = "LJM_STREAM_TRANSFERS_PER_SECOND";
/**
* Name: LJM_RETRY_ON_TRANSACTION_ID_MISMATCH
* Desc: Sets/gets whether or not LJM will automatically retry an operation if
* an LJME_TRANSACTION_ID_ERR occurs.
* Vals: 0 - Disable
* 1 - Enable (default)
**/
static const char * const LJM_RETRY_ON_TRANSACTION_ID_MISMATCH = "LJM_RETRY_ON_TRANSACTION_ID_MISMATCH";
/**
* Name: LJM_OLD_FIRMWARE_CHECK
* Desc: Sets/gets whether or not LJM will check the constants file (see
* LJM_CONSTANTS_FILE) to make sure the firmware of the current device is
* compatible with the Modbus register(s) being read from or written to,
* when applicable. When device firmware is lower than fwmin for the
* register(s) being read/written, LJM will return LJME_OLD_FIRMWARE and
* not perform the Modbus operation(s).
* Vals: 0 - Disable
* 1 - Enable (default)
* Note: When enabled, LJM will perform a check that is linear in size
* proportional to the number of register entries in the constants file
* for each address/name being read/written.
**/
static const char * const LJM_OLD_FIRMWARE_CHECK = "LJM_OLD_FIRMWARE_CHECK";
/**
* Name: LJM_ZERO_LENGTH_ARRAY_MODE
* Desc: Determines the behavior of array read/write functions when the array
* size is 0.
**/
static const char * const LJM_ZERO_LENGTH_ARRAY_MODE = "LJM_ZERO_LENGTH_ARRAY_MODE";
enum {
/**
* Name: LJM_ZERO_LENGTH_ARRAY_ERROR
* Desc: Sets LJM to return an error when an array of size 0 is detected.
**/
LJM_ZERO_LENGTH_ARRAY_ERROR = 1,
/**
* Name: LJM_ZERO_LENGTH_ARRAY_IGNORE_OPERATION
* Desc: Sets LJM to ignore the operation when all arrays in the
* operation are of size 0.
**/
LJM_ZERO_LENGTH_ARRAY_IGNORE_OPERATION = 2
};
// Config functions
/**
* Name: LJM_WriteLibraryConfigS
* Desc: Writes/sets a library configuration/setting.
* Para: Parameter, the name of the configuration setting. Not
* case-sensitive. Must null-terminate.
* Value, the config value to apply to Parameter.
* Retr: LJM_NOERROR for success,
* LJME_INVALID_CONFIG_NAME for a Parameter value that is unknown.
* Note: See "Config Parameters" for valid Parameters and "Config Values" for
* valid Values.
**/
LJM_ERROR_RETURN LJM_WriteLibraryConfigS(const char * Parameter, double Value);
/**
* Name: LJM_WriteLibraryConfigStringS
* Desc: Writes/sets a library configuration/setting.
* Para: Parameter, the name of the configuration setting. Not
* case-sensitive. Must null-terminate.
* String, the config value string to apply to Parameter. Must
* null-terminate. Must not be of size greater than
* LJM_MAX_NAME_SIZE, including null-terminator.
* Retr: LJM_NOERROR for success,
* LJME_INVALID_CONFIG_NAME for a Parameter value that is unknown
* Note: See "Config Parameters" for valid Parameters and "Config Values" for
* valid Values.
**/
LJM_ERROR_RETURN LJM_WriteLibraryConfigStringS(const char * Parameter,
const char * String);
/**
* Name: LJM_ReadLibraryConfigS
* Desc: Reads a configuration/setting from the library.
* Para: Parameter, the name of the configuration setting. Not
* case-sensitive. Must null-terminate.
* Value, return value representing the config value.
* Retr: LJM_NOERROR for success,
* LJME_INVALID_CONFIG_NAME for a Parameter value that is unknown.
* Note: See "Config Parameters" for valid Parameters and "Config Values" for
* valid Values.
**/
LJM_ERROR_RETURN LJM_ReadLibraryConfigS(const char * Parameter, double * Value);
/**
* Name: LJM_ReadLibraryConfigStringS
* Desc: Reads a configuration/setting from the library.
* Para: Parameter, the name of the configuration setting. Not
* case-sensitive. Must null-terminate.
* string, return value representing the config string. Must be
* pre-allocated to size LJM_MAX_NAME_SIZE.
* Retr: LJM_NOERROR for success,
* LJME_INVALID_CONFIG_NAME for a Parameter value that is unknown.
* Note: See "Config Parameters" for valid Parameters and "Config Values" for
* valid Values.
**/
LJM_ERROR_RETURN LJM_ReadLibraryConfigStringS(const char * Parameter, char * String);
/**
* Desc: Load all the configuration values in a specified file.
* Para: FileName, a relative or absolute file location. "default" maps to the
* default configuration file ljm_startup_config.json in the
* constants file location. Must null-terminate.
**/
LJM_ERROR_RETURN LJM_LoadConfigurationFile(const char * FileName);
/******************
* Log Functions *
******************/
/**
* Name: LJM_Log
* Desc: Sends a message of the specified level to the LJM debug logger.
* Para: Level, the level to output the message at. See LJM_DEBUG_LOG_LEVEL.
* String, the debug message to be written to the log file.
* Note: By default, LJM_DEBUG_LOG_MODE is to never log, so LJM does not output
* any log messages, even from this function.
* Note: For more information on the LJM debug logger, see LJM_DEBUG_LOG_MODE,
* LJM_DEBUG_LOG_LEVEL, LJM_DEBUG_LOG_BUFFER_MAX_SIZE,
* LJM_DEBUG_LOG_SLEEP_TIME_MS, LJM_DEBUG_LOG_FILE,
* LJM_DEBUG_LOG_FILE_MAX_SIZE
**/
LJM_ERROR_RETURN LJM_Log(int Level, const char * String);
/**
* Name: LJM_ResetLog
* Desc: Clears all characters from the debug log file.
* Note: See the LJM configuration properties for Log-related properties.
**/
LJM_ERROR_RETURN LJM_ResetLog();
#ifdef __cplusplus
}
#endif
#endif // #define LAB_JACK_M_HEADER
| 76,915 | C | 43.980117 | 129 | 0.680894 |
adegirmenci/HBL-ICEbot/old/frmgrab.cpp | #include "frmgrab.h"
#include "ui_frmgrab.h"
FrmGrab::FrmGrab(QWidget *parent) :
QWidget(parent),
ui(new Ui::FrmGrab)
{
ui->setupUi(this);
m_fg = NULL;
m_isInitialized = false;
m_isConnected = false;
m_numFramesWritten = 0;
}
FrmGrab::~FrmGrab()
{
frmGrabDisconnect();
delete ui;
}
bool FrmGrab::frmGrabConnect()
{
m_isConnected = false;
m_fg = FrmGrabLocal_Open();
if(!(m_fg == NULL))
{
m_isConnected = FrmGrab_Start(m_fg); // set global variable to true to indicate frmGrabber is initialized
if(m_isConnected)
qDebug() << "FrmGrab started.";
else
qDebug() << "FrmGrab failed to start.";
}
else
{
ui->statusLineEdit->setText("Failed to open device!");
qDebug() << "Failed to open device!";
}
return m_isConnected;
}
bool FrmGrab::SetFileName(const QString &fileName)
{
QMutexLocker locker(&m_mutex); // lock mutex
// mutex unlocks when locker goes out of scope
if(!m_txtFile.isOpen()) // file is not open
{
m_txtFile.setFileName(fileName);
return true;
}
else // file is already open
{
return false;
}
}
bool FrmGrab::frmGrabInitialize(const char *location)
{
bool state = false;
if(m_isConnected && (!m_isInitialized) ) // successfully connected and not alreadxy initialized
{
qDebug() << "Initializing file.";
QString t = getCurrDateTimeFileStr(); // get date time now
m_saveDir.clear(); // clear filename
m_saveDir.append("RECORDED_FRMGRAB/").append(t); // set the directory
// check if the directory exists, if not, create it
QDir dir;
if( ! dir.exists(m_saveDir) ){
if( dir.mkpath(m_saveDir) )
{
qDebug() << "Folder created: " << m_saveDir;
state = true;
}
else
qDebug() << "Folder creation failed: " << m_saveDir;
}
// set file name
m_imgFname_pre = getCurrDateTimeFileStr();
m_txtFname = m_saveDir;
m_txtFname.append("/");
m_txtFname.append(m_imgFname_pre);
m_txtFname.append("_");
m_txtFname.append(location);
m_txtFname.append(".txt");
state = SetFileName(m_txtFname);
//Open file for write and append
if(!m_txtFile.open(QIODevice::WriteOnly | QIODevice::Append))
{
qDebug() << "File could not be opened: " << m_txtFile.fileName();
state = false;
}
else
{
m_textStream.setDevice(&m_txtFile);
m_textStream << "File opened at: " << getCurrDateTimeStr() << '\n';
m_textStream << location << endl; // write to file where initialize is called from
m_textStream << "File Name \t Time (s)" << endl; // write header
state = state && true;
qDebug() << "File opened:" << m_txtFile.fileName();
}
}
m_isInitialized = state;
qDebug() << "State is " << state;
return state; // return false if already initialized or if the file couldn't be opened
}
bool FrmGrab::grabFrame()
{
bool state = false;
if(m_fg == NULL)
{
ui->statusLineEdit->setText("Failed to read device.");
}
else
{
std::shared_ptr<Frame> newFrame( new Frame );
newFrame->timestamp_ = m_epoch.elapsed()/1000.; // get time stamp
m_frame = FrmGrab_Frame(m_fg, V2U_GRABFRAME_FORMAT_BGR24, NULL);
m_imgSize = cv::Size(m_frame->mode.width, m_frame->mode.height);
//qDebug() << m_imgSize.width << " x " << m_imgSize.height;
if (m_frame)
{
m_src = cv::Mat(m_imgSize,CV_8UC3);
m_src.data = (uchar*)(m_frame->pixbuf);
cv::cvtColor(m_src, m_dst, CV_BGR2GRAY);
newFrame->image_ = m_dst; // add frame to container
FrmGrab_Release(m_fg, m_frame);
newFrame->index_ = m_numFramesWritten;
m_numFramesWritten++;
QMutexLocker locker(&m_mutex);
m_frmList.push_back( newFrame );
state = true;
}
}
return state;
}
bool FrmGrab::saveFrame(std::shared_ptr<Frame> frm)
{
bool state = false;
if(m_isInitialized) // not already initialized
{
QString m_imgFname = m_saveDir; // contains file name of frame
m_imgFname.append("/").append(m_imgFname_pre);
// populate m_imgFname with index
m_imgFname.append( QString("_%1.jpg").arg(frm->index_) );
// save frame
//state = frame->image_.save(m_imgFname, "JPG", 100);
cv::imwrite(m_imgFname.toStdString().c_str(), frm->image_ ); // write frame
// output to text
if(m_txtFile.isOpen())
{
m_textStream << m_imgFname_pre << QString("_%1.jpg").arg(frm->index_) << "\t"
<< QString::number(frm->timestamp_, 'f', 6) << '\n';
m_textStream.flush();
state = true;
}
}
// save image to file using QtConcurrent calls
return state;
}
bool FrmGrab::frmGrabDisconnect()
{
FrmGrab_Close(m_fg);
// if(m_fg == NULL)
// return true;
// else
// return false;
return true;
}
bool FrmGrab::setEpoch(const QTime &epoch)
{
m_epoch = epoch;
return true;
}
// ------------------------------ //
// GUI INTERACTION IMPLEMENTATION //
// ------------------------------ //
void FrmGrab::on_connectButton_clicked()
{
if( frmGrabConnect() )
{
ui->connectButton->setEnabled(false);
ui->initButton->setEnabled(true);
ui->disconnectButton->setEnabled(true);
ui->statusLineEdit->setText("Connected.");
}
else
ui->statusLineEdit->setText("Failed to connect.");
}
void FrmGrab::on_initButton_clicked()
{
if( frmGrabInitialize("GUI_Button") )
{
ui->initButton->setEnabled(false);
ui->statusLineEdit->setText("Initialized.");
ui->acquireButton->setEnabled(true);
ui->saveButton->setEnabled(true);
}
else
{
ui->statusLineEdit->setText("Failed to initialize.");
ui->acquireButton->setEnabled(false);
ui->saveButton->setEnabled(false);
}
}
void FrmGrab::on_disconnectButton_clicked()
{
if( frmGrabDisconnect() )
{
ui->connectButton->setEnabled(true);
ui->initButton->setEnabled(false);
ui->disconnectButton->setEnabled(false);
ui->acquireButton->setEnabled(false);
ui->saveButton->setEnabled(false);
ui->statusLineEdit->setText("Disconnected.");
}
else
ui->statusLineEdit->setText("Failed to disconnect.");
}
void FrmGrab::on_acquireButton_clicked()
{
for( int i = 0; i < 120; i++)
grabFrame();
if( grabFrame() )
ui->statusLineEdit->setText("Frame grabbed.");
else
ui->statusLineEdit->setText("Failed to grab frame.");
}
void FrmGrab::on_saveButton_clicked()
{
while( m_frmList.size() > 0)
{
if( saveFrame(m_frmList.front()) )
{
ui->statusLineEdit->setText("Frame saved.");
QMutexLocker locker(&m_mutex);
m_frmList.pop_front();
}
else
ui->statusLineEdit->setText("Failed to save frame.");
}
ui->statusLineEdit->setText("No more frames to write.");
}
// ------------------------------------- //
// GUI INTERACTION IMPLEMENTATION - DONE //
// ------------------------------------- //
inline const QString getCurrDateTimeFileStr()
{
return QDateTime::currentDateTime().toString("ddMMyyyy_hhmmsszzz");
}
inline const QString getCurrDateTimeStr()
{
return QDateTime::currentDateTime().toString("dd/MM/yyyy - hh:mm:ss.zzz");
}
| 7,807 | C++ | 24.025641 | 113 | 0.55937 |
adegirmenci/HBL-ICEbot/old/frmgrab.h | #ifndef FRMGRAB_H
#define FRMGRAB_H
#include <QWidget>
#include <QString>
#include <QFile>
#include <QTextStream>
#include <QImage>
#include <list>
#include <memory>
#include <QTime>
#include <QDir>
#include <QDebug>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
//#include <epiphan/include/v2u_defs.h>
#include <epiphan/frmgrab/include/frmgrab.h>
//#include <v2u_defs.h>
//#include <frmgrab.h>
//#include "epiphan/include/v2u_defs.h"
//#include "epiphan/frmgrab/include/frmgrab.h"
/** Frame structure.
* This will hold an image, a timestamp, and an index.
*/
struct Frame{
cv::Mat image_; /*!< Image data. */
double timestamp_; /*!< Timestamp, msec since some epoch. */
int index_; /*!< Index value of Frame, indicate order of acquisition. */
//! Constructor.
Frame()
{
image_ = NULL;
timestamp_ = -1.;
index_ = -1;
}
Frame(cv::Mat& img, double ts, int id)
{
image_ = img;
timestamp_ = ts;
index_ = id;
}
};
namespace Ui {
class FrmGrab;
}
class FrmGrab : public QWidget
{
Q_OBJECT
public:
explicit FrmGrab(QWidget *parent = 0);
bool setEpoch(const QTime &epoch);
~FrmGrab();
private slots:
void on_connectButton_clicked();
void on_initButton_clicked();
void on_disconnectButton_clicked();
void on_acquireButton_clicked();
void on_saveButton_clicked();
private:
Ui::FrmGrab *ui;
// File names for frame grabber use
QString m_saveDir; // the directory where files will be saved
QString m_txtFname; // contains file name of each frame and its timestamp
QString m_imgFname_pre; // filename prepend
// File for time stamps : open file for output, delete content if already exists
QFile m_txtFile;
QTextStream m_textStream;
bool m_isConnected;
bool m_isInitialized;
int m_numFramesWritten;
QTime m_epoch; // when was the GUI started - can be set externally
//cv::VideoCapture m_frmGrab_cap;
FrmGrabber* m_fg;
V2U_GrabFrame2* m_frame;
cv::Mat m_src; // Image containers
cv::Mat m_dst;
cv::Size m_imgSize;
std::list< std::shared_ptr<Frame> > m_frmList;
// DO NOT use m_mutex.lock()
// INSTEAD use "QMutexLocker locker(&m_mutex);"
// this will unlock the mutex when the locker goes out of scope
mutable QMutex m_mutex;
bool frmGrabConnect();
bool SetFileName(const QString &fileName);
bool frmGrabInitialize(const char* location);
bool grabFrame();
bool saveFrame(std::shared_ptr<Frame> frm);
bool frmGrabDisconnect();
};
inline const QString getCurrDateTimeFileStr();
inline const QString getCurrDateTimeStr();
#endif // FRMGRAB_H
| 2,761 | C | 21.455284 | 84 | 0.661355 |
adegirmenci/HBL-ICEbot/old/Point.cpp | #include "Point.h"
Point::Point()
{
m_x = 0.0;
m_y = 0.0;
m_z = 0.0;
}
Point::Point(double x, double y, double z)
{
m_x = x;
m_y = y;
m_z = z;
}
void Point::update(double px, double py, double pz)
{
m_x = px;
m_y = py;
m_z = pz;
}
// Distance to another point. Pythagorean thm.
double Point::dist(const Point other)
{
double xd = m_x - other.m_x;
double yd = m_y - other.m_y;
double zd = m_z - other.m_z;
return sqrt(xd*xd + yd*yd + zd*zd);
}
// Add or subtract two points.
Point Point::operator+(const Point& rhs)
{
return Point(m_x + rhs.getx(),
m_y + rhs.gety(),
m_z + rhs.getz());
}
Point Point::operator-(const Point& rhs)
{
return Point(m_x - rhs.getx(),
m_y - rhs.gety(),
m_z - rhs.getz());
}
Point Point::operator*(const double k)
{
return Point(m_x*k, m_y*k, m_z*k);
}
Point Point::operator/(const double k)
{
return Point(m_x/k, m_y/k, m_z/k);
}
Point& Point::operator=(const Point& rhs)
{
m_x = rhs.getx();
m_y = rhs.gety();
m_z = rhs.getz();
return *this;
}
// Move the existing point.
void Point::move(double a, double b, double c)
{
m_x += a;
m_y += b;
m_z += c;
}
| 1,253 | C++ | 16.416666 | 51 | 0.523543 |
adegirmenci/HBL-ICEbot/old/Point.h | #ifndef POINT_H
#define POINT_H
#include <math.h>
class Point
{
private:
double m_x;
double m_y;
double m_z;
public:
Point();
Point(double x, double y, double z);
~Point(){}
// helper functions - data access
void setx(double pk) { m_x = pk; }
void sety(double pk) { m_y = pk; }
void setz(double pk) { m_z = pk; }
// helper functions - modifiers
double getx() const { return m_x; }
double gety() const { return m_y; }
double getz() const { return m_z; }
void update(double px, double py, double pz);
double dist(const Point other);
Point operator+(const Point& rhs);
Point operator-(const Point& rhs);
Point operator*(const double k);
Point operator/(const double k);
Point& operator=(const Point& rhs);
void move(double a, double b, double c);
};
#endif // POINT_H
| 861 | C | 20.549999 | 49 | 0.608595 |
adegirmenci/HBL-ICEbot/old/labjack.h | #ifndef LABJACK_H
#define LABJACK_H
#include <QWidget>
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <QPointer>
#include <QThread>
#include <QTimer>
#include <QDateTime>
#include "LabJackUD.h"
// ------------------------------------------- \\
// -------------- LabJackWorker -------------- \\
// ------------------------------------------- \\
class LabJackWorker : public QObject
{
Q_OBJECT
public:
LabJackWorker();
LabJackWorker(int samplesPsec);
~LabJackWorker();
public slots:
bool ConnectToLabJack(); // helper function to connect to LabJack
bool SetFileName(const QString &fileName);
bool ConfigureStream();
bool StartStream();
bool StopStream();
bool DisconnectFromLabJack(); // helper function to disconnect from LabJack
void setEpoch(const QTime &epoch);
bool workerIsReady();
bool workerIsRecording();
private slots:
bool ReadStream();
signals:
void finished();
private:
QPointer<QTimer> m_eventTimer; // timer for event loop
QFile m_outputFile; // output file
QTextStream m_textStream;
int m_timeCurr;
QTime m_epoch; // when was the GUI started - can be set externally
// Flag to keep track of connection
bool m_LabJackReady;
// DO NOT use m_mutex.lock()
// INSTEAD use "QMutexLocker locker(&m_mutex);"
// this will unlock the mutex when the locker goes out of scope
mutable QMutex m_mutex;
// LabJack specific variables
LJ_ERROR m_lngErrorcode;
LJ_HANDLE m_lngHandle;
long m_lngGetNextIteration;
unsigned long long int m_i, m_k;
long m_lngIOType, m_lngChannel;
double m_dblValue, m_dblCommBacklog, m_dblUDBacklog;
double m_scanRate; //scan rate = sample rate / #channels
int m_delayms;
double m_numScans; //Max number of scans per read. 2x the expected # of scans (2*scanRate*delayms/1000).
double m_numScansRequested;
double *m_adblData;
long m_padblData;
// LabJack specific variables \\
bool ErrorHandler(LJ_ERROR lngErrorcode, long lngLineNumber, long lngIteration);
};
// ------------------------------------- \\
// -------------- LabJack -------------- \\
// ------------------------------------- \\
namespace Ui {
class LabJack;
}
class LabJack : public QWidget
{
Q_OBJECT
QPointer<QThread> workerThread;
public:
explicit LabJack(QWidget *parent = 0);
~LabJack();
bool isReady();
bool isRecording();
bool setWorkerEpoch(const QTime &epoch);
bool setWorkerFileName(const QString &fileName);
public slots:
signals:
private slots:
void on_connectButton_clicked();
void on_disconnectButton_clicked();
void on_initializeLJbutton_clicked();
void on_startRecordButton_clicked();
void on_stopRecordButton_clicked();
private:
Ui::LabJack *ui;
QPointer<LabJackWorker> worker;
bool ConfigureWorker(int samplesPsec);
};
inline const QString getCurrTimeStr();
inline const QString getCurrDateTimeStr();
#endif // LABJACK_H
| 3,010 | C | 22.341085 | 109 | 0.640199 |
adegirmenci/HBL-ICEbot/old/labjack.cpp | #include "labjack.h"
#include "ui_labjack.h"
// ------------------------------------------- \\
// -------------- LabJackWorker -------------- \\
// ------------------------------------------- \\
LabJackWorker::LabJackWorker()
{
// default samples per second is 1000
LabJackWorker(1000);
}
LabJackWorker::LabJackWorker(int samplesPsec)
{
QMutexLocker locker(&m_mutex); // lock mutex
m_lngErrorcode = 0;
m_lngHandle = 0;
m_i = 0;
m_k = 0;
m_lngIOType = 0;
m_lngChannel = 0;
m_dblValue = 0;
m_dblCommBacklog = 0;
m_dblUDBacklog = 0;
m_scanRate = samplesPsec; //scan rate = sample rate / #channels
m_delayms = 1000; // 1 seconds per 1000 samples
m_numScans = 2*m_scanRate*m_delayms/1000; //Max number of scans per read. 2x the expected # of scans (2*scanRate*delayms/1000).
m_adblData = (double *)calloc( m_numScans, sizeof(double)); //Max buffer size (#channels*numScansRequested)
m_padblData = (long)&m_adblData[0];
m_LabJackReady = false;
//m_keepRecording = false; // flag for the while loop
m_eventTimer = new QTimer(this->thread());
connect(m_eventTimer, SIGNAL(timeout()), this, SLOT(ReadStream()));
// mutex unlocks when locker goes out of scope
}
LabJackWorker::~LabJackWorker()
{
qDebug() << "[Destroy LabJack Worker] Disconnect From Labjack" <<
DisconnectFromLabJack();
qDebug() << "[Destroy LabJack Worker] DeleteLater m_eventTimer";
if(!m_eventTimer.isNull())
delete m_eventTimer;//->deleteLater();
qDebug() << "[Destroy LabJack Worker] Free m_adblData";
free( m_adblData );
}
bool LabJackWorker::ConnectToLabJack()
{
bool success = false;
QMutexLocker locker(&m_mutex); // lock mutex
//Open the first found LabJack U6.
m_lngErrorcode = OpenLabJack(LJ_dtU6, LJ_ctUSB, "1", 1, &m_lngHandle);
success = ErrorHandler(m_lngErrorcode, __LINE__, 0);
//Read and display the hardware version of this U6.
m_lngErrorcode = eGet(m_lngHandle, LJ_ioGET_CONFIG, LJ_chHARDWARE_VERSION, &m_dblValue, 0);
printf("U6 Hardware Version = %.3f\n\n", m_dblValue);
ErrorHandler(m_lngErrorcode, __LINE__, 0);
//Read and display the firmware version of this U6.
m_lngErrorcode = eGet(m_lngHandle, LJ_ioGET_CONFIG, LJ_chFIRMWARE_VERSION, &m_dblValue, 0);
printf("U6 Firmware Version = %.3f\n\n", m_dblValue);
ErrorHandler(m_lngErrorcode, __LINE__, 0);
return success;
// mutex unlocks when locker goes out of scope
}
bool LabJackWorker::SetFileName(const QString &fileName)
{
QMutexLocker locker(&m_mutex); // lock mutex
// mutex unlocks when locker goes out of scope
if(!m_outputFile.isOpen()) // file is not open
{
m_outputFile.setFileName(fileName);
return true;
}
else // file is already open
{
return false;
}
}
bool LabJackWorker::ConfigureStream()
{
bool success = false;
QMutexLocker locker(&m_mutex); // lock mutex
// mutex unlocks when locker goes out of scope
//Open file for write and append
if(!m_outputFile.open(QIODevice::WriteOnly | QIODevice::Append))
{
qDebug() << "File could not be opened: " << m_outputFile.fileName();
return false;
}
else
{
m_textStream.setDevice(&m_outputFile);
m_textStream << "File opened at: " << getCurrDateTimeStr() << '\n';
}
//Configure the stream:
//Configure resolution of the analog inputs (pass a non-zero value for quick sampling).
//See section 2.6 / 3.1 for more information.
m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_CONFIG, LJ_chAIN_RESOLUTION, 0, 0, 0);
ErrorHandler(m_lngErrorcode, __LINE__, 0);
// Configure the analog input range on channel 0 for bipolar + -5 volts.
//m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_AIN_RANGE, 0, LJ_rgBIP5V, 0, 0);
//ErrorHandler(m_lngErrorcode, __LINE__, 0);
//Set the scan rate.
m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_CONFIG, LJ_chSTREAM_SCAN_FREQUENCY, m_scanRate, 0, 0);
ErrorHandler(m_lngErrorcode, __LINE__, 0);
//Give the driver a 5 second buffer (scanRate * 1 channels * 5 seconds).
m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_CONFIG, LJ_chSTREAM_BUFFER_SIZE, m_scanRate * 1 * 5, 0, 0);
ErrorHandler(m_lngErrorcode, __LINE__, 0);
//Configure reads to retrieve whatever data is available without waiting (wait mode LJ_swNONE).
m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_CONFIG, LJ_chSTREAM_WAIT_MODE, LJ_swNONE, 0, 0);
ErrorHandler(m_lngErrorcode, __LINE__, 0);
//Define the scan list as AIN0.
m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioCLEAR_STREAM_CHANNELS, 0, 0, 0, 0);
ErrorHandler(m_lngErrorcode, __LINE__, 0);
m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioADD_STREAM_CHANNEL, 0, 0, 0, 0); // first method for single ended reading - AIN0
ErrorHandler(m_lngErrorcode, __LINE__, 0);
//Execute the list of requests.
m_lngErrorcode = GoOne(m_lngHandle);
success = ErrorHandler(m_lngErrorcode, __LINE__, 0);
//Get all the results just to check for errors.
m_lngErrorcode = GetFirstResult(m_lngHandle, &m_lngIOType, &m_lngChannel, &m_dblValue, 0, 0);
success = success && ErrorHandler(m_lngErrorcode, __LINE__, 0);
m_lngGetNextIteration = 0; //Used by the error handling function.
while (m_lngErrorcode < LJE_MIN_GROUP_ERROR)
{
m_lngErrorcode = GetNextResult(m_lngHandle, &m_lngIOType, &m_lngChannel, &m_dblValue, 0, 0);
if (m_lngErrorcode != LJE_NO_MORE_DATA_AVAILABLE)
{
success = success && ErrorHandler(m_lngErrorcode, __LINE__, m_lngGetNextIteration);
}
m_lngGetNextIteration++;
}
return m_LabJackReady = success;
}
bool LabJackWorker::StartStream()
{
QMutexLocker locker(&m_mutex); // lock mutex
// mutex unlocks when locker goes out of scope
if(m_LabJackReady) // ready to read data
{
m_timeCurr = m_epoch.elapsed(); // msec since epoch
//Start the stream.
m_lngErrorcode = eGet(m_lngHandle, LJ_ioSTART_STREAM, 0, &m_dblValue, 0);
ErrorHandler(m_lngErrorcode, __LINE__, 0);
// Write start time
if(m_outputFile.isOpen())
{
m_textStream << "Epoch at: "
<< m_epoch.toString("dd/MM/yyyy - hh:mm:ss.zzz") << '\n';
m_textStream << "Recording started at: " << getCurrTimeStr() << '\n';
// write actual scan rate to file
m_textStream << "Actual Scan Rate = " << m_dblValue << '\n';
m_textStream << "Time Since Epoch (ms) \t Voltage (V)" << '\n';
}
else
{
qDebug() << getCurrTimeStr() << "[StartStream] File is closed.";
return false;
}
qDebug() << "Starting timer.";
m_eventTimer->start(m_delayms);
if(m_eventTimer->isActive())
{
qDebug() << "Timer started.";
return true;
}
else
{
qDebug() << getCurrTimeStr() << "[StartStream] m_eventTimer is not active.";
return false;
}
}
else
{
qDebug() << getCurrTimeStr() << "[StartStream] LabJack is not ready.";
return false;
}
}
bool LabJackWorker::StopStream()
{
QMutexLocker locker(&m_mutex); // lock mutex
// mutex unlocks when locker goes out of scope
if(m_eventTimer->isActive())
{
m_eventTimer->stop();
while(m_eventTimer->isActive())
{
; // twiddle thumbs
}
m_lngErrorcode = eGet(m_lngHandle, LJ_ioSTOP_STREAM, 0, 0, 0);
ErrorHandler(m_lngErrorcode, __LINE__, 0);
m_textStream << "Recording stopped at: " << getCurrTimeStr() << '\n\n';
m_textStream.flush();
qDebug() << "Timer stopped.";
return true;
}
else
{
qDebug() << "Timer already stopped.";
return false;
}
}
bool LabJackWorker::DisconnectFromLabJack()
{
bool success = StopStream();
QMutexLocker locker(&m_mutex); // lock mutex
// mutex unlocks when locker goes out of scope
if(m_outputFile.isOpen())
{
m_textStream.flush();
m_outputFile.flush();
m_outputFile.close();
}
else
qDebug() << "textStream is already closed!";
emit finished();
//this->moveToThread(this->thread());
return success;
}
void LabJackWorker::setEpoch(const QTime &epoch)
{
QMutexLocker locker(&m_mutex); // lock mutex
// mutex unlocks when locker goes out of scope
m_epoch = epoch;
}
bool LabJackWorker::workerIsReady()
{
QMutexLocker locker(&m_mutex); // lock mutex
// mutex unlocks when locker goes out of scope
bool result = m_LabJackReady;
return result;
}
bool LabJackWorker::workerIsRecording()
{
QMutexLocker locker(&m_mutex); // lock mutex
// mutex unlocks when locker goes out of scope
bool result = m_eventTimer->isActive();
return result;
}
bool LabJackWorker::ReadStream() {
QTime tmr;
tmr.start();
QMutexLocker locker(&m_mutex); // lock mutex
// mutex unlocks when locker goes out of scope
if(m_LabJackReady)
{
for (m_k = 0; m_k < m_numScans; m_k++)
{
m_adblData[m_k] = 9999.0;
}
//Read the data. We will request twice the number we expect, to
//make sure we get everything that is available.
//Note that the array we pass must be sized to hold enough SAMPLES, and
//the Value we pass specifies the number of SCANS to read.
m_numScansRequested = m_numScans;
m_lngErrorcode = eGet(m_lngHandle, LJ_ioGET_STREAM_DATA, LJ_chALL_CHANNELS,
&m_numScansRequested, m_padblData);
//The displays the number of scans that were actually read.
//printf("\nIteration # %d\n", i);
//printf("Number scans read = %.0f\n", numScansRequested);
//outputFile << "Number scans read = " << numScansRequested << std::endl;
//This displays just the first and last scans.
//printf("First scan = %.3f, %.3f\n", adblData[0], adblData[(int)numScansRequested - 1]);
ErrorHandler(m_lngErrorcode, __LINE__, 0);
//Retrieve the current Comm backlog. The UD driver retrieves stream data from
//the U6 in the background, but if the computer is too slow for some reason
//the driver might not be able to read the data as fast as the U6 is
//acquiring it, and thus there will be data left over in the U6 buffer.
//lngErrorcode = eGet(lngHandle, LJ_ioGET_CONFIG, LJ_chSTREAM_BACKLOG_COMM, &dblCommBacklog, 0);
//printf("Comm Backlog = %.0f\n", dblCommBacklog);
//Retrieve the current UD driver backlog. If this is growing, then the application
//software is not pulling data from the UD driver fast enough.
//lngErrorcode = eGet(lngHandle, LJ_ioGET_CONFIG, LJ_chSTREAM_BACKLOG_UD, &dblUDBacklog, 0);
//printf("UD Backlog = %.0f\n", dblUDBacklog);
double tick = 1000./((double)m_scanRate); // msec
// Write to file
if (m_outputFile.isOpen()) // file is ready
{
for (int idx = 0; idx < m_numScansRequested; idx++)
{
m_textStream << QString::number(m_timeCurr + idx*tick, 'f', 3)
<< '\t' << QString::number(m_adblData[idx], 'f', 6) << '\n';
}
// update current time for next iteration
m_timeCurr += m_numScansRequested*tick;
m_textStream.flush();
m_i++;
qDebug() << "Data acq took (ms): " << tmr.elapsed();
return true;
}
else // file is not ready
{
qDebug() << "Data acq took (ms): " << tmr.elapsed();
return false;
}
}
else // LabJack not ready
{
qDebug() << "Data acq took (ms): " << tmr.elapsed();
return false;
}
}
bool LabJackWorker::ErrorHandler(LJ_ERROR lngErrorcode, long lngLineNumber, long lngIteration)
{
char err[255];
if (lngErrorcode != LJE_NOERROR)
{
ErrorToString(lngErrorcode, err);
qDebug() << "Error number = " << lngErrorcode;
qDebug() << "Error string = " << err;
qDebug() << "Source line number = " << lngLineNumber;
qDebug() << "Iteration = " << lngIteration;
if (lngErrorcode > LJE_MIN_GROUP_ERROR)
{
qDebug() << "FATAL ERROR!";
}
return false; // there was an error
}
else
return true; // no errors - success
}
// ------------------------------------- \\
// -------------- LabJack -------------- \\
// ------------------------------------- \\
LabJack::LabJack(QWidget *parent) :
QWidget(parent),
ui(new Ui::LabJack)
{
ui->setupUi(this);
}
LabJack::~LabJack()
{
if(ui->disconnectButton->isEnabled())
ui->disconnectButton->click();
// if(!workerThread.isNull())
// {
// if(workerThread->isRunning())
// {
// workerThread->quit();
// workerThread->terminate();
// workerThread->wait();
// if(!worker.isNull())
// {
// delete worker;//->deleteLater();
// }
// }
// delete workerThread;//->deleteLater();
// }
// if(!worker.isNull())
// {
// delete worker;//->deleteLater();
// }
delete ui;
}
bool LabJack::isReady()
{
if(workerThread->isRunning())
return worker->workerIsReady();
else
return false;
}
bool LabJack::isRecording()
{
if(workerThread->isRunning())
return worker->workerIsRecording();
else
return false;
}
bool LabJack::setWorkerEpoch(const QTime &epoch)
{
if(workerThread->isRunning())
{
worker->setEpoch(epoch);
return true;
}
else
return false;
}
bool LabJack::setWorkerFileName(const QString &fileName)
{
if(workerThread->isRunning())
{
if(!isRecording())
{
worker->SetFileName(fileName);
return true;
}
else
return false;
}
else
return false;
}
bool LabJack::ConfigureWorker(int samplesPsec)
{
workerThread = new QThread;
worker = new LabJackWorker(samplesPsec);
worker->moveToThread(workerThread);
connect(worker, SIGNAL(finished()), workerThread, SLOT(quit()));
connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
connect(workerThread, SIGNAL(finished()), workerThread, SLOT(deleteLater()));
workerThread->start();
return workerThread->isRunning();
}
void LabJack::on_connectButton_clicked()
{
// get the desired number of samples from the GUI
int samplesPsec = ui->samplesPsecSpinBox->value();
bool result = ConfigureWorker(samplesPsec);
// TODO: EPOCH SHOULD COME FROM MAIN GUI
QTime tmp;
tmp.start();
result = result && setWorkerEpoch(tmp);
// TODO: FILENAME SHOULD COME FROM MAIN GUI
result = result && setWorkerFileName("test.txt");
result = result && worker->ConnectToLabJack();
if( result )
{
// update GUI elements
ui->connectButton->setEnabled(false);
ui->disconnectButton->setEnabled(true);
ui->samplesPsecSpinBox->setEnabled(false);
ui->statusLineEdit->setText("Connected");
ui->initializeLJbutton->setEnabled(true);
}
}
void LabJack::on_disconnectButton_clicked()
{
worker->DisconnectFromLabJack();
// Stop collection, stop thread, delete worker
//worker->StopStream();
// workerThread->quit();
// workerThread->terminate();
// workerThread->wait();
// delete worker;//->deleteLater();
// delete workerThread;//->deleteLater();
// update GUI elements
ui->connectButton->setEnabled(true);
ui->disconnectButton->setEnabled(false);
ui->samplesPsecSpinBox->setEnabled(true);
ui->statusLineEdit->setText("Disconnected");
ui->initializeLJbutton->setEnabled(false);
ui->startRecordButton->setEnabled(false);
ui->stopRecordButton->setEnabled(false);
}
void LabJack::on_initializeLJbutton_clicked()
{
bool result = worker->ConfigureStream();
if( result )
{
// update GUI elements
ui->statusLineEdit->setText("Initialized.");
ui->initializeLJbutton->setEnabled(false);
ui->startRecordButton->setEnabled(true);
ui->stopRecordButton->setEnabled(false);
}
}
void LabJack::on_startRecordButton_clicked()
{
bool result = worker->StartStream();
if( result )
{
// update GUI elements
ui->statusLineEdit->setText("Recording!");
ui->startRecordButton->setEnabled(false);
ui->stopRecordButton->setEnabled(true);
}
}
void LabJack::on_stopRecordButton_clicked()
{
bool result = worker->StopStream();
if( result )
{
// update GUI elements
ui->statusLineEdit->setText("Stopped! Ready.");
ui->startRecordButton->setEnabled(true);
ui->stopRecordButton->setEnabled(false);
}
}
inline const QString getCurrTimeStr()
{
return QTime::currentTime().toString("HH.mm.ss.zzz");
}
inline const QString getCurrDateTimeStr()
{
return QDateTime::currentDateTime().toString("dd/MM/yyyy - hh:mm:ss.zzz");
}
| 17,372 | C++ | 28.445763 | 133 | 0.600679 |
adegirmenci/HBL-ICEbot/old/epos2.cpp | #include "epos2.h"
#include "ui_epos2.h"
#include <QDebug>
epos2::epos2(QWidget *parent) :
QWidget(parent),
ui(new Ui::epos2)
{
ui->setupUi(this);
m_KeyHandle = 0;
//user has to open connection to motors using the GUI
m_motorsEnabled = FALSE;
m_transMotor.m_nodeID = TRANS_MOTOR_ID;
m_pitchMotor.m_nodeID = PITCH_MOTOR_ID;
m_yawMotor.m_nodeID = YAW_MOTOR_ID;
m_rollMotor.m_nodeID = ROLL_MOTOR_ID;
qDebug() << "Initizializing pointers to eposMotor";
m_motors.reserve(4);
m_motors.push_back(QSharedPointer<eposMotor>(&m_transMotor));
m_motors.push_back(QSharedPointer<eposMotor>(&m_pitchMotor));
m_motors.push_back(QSharedPointer<eposMotor>(&m_yawMotor));
m_motors.push_back(QSharedPointer<eposMotor>(&m_rollMotor));
}
epos2::~epos2()
{
on_connectionButtonBox_rejected(); //disable motors and close EPOS connection
m_motors.clear();
qDebug() << "Cleared motor list.";
//VCS_CloseAllDevices(&m_ulErrorCode);
delete ui;
}
BOOL epos2::InitMotor(QSharedPointer<eposMotor> mot)
{
mot.data()->m_bMode = 0;
mot.data()->m_lActualValue = 0;
mot.data()->m_lStartPosition = 0;
mot.data()->m_lTargetPosition = 0;
//mot.data()->m_ulProfileVelocity = EPOS_VELOCITY;
//mot.data()->m_ulProfileAcceleration = EPOS_ACCEL;
//mot.data()->m_ulProfileDeceleration = EPOS_DECEL;
WORD motorID = mot.data()->m_nodeID;
ui->outputText->append(QString("Connecting to Node %1...").arg(motorID));
mot.data()->m_enabled = FALSE;
if(m_KeyHandle)
{
//Clear Error History
if(VCS_ClearFault(m_KeyHandle, motorID, &m_ulErrorCode))
{
//Enable
if( VCS_SetEnableState(m_KeyHandle, motorID, &m_ulErrorCode) )
{
//Read Operation Mode
if(VCS_GetOperationMode(m_KeyHandle, motorID,
&(mot.data()->m_bMode),
&m_ulErrorCode))
{
//Read Position Profile Objects
if(VCS_GetPositionProfile(m_KeyHandle, motorID,
&(mot.data()->m_ulProfileVelocity),
&(mot.data()->m_ulProfileAcceleration),
&(mot.data()->m_ulProfileDeceleration),
&m_ulErrorCode))
{
//Write Profile Position Mode
if(VCS_SetOperationMode(m_KeyHandle, motorID,
OMD_PROFILE_POSITION_MODE,
&m_ulErrorCode))
{
//Write Profile Position Objects
if(VCS_SetPositionProfile(m_KeyHandle, motorID,
EPOS_VELOCITY,
EPOS_ACCEL,
EPOS_DECEL,
&m_ulErrorCode))
{
//Read Actual Position
if(VCS_GetPositionIs(m_KeyHandle, motorID,
&(mot.data()->m_lStartPosition),
&m_ulErrorCode))
{
ui->outputText->append("DONE!");
mot.data()->m_enabled = TRUE;
}
}
}
}
}
}
}
if(!mot.data()->m_enabled)
{
ui->outputText->append("Can't connect to motor!");
ShowErrorInformation(m_ulErrorCode);
}
}
else
{
ui->outputText->append("Can't open device!");
mot.data()->m_enabled = FALSE;
}
return mot.data()->m_enabled;
}
BOOL epos2::DisableMotor(QSharedPointer<eposMotor> mot)
{
WORD nodeId = mot.data()->m_nodeID; //get motor ID
mot.data()->m_enabled = FALSE; // set flag to false
// disable motor
BOOL result = VCS_SetDisableState(m_KeyHandle, nodeId, &m_ulErrorCode);
if(result)
qDebug() <<"Motor " << nodeId << " disabled.";
else
ShowErrorInformation(m_ulErrorCode);
return result;
}
BOOL epos2::OpenDevice() //(WORD motorID)
{
ui->outputText->append("Opening connection to EPOS...");
if(m_KeyHandle)
{
//Close Previous Device
VCS_CloseDevice(m_KeyHandle, &m_ulErrorCode);
m_KeyHandle = 0;
}
else
m_KeyHandle = 0;
//Settings
m_oImmediately = TRUE;
m_oUpdateActive = FALSE;
HANDLE hNewKeyHandle;
hNewKeyHandle = VCS_OpenDeviceDlg(&m_ulErrorCode);
if(hNewKeyHandle)
m_KeyHandle = hNewKeyHandle;
else
return FALSE;
// Set properties of each motor
BOOL initSuccess = TRUE;
initSuccess = initSuccess && InitMotor(m_motors[TRANS]);
initSuccess = initSuccess && InitMotor(m_motors[PITCH]);
initSuccess = initSuccess && InitMotor(m_motors[YAW]);
initSuccess = initSuccess && InitMotor(m_motors[ROLL]);
return initSuccess;
}
void epos2::moveMotor(long targetPos, QSharedPointer<eposMotor> mot, BOOL moveAbsOrRel)
{
if(moveAbsOrRel)
mot.data()->m_lTargetPosition = targetPos;
else
mot.data()->m_lTargetPosition += targetPos;
WORD usNodeId = mot.data()->m_nodeID;
QElapsedTimer elTimer;
qDebug() << "Using clock type " << elTimer.clockType();
elTimer.start();
if(mot.data()->m_enabled)
{
if(!VCS_MoveToPosition(m_KeyHandle, usNodeId, targetPos, moveAbsOrRel, m_oImmediately, &m_ulErrorCode))
{
ShowErrorInformation(m_ulErrorCode);
}
}
qDebug() << "Elapsed Time: " << elTimer.nsecsElapsed()/1000000. << " ms";
getMotorQC(mot);
}
void epos2::getMotorQC(QSharedPointer<eposMotor> mot)
{
WORD usNodeId = mot.data()->m_nodeID;
QElapsedTimer elTimer;
elTimer.start();
if(!VCS_GetPositionIs(m_KeyHandle, usNodeId, &(mot.data()->m_lStartPosition), &m_ulErrorCode))
{
ShowErrorInformation(m_ulErrorCode);
}
qDebug() << "Elapsed Time: " << elTimer.nsecsElapsed()/1000000. << " ms";
qDebug() << "Motor is at " << mot.data()->m_lStartPosition << " qc";
}
void epos2::haltMotor(QSharedPointer<eposMotor> mot)
{
WORD usNodeId = mot.data()->m_nodeID;
if(!VCS_HaltPositionMovement(m_KeyHandle, usNodeId, &m_ulErrorCode))
{
ShowErrorInformation(m_ulErrorCode);
}
}
BOOL epos2::ShowErrorInformation(DWORD p_ulErrorCode)
{
char* pStrErrorInfo;
const char* strDescription;
if((pStrErrorInfo = (char*)malloc(100)) == NULL)
{
qDebug() << "Not enough memory to allocate buffer for error information string.";
return FALSE;
}
if(VCS_GetErrorInfo(p_ulErrorCode, pStrErrorInfo, 100))
{
strDescription = pStrErrorInfo;
qDebug() << "Maxon: " << strDescription;
free(pStrErrorInfo);
return TRUE;
}
else
{
free(pStrErrorInfo);
qDebug() << "Error information can't be read!";
return FALSE;
}
}
void epos2::on_connectionButtonBox_accepted()
{
if(OpenDevice())
{
m_motorsEnabled = TRUE;
ui->enableNodeButton->setEnabled(false);
ui->disableNodeButton->setEnabled(true);
ui->moveAbsButton->setEnabled(true);
ui->moveRelButton->setEnabled(true);
ui->haltButton->setEnabled(true);
ui->homingButton->setEnabled(true);
}
else
{
m_motorsEnabled = FALSE;
ui->enableNodeButton->setEnabled(true);
ui->disableNodeButton->setEnabled(false);
ui->moveAbsButton->setEnabled(false);
ui->moveRelButton->setEnabled(false);
ui->haltButton->setEnabled(false);
ui->homingButton->setEnabled(false);
}
}
void epos2::on_connectionButtonBox_rejected()
{
m_motorsEnabled = FALSE;
if(m_KeyHandle)
{
for(int i = 0; i < 4; i++)
{
DisableMotor(m_motors[i]);
}
qDebug() << "Motors disabled.";
if(VCS_CloseDevice(m_KeyHandle, &m_ulErrorCode))
{
m_KeyHandle = 0;
qDebug() << "EPOS closed successfully.";
ui->outputText->append("Closed.\n");
ui->enableNodeButton->setEnabled(false);
ui->disableNodeButton->setEnabled(false);
ui->moveAbsButton->setEnabled(false);
ui->moveRelButton->setEnabled(false);
ui->haltButton->setEnabled(false);
ui->homingButton->setEnabled(false);
}
else
ShowErrorInformation(m_ulErrorCode);
}
else
{
ui->outputText->append("EPOS is already closed.\n");
ui->enableNodeButton->setEnabled(false);
ui->disableNodeButton->setEnabled(false);
ui->moveAbsButton->setEnabled(false);
ui->moveRelButton->setEnabled(false);
ui->haltButton->setEnabled(false);
ui->homingButton->setEnabled(false);
}
//VCS_CloseAllDevices(&m_ulErrorCode);
}
void epos2::on_enableNodeButton_clicked()
{
int selection = ui->nodeIDcomboBox->currentIndex();
if(InitMotor(m_motors[selection]))
{
ui->enableNodeButton->setEnabled(false);
ui->disableNodeButton->setEnabled(true);
ui->moveAbsButton->setEnabled(true);
ui->moveRelButton->setEnabled(true);
ui->haltButton->setEnabled(true);
ui->homingButton->setEnabled(true);
}
}
void epos2::on_disableNodeButton_clicked()
{
int selection = ui->nodeIDcomboBox->currentIndex();
if(DisableMotor(m_motors[selection]))
{
ui->enableNodeButton->setEnabled(true);
ui->disableNodeButton->setEnabled(false);
ui->moveAbsButton->setEnabled(false);
ui->moveRelButton->setEnabled(false);
ui->haltButton->setEnabled(false);
ui->homingButton->setEnabled(false);
}
}
void epos2::on_moveAbsButton_clicked()
{
int selection = ui->nodeIDcomboBox->currentIndex();
long counts = (long)ui->targetQClineEdit->value();
qDebug() << "Moving motor " << m_motors[selection].data()->m_nodeID << " to " << counts;
moveMotor(counts, m_motors[selection], true);
}
void epos2::on_moveRelButton_clicked()
{
int selection = ui->nodeIDcomboBox->currentIndex();
long counts = (long)ui->targetQClineEdit->value();
moveMotor(counts, m_motors[selection], false);
}
void epos2::on_nodeIDcomboBox_currentIndexChanged(int index)
{
if(m_motors[index].data()->m_enabled)
{
ui->enableNodeButton->setEnabled(false);
ui->disableNodeButton->setEnabled(true);
ui->moveAbsButton->setEnabled(true);
ui->moveRelButton->setEnabled(true);
ui->haltButton->setEnabled(true);
ui->homingButton->setEnabled(true);
}
else
{
ui->enableNodeButton->setEnabled(true);
ui->disableNodeButton->setEnabled(false);
ui->moveAbsButton->setEnabled(false);
ui->moveRelButton->setEnabled(false);
ui->haltButton->setEnabled(false);
ui->homingButton->setEnabled(false);
}
}
void epos2::on_haltButton_clicked()
{
int selection = ui->nodeIDcomboBox->currentIndex();
haltMotor(m_motors[selection]);
}
void epos2::on_homingButton_clicked()
{
long homepos[4]={0, 0, 0, 0};
// set a lower speed
for(int i = 0; i < 4; i++)
{
WORD nodeID = m_motors[i].data()->m_nodeID;
if(!VCS_SetPositionProfile(m_KeyHandle,nodeID,
1400,2000,2000,&m_ulErrorCode))
{
ShowErrorInformation(m_ulErrorCode);
}
}
for(int i = 0; i < 4; i++)
{
WORD nodeID = m_motors[i].data()->m_nodeID;
if(!VCS_MoveToPosition(m_KeyHandle,nodeID,homepos[i],true,true,&m_ulErrorCode))
{
ShowErrorInformation(m_ulErrorCode);
}
}
//TODO: reset the motor limits since roll is back to zero
//------
// reset the profile
for(int i = 0; i < 4; i++)
{
WORD nodeID = m_motors[i].data()->m_nodeID;
if(!VCS_SetPositionProfile(m_KeyHandle,nodeID,
EPOS_VELOCITY,EPOS_ACCEL,EPOS_DECEL,
&m_ulErrorCode))
{
ShowErrorInformation(m_ulErrorCode);
}
}
}
| 12,675 | C++ | 28.686183 | 111 | 0.559132 |
adegirmenci/HBL-ICEbot/old/SharedPoint.cpp | #include "SharedPoint.h"
class SharedPointData : public QSharedData
{
public:
SharedPointData()
{
m_x = 0.0;
m_y = 0.0;
m_z = 0.0;
}
SharedPointData(double x, double y, double z)
{
m_x = x;
m_y = y;
m_z = z;
}
SharedPointData(const SharedPointData &rhs)
: QSharedData(rhs)
{
m_x = rhs.m_x;
m_y = rhs.m_y;
m_z = rhs.m_z;
}
~SharedPointData() {}
double m_x;
double m_y;
double m_z;
};
// Zero Constructor
SharedPoint::SharedPoint() : data(new SharedPointData) {}
// Constructor
SharedPoint::SharedPoint(double x, double y, double z)
{
data( new SharedPointData(x, y, z) );
}
// Copy
SharedPoint::SharedPoint(const SharedPoint &rhs) : data(rhs.data) {}
// Copy
SharedPoint &SharedPoint::operator=(const SharedPoint &rhs)
{
if (this != &rhs)
data.operator=(rhs.data);
return *this;
}
// Destructor
SharedPoint::~SharedPoint() {}
SharedPoint SharedPoint::update(double px, double py, double pz)
{
this->setx(px);
this->sety(py);
this->setz(pz);
return this;
}
// Distance to another point. Pythagorean thm.
double SharedPoint::dist(SharedPoint& other) {
double xd = this->getx() - other.getx();
double yd = this->gety() - other.gety();
double zd = this->getz() - other.getz();
return sqrt(xd*xd + yd*yd + zd*zd);
}
SharedPoint SharedPoint::operator+(const SharedPoint& b) const
{
return SharedPoint(this->getx() + b.getx(),
this->gety() + b.gety(),
this->getz() + b.getz());
}
SharedPoint SharedPoint::operator-(const SharedPoint& b) const
{
return SharedPoint(this->getx() - b.getx(),
this->gety() - b.gety(),
this->getz() - b.getz());
}
SharedPoint SharedPoint::operator*(const double k) const
{
return SharedPoint(this->getx()*k,
this->gety()*k,
this->getz()*k);
}
SharedPoint SharedPoint::operator/(const double k) const
{
return SharedPoint(this->getx()/k,
this->gety()/k,
this->getz()/k);
}
void SharedPoint::move(double a, double b, double c)
{
this->setx(this->getx() + a);
this->sety(this->gety() + b);
this->setz(this->getz() + c);
}
| 2,357 | C++ | 20.833333 | 68 | 0.557488 |
adegirmenci/HBL-ICEbot/old/epos2.h | #ifndef EPOS2_H
#define EPOS2_H
#include <QWidget>
#include <QSharedPointer>
#include <QList>
#include <QElapsedTimer>
#include "MaxonLibs/Definitions.h"
#include <stdio.h>
#include <Windows.h>
#define EPOS_VELOCITY 5000
#define EPOS_ACCEL 8000
#define EPOS_DECEL 8000
// node ID's for motors
#define TRANS_MOTOR_ID 1
#define PITCH_MOTOR_ID 2
#define YAW_MOTOR_ID 3
#define ROLL_MOTOR_ID 4
// indices for the motor in list
#define TRANS 0
#define PITCH 1
#define YAW 2
#define ROLL 3
struct eposMotor
{
__int8 m_bMode;
WORD m_nodeID; // motor ID
DWORD m_ulProfileAcceleration; // acceleration value
DWORD m_ulProfileDeceleration; // deceleration value
DWORD m_ulProfileVelocity; // velocity value
BOOL m_enabled;
long m_lActualValue; // volatile?
long m_lStartPosition; // volatile?
long m_lTargetPosition; // volatile?
long m_maxQC; // upper limit
long m_minQC; // lower limit
};
namespace Ui {
class epos2;
}
class epos2 : public QWidget
{
Q_OBJECT
public:
explicit epos2(QWidget *parent = 0);
~epos2();
long m_lActualValue;
long m_lStartPosition;
long m_lTargetPosition;
void moveMotor(long targetPos, QSharedPointer<eposMotor> mot, BOOL moveAbsOrRel);
void getMotorQC(QSharedPointer<eposMotor> mot);
void haltMotor(QSharedPointer<eposMotor> mot);
BOOL m_motorsEnabled;
private slots:
void on_connectionButtonBox_accepted();
void on_connectionButtonBox_rejected();
void on_enableNodeButton_clicked();
void on_disableNodeButton_clicked();
void on_moveAbsButton_clicked();
void on_nodeIDcomboBox_currentIndexChanged(int index);
void on_moveRelButton_clicked();
void on_haltButton_clicked();
void on_homingButton_clicked();
private:
Ui::epos2 *ui;
BOOL OpenDevice();
BOOL InitMotor(QSharedPointer<eposMotor> mot);
BOOL DisableMotor(QSharedPointer<eposMotor> mot);
BOOL ShowErrorInformation(DWORD p_ulErrorCode);
BOOL m_oImmediately;
BOOL m_oInitialisation;
BOOL m_oUpdateActive;
DWORD m_ulErrorCode;
HANDLE m_KeyHandle;
QList<QSharedPointer<eposMotor>> m_motors;
eposMotor m_transMotor;
eposMotor m_pitchMotor;
eposMotor m_yawMotor;
eposMotor m_rollMotor;
};
#endif // EPOS2_H
| 2,293 | C | 20.045871 | 85 | 0.706934 |
adegirmenci/HBL-ICEbot/old/SharedPoint.h | #ifndef SHAREDPOINT_H
#define SHAREDPOINT_H
#include <QSharedDataPointer>
class SharedPointData;
class SharedPoint
{
public:
SharedPoint();
SharedPoint(double x, double y, double z);
SharedPoint(const SharedPoint& rhs);
SharedPoint &operator=(const SharedPoint& rhs);
~SharedPoint();
// modifiers
void setx(double pk) { data->m_x = pk; }
void sety(double pk) { data->m_y = pk; }
void setz(double pk) { data->m_z = pk; }
// accessors
double getx() const { return data->m_x; }
double gety() const { return data->m_y; }
double getz() const { return data->m_z; }
SharedPoint update(double px, double py, double pz);
double dist(SharedPoint& other);
SharedPoint operator+(const SharedPoint& b) const;
SharedPoint operator-(const SharedPoint& b) const;
SharedPoint operator*(const double k) const;
SharedPoint operator/(const double k) const;
void move(double a, double b, double c);
signals:
public slots:
private:
QSharedDataPointer<SharedPointData> data;
};
#endif // SHAREDPOINT_H
| 1,074 | C | 22.888888 | 56 | 0.675047 |
adegirmenci/HBL-ICEbot/SceneVizWidget/usentity.h | #ifndef USENTITY_H
#define USENTITY_H
#include <QtCore/QObject>
#include <Qt3DCore/qentity.h>
#include <QFileInfo>
#include <QUrl>
#include <Qt3DCore/qtransform.h>
#include <QVector3D>
#include <QQuaternion>
#include <QtCore/QVector>
#include <QtCore/QDebug>
#include <QColor>
#include <Qt3DRender/qmesh.h>
#include <Qt3DRender/qtextureimage.h>
#include <Qt3DExtras/qdiffusemapmaterial.h>
#include <Qt3DRender/qcullface.h>
#include <Qt3DRender/qdepthtest.h>
#include <QSharedPointer>
#include <Qt3DRender/qeffect.h>
#include <Qt3DRender/qtechnique.h>
#include <Qt3DRender/qrenderpass.h>
#include <Qt3DRender/qrenderstate.h>
#include <QDir>
class usEntity : public Qt3DCore::QEntity
{
Q_OBJECT
public:
explicit usEntity(QEntity *parent = nullptr);
~usEntity();
QVector3D getTranslation() { return m_usTransforms->translation(); }
QQuaternion getRotation() { return m_usTransforms->rotation(); }
// signals:
public slots:
// setDisplayed // implemented by QEntity
void translate(QVector3D &trans);
void rotate(QQuaternion &rot);
void setTransformation(Qt3DCore::QTransform &tform);
private:
Qt3DRender::QMesh *m_usMesh;
QVector<Qt3DCore::QEntity *> m_usEntityList;
Qt3DRender::QTextureImage *m_usImage;
Qt3DExtras::QDiffuseMapMaterial *m_usMaterial;
Qt3DCore::QTransform *m_usTransforms;
bool isShown;
};
#endif // USENTITY_H
| 1,452 | C | 22.063492 | 72 | 0.710055 |
adegirmenci/HBL-ICEbot/SceneVizWidget/extendedqt3dwindow.cpp | #include "extendedqt3dwindow.h"
ExtendedQt3DWindow::ExtendedQt3DWindow(QScreen *screen) : Qt3DExtras::Qt3DWindow(screen)
{
qRegisterMetaType< QSharedPointer<QWheelEvent> >("QSharedPointer<QWheelEvent>");
}
void ExtendedQt3DWindow::wheelEvent(QWheelEvent *event)
{
emit wheelScrolled(QSharedPointer<QWheelEvent>( new QWheelEvent(*event) ));
event->accept();
}
| 374 | C++ | 25.785712 | 88 | 0.770053 |
adegirmenci/HBL-ICEbot/SceneVizWidget/triadentity.h | #ifndef TRIADENTITY_H
#define TRIADENTITY_H
#include <QtCore/QObject>
#include <Qt3DCore/qentity.h>
#include <QFileInfo>
#include <QUrl>
#include <Qt3DCore/qtransform.h>
#include <QVector3D>
#include <QQuaternion>
#include <QtCore/QVector>
#include <QtCore/QDebug>
#include <QColor>
#include <Qt3DRender/qmesh.h>
#include <QSharedPointer>
#include <Qt3DExtras/QPhongMaterial>
#include <Qt3DExtras/QGoochMaterial>
//typedef QVector<QComponent*> QComponentVector;
class TriadEntity : public Qt3DCore::QEntity
{
Q_OBJECT
public:
explicit TriadEntity(QEntity *parent = nullptr);
~TriadEntity();
QVector3D getTranslation() { return m_triadTransforms->translation(); }
QQuaternion getRotation() { return m_triadTransforms->rotation(); }
// signals:
public slots:
// setDisplayed // implemented by QEntity
void translate(const QVector3D &trans);
void rotate(const QQuaternion &rot);
void setTransformation(const Qt3DCore::QTransform &tform);
private:
Qt3DRender::QMesh *m_arrowMesh;
//QSharedPointer<Qt3DRender::QMesh> arrowMesh;
QVector<Qt3DCore::QEntity *> m_arrowEntityList;
Qt3DCore::QTransform *m_triadTransforms;
bool isShown;
};
#endif // TRIADENTITY_H
| 1,225 | C | 20.892857 | 75 | 0.736327 |
adegirmenci/HBL-ICEbot/SceneVizWidget/usentity.cpp | #include "usentity.h"
usEntity::usEntity(Qt3DCore::QEntity *parent) : Qt3DCore::QEntity(parent)
, m_usTransforms(new Qt3DCore::QTransform())
, m_usMaterial(new Qt3DExtras::QDiffuseMapMaterial())
, m_usImage(new Qt3DRender::QTextureImage())
, m_usMesh(new Qt3DRender::QMesh())
{
// LOAD MESH
m_usMesh->setMeshName("USplane");
QFileInfo check_file( QStringLiteral("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\SceneVizWidget\\ultrasound2.obj") );
if( check_file.exists() && check_file.isFile() )
{
m_usMesh->setSource(QUrl::fromLocalFile(check_file.absoluteFilePath()));
qDebug() << "Loaded ultrasound mesh.";
}
else
{
qDebug() << "Ultrasound mesh file doesn't exist!";
}
// LOAD MESH DONE
// SET GLOBAL TRANSFORM
m_usTransforms->setTranslation(QVector3D(0.0f, 0.0f, 0.0f));
m_usTransforms->setRotation( QQuaternion::fromAxisAndAngle(QVector3D(1, 0, 0),0.0f) );
this->addComponent(m_usTransforms);
// SET GLOBAL TRANSFORM DONE
// SET ULTRASOUND IMAGE AS TEXTURE
check_file.setFile(QStringLiteral("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\SceneVizWidget\\1.jpg"));
if( check_file.exists() && check_file.isFile() )
{
m_usImage->setSource(QUrl::fromLocalFile(check_file.absoluteFilePath()));
qDebug() << "Loaded ultrasound image.";
}
else
{
qDebug() << "Ultrasound image file doesn't exist!";
}
m_usMaterial->diffuse()->addTextureImage(m_usImage);
m_usMaterial->setShininess(10.0f);
m_usMaterial->setSpecular(QColor::fromRgbF(0.75f, 0.75f, 0.75f, 1.0f));
//m_usMaterial->diffuse()->setSize(720,480);
// SET ULTRASOUND IMAGE AS TEXTURE DONE
// m_usMaterial->setSpecular(Qt::gray);
// m_usMaterial->setAmbient(Qt::gray);
// m_usMaterial->setShininess(10.0f);
// m_usMaterial->setTextureScale(0.01f);
// Begin: No culling
// Access the render states of the material
Qt3DRender::QEffect *effect_ = m_usMaterial->effect();
QVector<Qt3DRender::QTechnique *> tqs = effect_->techniques();
if(tqs.size() > 0)
{
QVector<Qt3DRender::QRenderPass *> rps = tqs[0]->renderPasses();
if(rps.size() > 0)
{
QVector<Qt3DRender::QRenderState *> rss = rps[0]->renderStates();
if(rss.size() > 0)
{
qDebug() << "A render state already exists:" << rss[0]->objectName();
}
else
{
Qt3DRender::QCullFace *cullFront = new Qt3DRender::QCullFace();
cullFront->setMode(Qt3DRender::QCullFace::NoCulling);
rps[0]->addRenderState(cullFront);
Qt3DRender::QDepthTest *depthTest = new Qt3DRender::QDepthTest();
depthTest->setDepthFunction(Qt3DRender::QDepthTest::LessOrEqual);
rps[0]->addRenderState(depthTest);
}
}
else
qDebug() << "No renderPasses.";
}
else
qDebug() << "No techniques.";
// End: No culling
// ADD MESH TO ULTRASOUND ENTITY
qDebug() << "Adding meshes to usEntityList.";
m_usEntityList.fill(new Qt3DCore::QEntity(this), 1);
for(int i = 0; i < m_usEntityList.size(); i++)
{
//m_usEntityList.replace(i, new Qt3DCore::QEntity(this));
Qt3DCore::QTransform *usTransforms = new Qt3DCore::QTransform();
usTransforms->setTranslation(QVector3D(0.0f, 0.0f, 0.0f));
usTransforms->setRotation( QQuaternion::fromAxisAndAngle(QVector3D(0, 1, 0),90.0f) );
usTransforms->setScale3D(QVector3D(10,10,10));
m_usEntityList[i]->addComponent(m_usMesh);
m_usEntityList[i]->addComponent(m_usMaterial);
m_usEntityList[i]->addComponent(usTransforms);
}
qDebug() << "Adding meshes done.";
}
usEntity::~usEntity()
{
qDebug() << "Destroying usEntity.";
qDebug() << m_usImage->status();
// m_usMesh->deleteLater();
// m_usImage->deleteLater();
// m_usMaterial->deleteLater();
// m_usTransforms->deleteLater();
}
void usEntity::translate(QVector3D &trans)
{
m_usTransforms->setTranslation(trans);
}
void usEntity::rotate(QQuaternion &rot)
{
m_usTransforms->setRotation(rot);
}
void usEntity::setTransformation(Qt3DCore::QTransform &tform)
{
m_usTransforms->setMatrix(tform.matrix());
}
| 4,553 | C++ | 33.763359 | 136 | 0.599824 |
adegirmenci/HBL-ICEbot/SceneVizWidget/scenemodifier.h | #ifndef SCENEMODIFIER_H
#define SCENEMODIFIER_H
#include <QtCore/QObject>
#include <iostream>
#include <Qt3DCore/qentity.h>
#include <Qt3DCore/qtransform.h>
#include <QMatrix4x4>
#include <QtCore/QVector>
#include <QtCore/QHash>
#include <QtCore/QDebug>
#include <QSharedPointer>
#include <QVector3D>
#include <QTime>
#include "../icebot_definitions.h"
#include "../AscensionWidget/3DGAPI/ATC3DG.h"
#include "triadentity.h"
#include "usentity.h"
class SceneModifier : public QObject
{
Q_OBJECT
public:
explicit SceneModifier(Qt3DCore::QEntity *rootEntity);
~SceneModifier();
QVector3D getTriadPosition(EM_SENSOR_IDS sensorID);
signals:
public slots:
void enableObject(bool enabled, int objID);
void receiveEMreading(QTime timeStamp,
int sensorID,
DOUBLE_POSITION_MATRIX_TIME_Q_RECORD data);
void receiveEMreading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> data);
void resetBase();
void changeTFormOption(int opt);
void setUSangle(int ang);
private:
QVector<Qt3DCore::QEntity *> m_entityList;
QHash<QString, int> m_entityHash; // look up entities by name
Qt3DCore::QEntity *m_rootEntity;
QMatrix4x4 m_calibMat;
Qt3DCore::QTransform m_Box_US; // Emitter to US crystal transforms
QMatrix4x4 m_T_Box_EM;
QMatrix4x4 m_T_EM_CT;
Qt3DCore::QTransform m_CT_US;
QMatrix4x4 m_baseEMpose; // for relative stuff
int m_tformOption;
float m_usAngle;
};
// TRIADOBJECT
#endif // SCENEMODIFIER_H
| 1,539 | C | 21.985074 | 82 | 0.701754 |
adegirmenci/HBL-ICEbot/SceneVizWidget/scenevizwidget.h | #ifndef SCENEVIZWIDGET_H
#define SCENEVIZWIDGET_H
/*!
* Written by Alperen Degirmenci
* Harvard Biorobotics Laboratory
*/
#include <QWidget>
#include <Qt3DRender/qcamera.h>
#include <Qt3DCore/qentity.h>
#include <Qt3DRender/qcameralens.h>
#include <QtWidgets/QWidget>
#include <QtWidgets/QHBoxLayout>
#include <QtGui/QScreen>
#include <Qt3DInput/QInputAspect>
#include <Qt3DInput/QWheelEvent>
#include <Qt3DExtras/qtorusmesh.h>
#include <Qt3DRender/qmesh.h>
#include <Qt3DRender/qtechnique.h>
#include <Qt3DRender/qmaterial.h>
#include <Qt3DRender/qeffect.h>
#include <Qt3DRender/qtexture.h>
#include <Qt3DRender/qrenderpass.h>
#include <Qt3DRender/qsceneloader.h>
#include <Qt3DCore/qtransform.h>
#include <Qt3DCore/qaspectengine.h>
#include <Qt3DRender/qrenderaspect.h>
#include <Qt3DExtras/qforwardrenderer.h>
#include <Qt3DExtras/qt3dwindow.h>
#include <Qt3DExtras/qorbitcameracontroller.h>
#include "scenemodifier.h"
#include "extendedqt3dwindow.h"
namespace Ui {
class SceneVizWidget;
}
class SceneVizWidget : public QWidget
{
Q_OBJECT
public:
explicit SceneVizWidget(QWidget *parent = 0);
~SceneVizWidget();
// Scenemodifier
SceneModifier *m_modifier;
private slots:
void on_toggleRenderWindowButton_clicked();
void acceptScroll(QSharedPointer<QWheelEvent> event);
void on_baseCheckBox_toggled(bool checked);
void on_pushButton_clicked();
void on_resetBaseButton_clicked();
void on_noTformRadio_clicked();
void on_tform1Radio_clicked();
void on_tform2Radio_clicked();
void on_usAngleSpinBox_valueChanged(int arg1);
void on_tipCheckBox_toggled(bool checked);
void on_instrCheckBox_toggled(bool checked);
void on_chestCheckBox_toggled(bool checked);
private:
Ui::SceneVizWidget *ui;
ExtendedQt3DWindow *m_view; //Qt3DExtras::Qt3DWindow *view;
QWidget *m_container;
QSize m_screenSize;
QWidget *m_widget;
QHBoxLayout *m_hLayout;
QVBoxLayout *m_vLayout;
Qt3DInput::QInputAspect *m_input;
Qt3DCore::QEntity *m_rootEntity;
Qt3DRender::QCamera *m_cameraEntity;
Qt3DExtras::QOrbitCameraController *m_camController;
bool m_isShown;
protected:
// void wheelEvent(QWheelEvent *event);
};
#endif // SCENEVIZWIDGET_H
| 2,263 | C | 20.980582 | 63 | 0.743261 |
adegirmenci/HBL-ICEbot/SceneVizWidget/scenemodifier.cpp | #include "scenemodifier.h"
SceneModifier::SceneModifier(Qt3DCore::QEntity *rootEntity)
: m_rootEntity(rootEntity)
{
// Y axis points up in OpenGL renderer
m_entityList.append(new TriadEntity(m_rootEntity));
m_entityList.append(new TriadEntity(m_rootEntity));
m_entityList.append(new TriadEntity(m_rootEntity));
m_entityList.append(new TriadEntity(m_rootEntity));
m_entityList.append(new TriadEntity(m_rootEntity));
//m_entityList.append(new usEntity(m_rootEntity));
m_entityList.append(new usEntity(m_entityList[1])); // US plane attached to the BT
static_cast<TriadEntity*>(m_entityList[0])->translate(QVector3D(0.0f, 0.0f, 0.0f));
// EM_SENSOR_BB
m_entityList[0]->setEnabled(false);
m_entityList[1]->setEnabled(false);
m_entityList[2]->setEnabled(false);
m_entityList[3]->setEnabled(false);
m_entityList[4]->setEnabled(true); // EM Box
m_entityList[5]->setEnabled(true); // US plane
Qt3DCore::QTransform tf;
tf.setTranslation(QVector3D(0,0,0));
static_cast<TriadEntity*>(m_entityList[4])->setTransformation(tf);
static_cast<usEntity*>(m_entityList[5])->setTransformation(tf);
//static_cast<usEntity*>(m_entityList[5])->setProperty();
// dummy
m_baseEMpose = tf.matrix();
Qt3DCore::QTransform calib;
calib.setRotation(QQuaternion(0.0098f, -0.0530f, -0.9873f, -0.1492f));
m_calibMat = calib.matrix();
m_tformOption = 0;
// QMatrix4x4 T_Box_EM(-1, 0, 0, 0,
// 0, 0, -1, 0,
// 0, -1, 0, 0,
// 0, 0, 0, 1);
m_T_Box_EM = QMatrix4x4(0, 0, 1, 0,
0, -1, 0, 0,
1, 0, 0, 0,
0, 0, 0, 1);
m_T_EM_CT = QMatrix4x4(1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 14.5,
0, 0, 0, 1);
m_CT_US.setRotationZ(0);
m_Box_US.setMatrix(m_T_Box_EM * m_T_EM_CT * m_CT_US.matrix()); //T_Box_EM
}
SceneModifier::~SceneModifier()
{
//m_entityList.clear();
}
QVector3D SceneModifier::getTriadPosition(EM_SENSOR_IDS sensorID)
{
return static_cast<TriadEntity*>(m_entityList[sensorID])->getTranslation();
}
void SceneModifier::enableObject(bool enabled, int objID)
{
// // Look at this example for creating object classes
// // http://doc.qt.io/qt-5/qt3drenderer-materials-cpp-barrel-cpp.html
// // arrow class can be useful to create triads, and then a triad class
Q_ASSERT(objID < m_entityList.size());
m_entityList[objID]->setEnabled(enabled);
}
void SceneModifier::receiveEMreading(QTime timeStamp, int sensorID, DOUBLE_POSITION_MATRIX_TIME_Q_RECORD data)
{
QMatrix4x4 tmp(data.s[0][0], data.s[0][1], data.s[0][2], data.x,
data.s[1][0], data.s[1][1], data.s[1][2], data.y,
data.s[2][0], data.s[2][1], data.s[2][2], data.z,
0.0, 0.0, 0.0, 1.0);
Qt3DCore::QTransform tf;
tf.setMatrix(tmp);
// tf.setRotation(QQuaternion(data.q[0],data.q[1],data.q[2],data.q[3]));
// tf.setTranslation(QVector3D(data.x,data.y,data.z));
if(m_tformOption == 0)
tf.setMatrix(tf.matrix());
else if(m_tformOption == 1)
tf.setMatrix(m_calibMat*tf.matrix()*m_Box_US.matrix());
else if(m_tformOption == 2)
tf.setMatrix(m_baseEMpose.inverted()*m_T_Box_EM.inverted() * tf.matrix()*m_Box_US.matrix());
else
tf.setMatrix(tf.matrix());
static_cast<TriadEntity*>(m_entityList[sensorID])->setTransformation(tf);
// static_cast<TriadEntity*>(m_entityList[sensorID])->rotate(QQuaternion(data.q[0],data.q[1],data.q[2],data.q[3]));
// static_cast<TriadEntity*>(m_entityList[sensorID])->translate(QVector3D(data.x,data.y,data.z));
}
void SceneModifier::receiveEMreading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> data)
{
Q_ASSERT(data.size() == 4);
for(size_t i = 0; i < data.size(); i++)
{
QMatrix4x4 tmp(data[i].s[0][0], data[i].s[0][1], data[i].s[0][2], data[i].x,
data[i].s[1][0], data[i].s[1][1], data[i].s[1][2], data[i].y,
data[i].s[2][0], data[i].s[2][1], data[i].s[2][2], data[i].z,
0.0, 0.0, 0.0, 1.0);
Qt3DCore::QTransform tf;
tf.setMatrix(tmp);
if(m_tformOption == 0)
tf.setMatrix(tf.matrix());
else if(m_tformOption == 1)
tf.setMatrix(m_calibMat*tf.matrix()*m_Box_US.matrix());
else if(m_tformOption == 2)
tf.setMatrix(m_baseEMpose.inverted()*m_T_Box_EM.inverted() * tf.matrix()*m_Box_US.matrix());
else
tf.setMatrix(tf.matrix());
static_cast<TriadEntity*>(m_entityList[i])->setTransformation(tf);
}
}
void SceneModifier::resetBase()
{
Qt3DCore::QTransform tf;
tf.setRotation(static_cast<TriadEntity*>(m_entityList[EM_SENSOR_BB])->getRotation());
tf.setTranslation(static_cast<TriadEntity*>(m_entityList[EM_SENSOR_BB])->getTranslation());
m_baseEMpose = tf.matrix();
}
void SceneModifier::changeTFormOption(int opt)
{
std::cout << "m_tformOption changed to " << opt << std::endl;
m_tformOption = opt;
}
void SceneModifier::setUSangle(int ang)
{
std::cout << "US angle changed to " << ang << std::endl;
m_usAngle = ang;
m_CT_US.setRotationZ(m_usAngle);
m_Box_US.setMatrix(m_T_Box_EM * m_T_EM_CT * m_CT_US.matrix()); //T_Box_EM
}
| 5,524 | C++ | 33.53125 | 118 | 0.588342 |
adegirmenci/HBL-ICEbot/SceneVizWidget/extendedqt3dwindow.h | #ifndef EXTENDEDQT3DWINDOW_H
#define EXTENDEDQT3DWINDOW_H
#include <QObject>
#include <QDebug>
#include <QScreen>
#include <Qt3DExtras/Qt3DWindow>
#include <Qt3DInput/QWheelEvent>
#include <QSharedPointer>
Q_DECLARE_METATYPE(QSharedPointer<QWheelEvent>)
class ExtendedQt3DWindow : public Qt3DExtras::Qt3DWindow
{
Q_OBJECT
public:
ExtendedQt3DWindow(QScreen *screen = nullptr);
signals:
void wheelScrolled(QSharedPointer<QWheelEvent> event);
protected:
void wheelEvent(QWheelEvent *event);
};
#endif // EXTENDEDQT3DWINDOW_H
| 547 | C | 17.896551 | 58 | 0.775137 |
adegirmenci/HBL-ICEbot/SceneVizWidget/scenevizwidget.cpp | #include "scenevizwidget.h"
#include "ui_scenevizwidget.h"
SceneVizWidget::SceneVizWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::SceneVizWidget)
{
ui->setupUi(this);
m_view = new ExtendedQt3DWindow(); //view = new Qt3DExtras::Qt3DWindow();
m_view->defaultFrameGraph()->setClearColor(QColor(QRgb(0x4d4d4f)));
m_container = QWidget::createWindowContainer(m_view);
m_container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
m_widget = ui->dockWidgetContents;
m_hLayout = new QHBoxLayout(m_widget);
m_vLayout = new QVBoxLayout();
m_vLayout->setAlignment(Qt::AlignTop);
m_hLayout->addWidget(m_container, 1);
m_hLayout->addLayout(m_vLayout);
ui->dockWidget->setWindowTitle(QStringLiteral("Scene Visualizer"));
m_input = new Qt3DInput::QInputAspect();
m_view->registerAspect(m_input);
// Root entity
m_rootEntity = new Qt3DCore::QEntity();
m_rootEntity->setObjectName(QStringLiteral("rootEntity"));
// Camera
m_cameraEntity = m_view->camera();
m_cameraEntity->lens()->setPerspectiveProjection(45.0f, 16.0f/9.0f, 0.1f, 1000.0f);
m_cameraEntity->setPosition(QVector3D(0, 20.0f, 0));
m_cameraEntity->setUpVector(QVector3D(0, 0, 1)); // Z is up
m_cameraEntity->setViewCenter(QVector3D(0, 0, 0));
// For camera controls
m_camController = new Qt3DExtras::QOrbitCameraController(m_rootEntity);
m_camController->setLinearSpeed( 50.0f );
m_camController->setLookSpeed( 180.0f );
m_camController->setCamera(m_cameraEntity);
// Set root object of the scene
m_view->setRootEntity(m_rootEntity);
// Scenemodifier
m_modifier = new SceneModifier(m_rootEntity);
// Show window
//view->show();
//connect(view, SIGNAL(wheelScrolled(std::shared_ptr<QWheelEvent>)), this, SLOT(acceptScroll(std::shared_ptr<QWheelEvent>)));
connect(m_view, SIGNAL(wheelScrolled(QSharedPointer<QWheelEvent>)), this, SLOT(acceptScroll(QSharedPointer<QWheelEvent>)));
m_isShown = true;
}
SceneVizWidget::~SceneVizWidget()
{
// if(ui->dockWidget->isHidden())
// ui->dockWidget->setHidden(false); // if window was closed
// ui->dockWidget->setFloating(false);
// view->close();
// view->destroy();
m_modifier->deleteLater();
// view->deleteLater();
// container->deleteLater();
// widget->deleteLater();
// hLayout->deleteLater();
// vLayout->deleteLater();
// input->deleteLater();
// rootEntity->deleteLater();
// cameraEntity->deleteLater();
// camController->deleteLater();
delete ui;
}
//void SceneVizWidget::wheelEvent(QWheelEvent *event)
//{
// QPoint angle = event->angleDelta();
// qDebug() << "Mouse wheel" << angle;
// double ang = static_cast<double>(angle.y())/240. + 1.;
// cameraEntity->setPosition(cameraEntity->position()*ang);
// event->accept();
//}
void SceneVizWidget::acceptScroll(QSharedPointer<QWheelEvent> event)
{
double ang = static_cast<double>(event->angleDelta().y())/240.;
m_cameraEntity->setPosition(m_cameraEntity->position()*(1-ang) + m_cameraEntity->viewCenter()*ang);
// TODO: add zoom with reference to the pointer location
}
void SceneVizWidget::on_toggleRenderWindowButton_clicked()
{
if(m_view->isVisible())
{
ui->dockWidget->hide();
//view->hide();
ui->toggleRenderWindowButton->setText("Show Window");
m_isShown = false;
}
else
{
ui->dockWidget->show();
if(ui->dockWidget->isFloating())
{
ui->dockWidget->resize(ui->dockFrame->size());
ui->dockWidget->move(1,1);
ui->dockWidget->setFloating(false);
}
//view->show();
ui->toggleRenderWindowButton->setText("Hide Window");
m_isShown = true;
}
}
void SceneVizWidget::on_baseCheckBox_toggled(bool checked)
{
m_modifier->enableObject(checked, EM_SENSOR_BB);
}
void SceneVizWidget::on_tipCheckBox_toggled(bool checked)
{
m_modifier->enableObject(checked, EM_SENSOR_BT);
}
void SceneVizWidget::on_instrCheckBox_toggled(bool checked)
{
m_modifier->enableObject(checked, EM_SENSOR_INST);
}
void SceneVizWidget::on_chestCheckBox_toggled(bool checked)
{
m_modifier->enableObject(checked, EM_SENSOR_CHEST);
}
void SceneVizWidget::on_pushButton_clicked()
{
QVector3D pos = m_modifier->getTriadPosition(EM_SENSOR_BB);
m_cameraEntity->setViewCenter(pos);
}
void SceneVizWidget::on_resetBaseButton_clicked()
{
m_modifier->resetBase();
}
void SceneVizWidget::on_noTformRadio_clicked()
{
m_modifier->changeTFormOption(0);
}
void SceneVizWidget::on_tform1Radio_clicked()
{
m_modifier->changeTFormOption(1);
}
void SceneVizWidget::on_tform2Radio_clicked()
{
m_modifier->changeTFormOption(2);
}
void SceneVizWidget::on_usAngleSpinBox_valueChanged(int arg1)
{
m_modifier->setUSangle(arg1);
}
| 4,903 | C++ | 26.396648 | 129 | 0.673057 |
adegirmenci/HBL-ICEbot/SceneVizWidget/triadentity.cpp | #include "triadentity.h"
TriadEntity::TriadEntity(Qt3DCore::QEntity *parent) : Qt3DCore::QEntity(parent)
{
// LOAD MESH
m_arrowMesh = new Qt3DRender::QMesh();
//arrowMesh = QSharedPointer<Qt3DRender::QMesh>(new Qt3DRender::QMesh());
m_arrowMesh->setMeshName("Arrow");
QFileInfo check_file( QStringLiteral("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\SceneVizWidget\\Arrow.obj") );
if( check_file.exists() && check_file.isFile() )
{
m_arrowMesh->setSource(QUrl::fromLocalFile(QStringLiteral("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\SceneVizWidget\\Arrow.obj")));
qDebug() << "Loaded arrow mesh.";
}
else
{
qDebug() << "Arrow mesh file doesn't exist!";
}
//
m_triadTransforms = new Qt3DCore::QTransform();
m_triadTransforms->setTranslation(QVector3D(0.0f, 0.0f, 0.0f));
this->addComponent(m_triadTransforms);
// ADD MESH TO THREE ARROW ENTITIES
qDebug() << "Adding meshes to arrowEntityList.";
m_arrowEntityList.resize(3);
for(size_t i = 0; i < 3; i++)
{
m_arrowEntityList.replace(i, new Qt3DCore::QEntity(this));
m_arrowEntityList[i]->addComponent(m_arrowMesh);
Qt3DCore::QTransform *arrowTransforms;
arrowTransforms = new Qt3DCore::QTransform(this);
arrowTransforms->setTranslation(QVector3D(0.0f, 0.0f, 0.0f));
switch(i){
case 0:
arrowTransforms->setRotation( QQuaternion::fromAxisAndAngle(QVector3D(1, 0, 0),0.0f) );
break;
case 1:
arrowTransforms->setRotation( QQuaternion::fromAxisAndAngle(QVector3D(0, 0, 1),90.0f) );
break;
case 2:
arrowTransforms->setRotation( QQuaternion::fromAxisAndAngle(QVector3D(0, 1, 0),-90.0f) );
break;
}
arrowTransforms->setScale3D(QVector3D(3,2,2));
Qt3DExtras::QGoochMaterial *arrowMaterial = new Qt3DExtras::QGoochMaterial(this);
arrowMaterial->setAlpha(0.5f);
arrowMaterial->setBeta(0.5f);
switch(i){
case 0:
arrowMaterial->setDiffuse(QColor(200,50,50));
//arrowMaterial->setDiffuse(QColor(200,50,50));
arrowMaterial->setWarm(QColor(155,0,0));
arrowMaterial->setCool(QColor(90,20,20));
//arrowMaterial->setSpecular(QColor(200,50,50));
break;
case 1:
arrowMaterial->setDiffuse(QColor(50,200,50));
//arrowMaterial->setDiffuse(QColor(50,200,50));
arrowMaterial->setWarm(QColor(0,127,0));
arrowMaterial->setCool(QColor(20,90,20));
//arrowMaterial->setSpecular(QColor(50,200,50));
break;
case 2:
arrowMaterial->setDiffuse(QColor(50,50,200));
//arrowMaterial->setDiffuse(QColor(50,50,200));
arrowMaterial->setWarm(QColor(0,0,127));
arrowMaterial->setCool(QColor(20,20,90));
//arrowMaterial->setSpecular(QColor(50,50,200));
break;
}
arrowMaterial->setShininess(1.0f);
m_arrowEntityList[i]->addComponent(arrowMaterial);
m_arrowEntityList[i]->addComponent(arrowTransforms);
}
qDebug() << "Adding meshes done.";
}
TriadEntity::~TriadEntity()
{
qDebug() << "Destroying TriadEntity.";
//arrowEntityList.clear();
//arrowMesh->deleteLater();
}
void TriadEntity::translate(const QVector3D &trans)
{
m_triadTransforms->setTranslation(trans);
}
void TriadEntity::rotate(const QQuaternion &rot)
{
m_triadTransforms->setRotation(rot);
}
void TriadEntity::setTransformation(const Qt3DCore::QTransform &tform)
{
m_triadTransforms->setMatrix(tform.matrix());
}
| 3,723 | C++ | 33.165137 | 155 | 0.627182 |
adegirmenci/HBL-ICEbot/FrmGrabWidget/frmgrabthread.cpp | #include "frmgrabthread.h"
FrmGrabThread::FrmGrabThread(QObject *parent) : QObject(parent)
{
qRegisterMetaType< std::shared_ptr<Frame> >("std::shared_ptr<Frame>");
m_isEpochSet = false;
m_isReady = false;
m_keepStreaming = false;
m_showLiveFeed = false;
m_numSaveImageRequests = 0;
m_frameCount = 0;
m_abort = false;
m_continuousSaving = false;
m_videoFPS = 0;
m_mutex = new QMutex(QMutex::Recursive);
}
FrmGrabThread::~FrmGrabThread()
{
frmGrabDisconnect();
m_mutex->lock();
m_continuousSaving = false;
m_abort = true;
qDebug() << "Ending FrmGrabThread - ID: " << reinterpret_cast<int>(QThread::currentThreadId()) << ".";
m_mutex->unlock();
delete m_mutex;
m_src.release();
m_dst.release();
emit finished();
}
void FrmGrabThread::frmGrabConnect()
{
QMutexLocker locker(m_mutex);
emit statusChanged(FRMGRAB_CONNECT_BEGIN);
m_cap.open(0); // open the default camera
if(m_cap.isOpened()) // check if we succeeded
{
emit statusChanged(FRMGRAB_CONNECTED); // success
}
else
{
emit statusChanged(FRMGRAB_CONNECT_FAILED); // failed
}
}
void FrmGrabThread::frmGrabInitialize(int width, int height, double fps)
{
QMutexLocker locker(m_mutex);
if(m_cap.isOpened())
{
m_videoFPS = fps; // m_cap.get(CV_CAP_PROP_FPS);
m_imgSize.height = height; //m_cap.get(CV_CAP_PROP_FRAME_HEIGHT);
m_imgSize.width = width; //m_cap.get(CV_CAP_PROP_FRAME_WIDTH);
m_cap.set(CV_CAP_PROP_FRAME_HEIGHT, m_imgSize.height);
m_cap.set(CV_CAP_PROP_FRAME_WIDTH, m_imgSize.width);
m_cap.set(CV_CAP_PROP_FPS, m_videoFPS);
qDebug() << "Width:" << m_imgSize.width << "Height:" << m_imgSize.height << "FPS:" << m_videoFPS;
emit statusChanged(FRMGRAB_INITIALIZED);
}
else
emit statusChanged(FRMGRAB_INITIALIZE_FAILED);
}
void FrmGrabThread::startStream()
{
QMutexLocker locker(m_mutex);
if(!m_keepStreaming)
{
m_timer = new QTimer(this);
m_timer->start(floor(1000./m_videoFPS));
connect(m_timer, SIGNAL(timeout()), this, SLOT(grabFrame()));
m_keepStreaming = true;
emit logEvent(SRC_FRMGRAB, LOG_INFO, QTime::currentTime(), FRMGRAB_LOOP_STARTED);
emit statusChanged(FRMGRAB_LOOP_STARTED);
qDebug() << "Streaming started.";
}
}
void FrmGrabThread::stopStream()
{
QMutexLocker locker(m_mutex);
if ( m_keepStreaming )
{
if(m_showLiveFeed)
toggleLiveFeed();
m_keepStreaming = false;
m_timer->stop();
disconnect(m_timer,SIGNAL(timeout()), 0, 0);
delete m_timer;
emit logEvent(SRC_FRMGRAB, LOG_INFO, QTime::currentTime(), FRMGRAB_LOOP_STOPPED);
qDebug() << "Streaming stopped.";
}
else
{
qDebug() << "Streaming already stopped.";
}
emit statusChanged(FRMGRAB_LOOP_STOPPED);
}
void FrmGrabThread::toggleLiveFeed()
{
QMutexLocker locker(m_mutex);
m_showLiveFeed = !m_showLiveFeed;
if(m_showLiveFeed)
{
cv::namedWindow(m_winName.toStdString());
cv::resizeWindow(m_winName.toStdString(), m_imgSize.width, m_imgSize.height);
// make connections
connect(this, SIGNAL(imageAcquired(std::shared_ptr<Frame>)), this, SLOT(displayFrame(std::shared_ptr<Frame>)));
emit statusChanged(FRMGRAB_LIVE_FEED_STARTED);
}
else
{
// break connections
disconnect(this, SIGNAL(imageAcquired(std::shared_ptr<Frame>)), this, SLOT(displayFrame(std::shared_ptr<Frame>)));
cv::destroyWindow(m_winName.toStdString());
emit statusChanged(FRMGRAB_LIVE_FEED_STOPPED);
}
}
void FrmGrabThread::displayFrame(std::shared_ptr<Frame> frm)
{
QMutexLocker locker(m_mutex);
cv::imshow(m_winName.toStdString(), frm->image_);
}
void FrmGrabThread::frmGrabDisconnect()
{
stopStream();
QMutexLocker locker(m_mutex);
m_cap.release(); // release video capture device
emit statusChanged(FRMGRAB_DISCONNECTED);
}
void FrameDeleter(Frame* frm)
{
frm->image_.release();
}
void FrmGrabThread::grabFrame()
{
QMutexLocker locker(m_mutex);
// capture frame
m_cap >> m_src;
//m_cap.read(m_src);
qint64 msec = QDateTime::currentMSecsSinceEpoch();
// convert to grayscale
cv::cvtColor(m_src, m_dst, CV_BGR2GRAY);
// construct new frame
std::shared_ptr<Frame> frame(new Frame(m_dst, msec, m_frameCount), FrameDeleter);
if(m_continuousSaving)
{
m_numSaveImageRequests++;
}
if(m_numSaveImageRequests > 0)
{
emit pleaseSaveImage(frame);
m_frameCount++;
m_numSaveImageRequests--;
}
//if(m_showLiveFeed)
emit imageAcquired(frame);
}
void FrmGrabThread::startSaving()
{
QMutexLocker locker(m_mutex);
m_continuousSaving = true;
}
void FrmGrabThread::stopSaving()
{
QMutexLocker locker(m_mutex);
m_continuousSaving = false;
}
void FrmGrabThread::addSaveRequest(unsigned short numFrames)
{
QMutexLocker locker(m_mutex);
m_numSaveImageRequests += numFrames;
}
void FrmGrabThread::setEpoch(const QDateTime &datetime)
{
QMutexLocker locker(m_mutex);
if(!m_keepStreaming)
{
m_epoch = datetime;
m_isEpochSet = true;
emit logEventWithMessage(SRC_FRMGRAB, LOG_INFO, QTime::currentTime(), FRMGRAB_EPOCH_SET,
m_epoch.toString("yyyy/MM/dd - hh:mm:ss.zzz"));
}
else
emit logEvent(SRC_FRMGRAB, LOG_INFO, QTime::currentTime(), FRMGRAB_EPOCH_SET_FAILED);
}
| 5,638 | C++ | 22.016326 | 122 | 0.632316 |
adegirmenci/HBL-ICEbot/FrmGrabWidget/frmgrabwidget.h | #ifndef FRMGRABWIDGET_H
#define FRMGRABWIDGET_H
#include <QWidget>
#include "frmgrabthread.h"
namespace Ui {
class FrmGrabWidget;
}
class FrmGrabWidget : public QWidget
{
Q_OBJECT
public:
explicit FrmGrabWidget(QWidget *parent = 0);
~FrmGrabWidget();
FrmGrabThread *m_worker;
signals:
void frmGrabConnect();
void frmGrabInitialize(int width, int height, double fps);
void startStream();
void stopStream();
void addSaveRequest(unsigned short numFrames);
void frmGrabDisconnect();
void toggleLiveFeed();
void startSaving();
void stopSaving();
private slots:
void workerStatusChanged(int status);
void on_connectButton_clicked();
void on_initButton_clicked();
void on_disconnectButton_clicked();
void on_startStreamButton_clicked();
void on_liveFeedButton_clicked();
void on_saveFrameButton_clicked();
void on_stopStreamButton_clicked();
void on_saveFramesButton_clicked();
void controlStarted();
void controlStopped();
private:
Ui::FrmGrabWidget *ui;
QThread m_thread; // FrmGrab Thread will live in here
bool mKeepSavingFrames;
};
#endif // FRMGRABWIDGET_H
| 1,186 | C | 17.261538 | 62 | 0.700675 |
adegirmenci/HBL-ICEbot/FrmGrabWidget/frmgrabwidget.cpp | #include "frmgrabwidget.h"
#include "ui_frmgrabwidget.h"
FrmGrabWidget::FrmGrabWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::FrmGrabWidget)
{
ui->setupUi(this);
m_worker = new FrmGrabThread;
m_worker->moveToThread(&m_thread);
mKeepSavingFrames = false;
//connect(&m_thread, &QThread::finished, m_worker, &QObject::deleteLater);
connect(&m_thread, SIGNAL(finished()), m_worker, SLOT(deleteLater()));
m_thread.start();
connect(m_worker, SIGNAL(statusChanged(int)), this, SLOT(workerStatusChanged(int)));
connect(this, SIGNAL(frmGrabConnect()), m_worker, SLOT(frmGrabConnect()));
connect(this, SIGNAL(frmGrabInitialize(int,int,double)), m_worker, SLOT(frmGrabInitialize(int,int,double)));
connect(this, SIGNAL(startStream()), m_worker, SLOT(startStream()));
connect(this, SIGNAL(stopStream()), m_worker, SLOT(stopStream()));
connect(this, SIGNAL(toggleLiveFeed()), m_worker, SLOT(toggleLiveFeed()));
connect(this, SIGNAL(addSaveRequest(unsigned short)), m_worker, SLOT(addSaveRequest(unsigned short)));
connect(this, SIGNAL(frmGrabDisconnect()), m_worker, SLOT(frmGrabDisconnect()));
connect(this, SIGNAL(startSaving()), m_worker, SLOT(startSaving()));
connect(this, SIGNAL(stopSaving()), m_worker, SLOT(stopSaving()));
}
FrmGrabWidget::~FrmGrabWidget()
{
m_thread.quit();
m_thread.wait();
qDebug() << "FrmGrab thread quit.";
delete ui;
}
void FrmGrabWidget::workerStatusChanged(int status)
{
switch(status)
{
case FRMGRAB_CONNECT_BEGIN:
ui->connectButton->setEnabled(false);
ui->initButton->setEnabled(true);
ui->disconnectButton->setEnabled(false);
ui->startStreamButton->setEnabled(false);
ui->liveFeedButton->setEnabled(false);
ui->saveFrameButton->setEnabled(false);
ui->stopStreamButton->setEnabled(false);
ui->statusLineEdit->setText("Connecting.");
break;
case FRMGRAB_CONNECT_FAILED:
ui->connectButton->setEnabled(true);
ui->initButton->setEnabled(false);
ui->disconnectButton->setEnabled(false);
ui->startStreamButton->setEnabled(false);
ui->liveFeedButton->setEnabled(false);
ui->saveFrameButton->setEnabled(false);
ui->stopStreamButton->setEnabled(false);
ui->statusLineEdit->setText("Connection failed.");
break;
case FRMGRAB_CONNECTED:
ui->connectButton->setEnabled(false);
ui->initButton->setEnabled(true);
ui->disconnectButton->setEnabled(true);
ui->startStreamButton->setEnabled(false);
ui->liveFeedButton->setEnabled(false);
ui->saveFrameButton->setEnabled(false);
ui->stopStreamButton->setEnabled(false);
ui->statusLineEdit->setText("Connected.");
break;
case FRMGRAB_INITIALIZE_BEGIN:
ui->connectButton->setEnabled(false);
ui->initButton->setEnabled(false);
ui->disconnectButton->setEnabled(true);
ui->startStreamButton->setEnabled(false);
ui->liveFeedButton->setEnabled(false);
ui->saveFrameButton->setEnabled(false);
ui->stopStreamButton->setEnabled(false);
ui->statusLineEdit->setText("Initializing.");
break;
case FRMGRAB_INITIALIZE_FAILED:
ui->connectButton->setEnabled(false);
ui->initButton->setEnabled(true);
ui->disconnectButton->setEnabled(true);
ui->startStreamButton->setEnabled(false);
ui->liveFeedButton->setEnabled(false);
ui->saveFrameButton->setEnabled(false);
ui->stopStreamButton->setEnabled(false);
ui->statusLineEdit->setText("Initialization failed.");
break;
case FRMGRAB_INITIALIZED:
ui->connectButton->setEnabled(false);
ui->initButton->setEnabled(false);
ui->disconnectButton->setEnabled(true);
ui->startStreamButton->setEnabled(true);
ui->liveFeedButton->setEnabled(false);
ui->saveFrameButton->setEnabled(false);
ui->stopStreamButton->setEnabled(false);
ui->statusLineEdit->setText("Initialized.");
break;
case FRMGRAB_LOOP_STARTED:
ui->connectButton->setEnabled(false);
ui->initButton->setEnabled(false);
ui->disconnectButton->setEnabled(true);
ui->startStreamButton->setEnabled(false);
ui->liveFeedButton->setEnabled(true);
ui->saveFrameButton->setEnabled(true);
ui->stopStreamButton->setEnabled(true);
ui->statusLineEdit->setText("Streaming.");
break;
case FRMGRAB_LOOP_STOPPED:
ui->connectButton->setEnabled(false);
ui->initButton->setEnabled(false);
ui->disconnectButton->setEnabled(true);
ui->startStreamButton->setEnabled(true);
ui->liveFeedButton->setEnabled(false);
ui->saveFrameButton->setEnabled(false);
ui->stopStreamButton->setEnabled(false);
ui->statusLineEdit->setText("Stream stopped.");
break;
case FRMGRAB_LIVE_FEED_STARTED:
ui->connectButton->setEnabled(false);
ui->initButton->setEnabled(false);
ui->disconnectButton->setEnabled(true);
ui->startStreamButton->setEnabled(false);
ui->liveFeedButton->setEnabled(true);
ui->liveFeedButton->setText("Close Feed");
ui->saveFrameButton->setEnabled(true);
ui->stopStreamButton->setEnabled(true);
ui->statusLineEdit->setText("Streaming.");
break;
case FRMGRAB_LIVE_FEED_STOPPED:
ui->connectButton->setEnabled(false);
ui->initButton->setEnabled(false);
ui->disconnectButton->setEnabled(true);
ui->startStreamButton->setEnabled(false);
ui->liveFeedButton->setEnabled(true);
ui->liveFeedButton->setText("Live Feed");
ui->saveFrameButton->setEnabled(true);
ui->stopStreamButton->setEnabled(true);
ui->statusLineEdit->setText("Streaming.");
break;
case FRMGRAB_EPOCH_SET:
qDebug() << "Epoch set.";
break;
case FRMGRAB_EPOCH_SET_FAILED:
qDebug() << "Epoch set failed.";
break;
case FRMGRAB_DISCONNECTED:
ui->connectButton->setEnabled(true);
ui->initButton->setEnabled(false);
ui->disconnectButton->setEnabled(false);
ui->startStreamButton->setEnabled(false);
ui->liveFeedButton->setEnabled(false);
ui->saveFrameButton->setEnabled(false);
ui->stopStreamButton->setEnabled(false);
ui->statusLineEdit->setText("Disconnected.");
break;
case FRMGRAB_DISCONNECT_FAILED:
ui->connectButton->setEnabled(false);
ui->initButton->setEnabled(false);
ui->disconnectButton->setEnabled(true);
ui->startStreamButton->setEnabled(false);
ui->liveFeedButton->setEnabled(false);
ui->saveFrameButton->setEnabled(false);
ui->stopStreamButton->setEnabled(false);
ui->statusLineEdit->setText("Disconnect failed.");
break;
default:
qDebug() << "Unknown state!";
break;
}
}
void FrmGrabWidget::on_connectButton_clicked()
{
emit frmGrabConnect();
}
void FrmGrabWidget::on_initButton_clicked()
{
int width = ui->widthSpinBox->value();
int height = ui->heightSpinBox->value();
double fps = ui->fpsSpinBox->value();
emit frmGrabInitialize(width, height, fps);
}
void FrmGrabWidget::on_disconnectButton_clicked()
{
emit frmGrabDisconnect();
}
void FrmGrabWidget::on_startStreamButton_clicked()
{
emit startStream();
}
void FrmGrabWidget::on_liveFeedButton_clicked()
{
emit toggleLiveFeed();
}
void FrmGrabWidget::on_saveFrameButton_clicked()
{
emit addSaveRequest(1); // request a single frame
}
void FrmGrabWidget::on_stopStreamButton_clicked()
{
emit stopStream();
}
void FrmGrabWidget::on_saveFramesButton_clicked()
{
if(mKeepSavingFrames) // already saving, so stop saving
{
mKeepSavingFrames = false;
ui->saveFramesButton->setText("Start Saving");
emit stopSaving();
}
else
{
mKeepSavingFrames = true;
ui->saveFramesButton->setText("Stop Saving");
emit startSaving();
}
}
void FrmGrabWidget::controlStarted()
{
if(!mKeepSavingFrames)
{
mKeepSavingFrames = true;
ui->saveFramesButton->setText("Stop Saving");
emit startSaving();
}
}
void FrmGrabWidget::controlStopped()
{
if(mKeepSavingFrames)
{
mKeepSavingFrames = false;
ui->saveFramesButton->setText("Start Saving");
emit stopSaving();
}
}
| 8,568 | C++ | 32.869565 | 112 | 0.656162 |
adegirmenci/HBL-ICEbot/FrmGrabWidget/frmgrabthread.h | #ifndef FRMGRABTHREAD_H
#define FRMGRABTHREAD_H
#include <QObject>
#include <QMutex>
#include <QMutexLocker>
#include <QThread>
#include <QString>
#include <QTime>
#include <QTimer>
#include <QDebug>
#include <QSharedPointer>
#include <vector>
#include <memory>
#include "../icebot_definitions.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
//#include "opencv2/video/video.hpp"
//#include <epiphan/frmgrab/include/frmgrab.h>
/** Frame structure.
* This will hold an image, a timestamp, and an index.
*/
struct Frame{
cv::Mat image_; /*!< Image data. */
qint64 timestamp_; /*!< Timestamp, msec since some epoch. */
int index_; /*!< Index value of Frame, indicate order of acquisition. */
//! Constructor.
explicit Frame(cv::Mat img = cv::Mat(), qint64 ts = -1, int id = -1) :
timestamp_(ts), index_(id)
{
image_ = img;
}
//! Destructor
~Frame() {
image_.release();
}
};
Q_DECLARE_METATYPE(std::shared_ptr<Frame>)
class FrmGrabThread : public QObject
{
Q_OBJECT
public:
explicit FrmGrabThread(QObject *parent = 0);
~FrmGrabThread();
signals:
void statusChanged(int event);
void imageAcquired(std::shared_ptr<Frame> frm);
void pleaseSaveImage(std::shared_ptr<Frame> frm);
void logData(QTime timeStamp,
int frameIdx,
QString &data);
void logEvent(int source, // LOG_SOURCE
int logType, // LOG_TYPES
QTime timeStamp,
int eventID); // FRMGRAB_EVENT_IDS
void logEventWithMessage(int source, // LOG_SOURCE
int logType, // LOG_TYPES
QTime timeStamp,
int eventID, // FRMGRAB_EVENT_IDS
QString &message);
void logError(int source, // LOG_SOURCE
int logType, // LOG_TYPES
QTime timeStamp,
int errCode, // FRMGRAB_ERROR_CODES
QString message);
void finished(); // emit upon termination
public slots:
void frmGrabConnect();
void frmGrabInitialize(int width, int height, double fps);
void startStream();
void stopStream();
void toggleLiveFeed();
void displayFrame(std::shared_ptr<Frame> frm);
void addSaveRequest(unsigned short numFrames);
void frmGrabDisconnect();
void setEpoch(const QDateTime &datetime); // set Epoch
void grabFrame();
void startSaving();
void stopSaving();
private:
// Instead of using "m_mutex.lock()"
// use "QMutexLocker locker(&m_mutex);"
// this will unlock the mutex when the locker goes out of scope
mutable QMutex *m_mutex;
// Timer for calling grabFrame every xxx msecs
QTimer *m_timer;
// Epoch for time stamps
// During initializeFrmGrab(), check 'isEpochSet' flag
// If Epoch is set externally from MainWindow, the flag will be true
// Otherwise, Epoch will be set internally
QDateTime m_epoch;
bool m_isEpochSet;
// Flag to indicate if Frame Grabber is ready
// True if InitializeFrmGrab was successful
bool m_isReady;
// Flag to tell that we are still recording
bool m_keepStreaming;
// Flag for live feed
bool m_showLiveFeed;
// Flag to abort actions (e.g. initialize, acquire, etc.)
bool m_abort;
// Image containers
cv::Mat m_src;
cv::Mat m_dst;
cv::Size m_imgSize;
int m_frameCount; // keep a count of number of saved frames
int m_numSaveImageRequests; // Counter to keep track of image saving
bool m_continuousSaving;
cv::VideoCapture m_cap; // video capture device
const QString m_winName = QString("Live Feed");
double m_videoFPS;
};
#endif // FRMGRABTHREAD_H
| 3,798 | C | 25.2 | 76 | 0.635071 |
adegirmenci/HBL-ICEbot/AscensionWidget/ascensionthread.h | #ifndef ASCENSIONTHREAD_H
#define ASCENSIONTHREAD_H
#include <QObject>
#include <QMutex>
#include <QMutexLocker>
#include <QThread>
#include <QWaitCondition>
#include <QString>
#include <QDateTime>
#include <QTimer>
#include <QDebug>
#include <QQuaternion>
#include <QMatrix3x3>
#include <vector>
#include "../icebot_definitions.h"
#include "3DGAPI/ATC3DG.h"
// ##############################
// # ATC3DG (Ascension) classes #
// ##############################
// System class
class CSystem
{
public:
SYSTEM_CONFIGURATION m_config;
};
// Sensor class
class CSensor
{
public:
SENSOR_CONFIGURATION m_config;
};
// Transmitter class
class CXmtr
{
public:
TRANSMITTER_CONFIGURATION m_config;
};
// ------------------------------
Q_DECLARE_METATYPE(DOUBLE_POSITION_MATRIX_TIME_Q_RECORD)
Q_DECLARE_METATYPE(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD>)
// ##################################
// # Ascension Thread Class Members #
// ##################################
class AscensionThread : public QObject
{
Q_OBJECT
public:
explicit AscensionThread(QObject *parent = 0);
~AscensionThread();
//bool isEMready();
//bool isRecording();
int getSampleRate();
int getNumSensors();
signals:
void statusChanged(int status);
//void EM_Ready(bool status); // tells the widget that the EM tracker is ready
void logData(QTime timeStamp,
int sensorID,
DOUBLE_POSITION_MATRIX_TIME_Q_RECORD data);
void sendLatestReading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> latestReading);
void logEvent(int source, // LOG_SOURCE
int logType, // LOG_TYPES
QTime timeStamp,
int eventID); // EM_EVENT_IDS
void logEventWithMessage(int source, // LOG_SOURCE
int logType, // LOG_TYPES
QTime timeStamp,
int eventID, // EM_EVENT_IDS
QString &message);
void logError(int source, // LOG_SOURCE
int logType, // LOG_TYPES
QTime timeStamp,
int errCode, // EM_ERROR_CODES
QString message);
void sendDataToGUI(int sensorID, const QString &output);
void finished(); // emit upon termination
public slots:
bool initializeEM(); // open connection to EM
void startAcquisition(); // start timer
void stopAcquisition(); // stop timer
bool disconnectEM(); // disconnect from EM
void setEpoch(const QDateTime &datetime); // set Epoch
void setSampleRate(int freq); // set freq
void getLatestReading(const int sensorID, DOUBLE_POSITION_MATRIX_TIME_Q_RECORD &dataContainer);
void getLatestReadingsAll(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> &dataContainer);
private slots:
void getSample(); // called by timer
private:
// Instead of using "m_mutex.lock()"
// use "QMutexLocker locker(&m_mutex);"
// this will unlock the mutex when the locker goes out of scope
mutable QMutex *m_mutex;
// Timer for calling acquire data every 1/m_samplingFreq
QTimer *m_timer;
// Epoch for time stamps
// During initializeEM(), check 'isEpochSet' flag
// If Epoch is set externally from MainWindow, the flag will be true
// Otherwise, Epoch will be set internally
QDateTime m_epoch;
bool m_isEpochSet;
// Flag to indicate if EM tracker is ready for data collection
// True if InitializeEM was successful
bool m_isReady;
// Flag to tell the run() loop to keep acquiring readings from EM
bool m_keepRecording;
// Fllag to abort actions (e.g. initialize, acquire, etc.)
bool m_abort;
// EM tracker variables
CSystem m_ATC3DG;
CSensor *m_pSensor;
CXmtr *m_pXmtr;
int m_errorCode;
int m_i;
int m_numSensorsAttached;
int m_sensorID;
short m_id;
int m_samplingFreq;
int m_records;
int m_numberBytes;
// latest reading
std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> m_latestReading;
std::vector<double> m_deltaT;
double m_avgSamplingFreq;
const int m_prec = 4; // precision for print operations
// EM tracker error handler function
void errorHandler_(int error);
QString formatOutput(QTime &timeStamp,
const int sensorID,
DOUBLE_POSITION_MATRIX_TIME_Q_RECORD &record);
};
// ----------------
// HELPER FUNCTIONS
// ----------------
inline const QString getCurrTimeStr();
inline const QString getCurrDateTimeStr();
#endif // ASCENSIONTHREAD_H
| 4,565 | C | 27.185185 | 99 | 0.630668 |
adegirmenci/HBL-ICEbot/AscensionWidget/ascensionthread.cpp | #include "ascensionthread.h"
AscensionThread::AscensionThread(QObject *parent) :
QObject(parent)
{
m_isEpochSet = false;
m_isReady = false;
m_keepRecording = false;
m_abort = false;
m_mutex = new QMutex(QMutex::Recursive);
m_numSensorsAttached = 0;
m_records = 0;
m_latestReading.resize(4);
m_deltaT.resize(EM_DELTA_T_SIZE,0);
m_avgSamplingFreq = 0.0;
qRegisterMetaType<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD>("DOUBLE_POSITION_MATRIX_TIME_Q_RECORD");
qRegisterMetaType< std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> >("std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD>");
}
AscensionThread::~AscensionThread()
{
disconnectEM();
m_mutex->lock();
m_abort = true;
qDebug() << "Ending AscensionThread - ID: " << reinterpret_cast<int>(QThread::currentThreadId()) << ".";
m_mutex->unlock();
delete m_mutex;
emit finished();
}
// ------------------------------
// SLOTS IMPLEMENTATION
// ------------------------------
bool AscensionThread::initializeEM() // open connection to EM
{
bool status = true;
QMutexLocker locker(m_mutex);
// Initialize the ATC3DG driver and DLL
// It is always necessary to first initialize the ATC3DG "system". By
// "system" we mean the set of ATC3DG cards installed in the PC. All cards
// will be initialized by a single call to InitializeBIRDSystem(). This
// call will first invoke a hardware reset of each board. If at any time
// during operation of the system an unrecoverable error occurs then the
// first course of action should be to attempt to Recall InitializeBIRDSystem()
// if this doesn't restore normal operating conditions there is probably a
// permanent failure - contact tech support.
// A call to InitializeBIRDSystem() does not return any information.
//
emit logEvent(SRC_EM, LOG_INFO, QTime::currentTime(), EM_INITIALIZE_BEGIN);
emit statusChanged(EM_INITIALIZE_BEGIN);
m_errorCode = InitializeBIRDSystem();
if(m_errorCode!=BIRD_ERROR_SUCCESS)
{
errorHandler_(m_errorCode);
emit statusChanged(EM_INITIALIZE_FAILED);
return status = false;
}
// GET SYSTEM CONFIGURATION
//
// In order to get information about the system we have to make a call to
// GetBIRDSystemConfiguration(). This call will fill a fixed size structure
// containing amongst other things the number of boards detected and the
// number of sensors and transmitters the system can support (Note: This
// does not mean that all sensors and transmitters that can be supported
// are physically attached)
//
m_errorCode = GetBIRDSystemConfiguration(&m_ATC3DG.m_config);
if(m_errorCode!=BIRD_ERROR_SUCCESS)
{
errorHandler_(m_errorCode);
emit statusChanged(EM_INITIALIZE_FAILED);
return status = false;
}
// GET SENSOR CONFIGURATION
//
// Having determined how many sensors can be supported we can dynamically
// allocate storage for the information about each sensor.
// This information is acquired through a call to GetSensorConfiguration()
// This call will fill a fixed size structure containing amongst other things
// a status which indicates whether a physical sensor is attached to this
// sensor port or not.
//
m_pSensor = new CSensor[m_ATC3DG.m_config.numberSensors];
for(m_i = 0; m_i < m_ATC3DG.m_config.numberSensors; m_i++)
{
m_errorCode = GetSensorConfiguration(m_i, &(m_pSensor + m_i)->m_config);
if(m_errorCode!=BIRD_ERROR_SUCCESS)
{
errorHandler_(m_errorCode);
emit statusChanged(EM_INITIALIZE_FAILED);
return status = false;
}
// if this sensor is attached, set number of sensors to current index
// !THIS ASSUMES THAT SENSORS ARE ATTACHED IN ORDER
// !BEGINNING AT 1 ON THE BOX (AND 0 IN C++)
if( (m_pSensor + m_i)->m_config.attached )
m_numSensorsAttached = m_i + 1;
}
emit logEventWithMessage(SRC_EM, LOG_INFO, QTime::currentTime(), EM_SENSORS_DETECTED,
QString::number(m_numSensorsAttached));
// GET TRANSMITTER CONFIGURATION
//
// The call to GetTransmitterConfiguration() performs a similar task to the
// GetSensorConfiguration() call. It also returns a status in the filled
// structure which indicates whether a transmitter is attached to this
// port or not. In a single transmitter system it is only necessary to
// find where that transmitter is in order to turn it on and use it.
//
m_pXmtr = new CXmtr[m_ATC3DG.m_config.numberTransmitters];
for(m_i = 0; m_i < m_ATC3DG.m_config.numberTransmitters; m_i++)
{
m_errorCode = GetTransmitterConfiguration(m_i, &(m_pXmtr + m_i)->m_config);
if(m_errorCode!=BIRD_ERROR_SUCCESS)
{
errorHandler_(m_errorCode);
emit statusChanged(EM_INITIALIZE_FAILED);
return status = false;
}
}
// Search for the first attached transmitter and turn it on
//
for(m_id = 0; m_id < m_ATC3DG.m_config.numberTransmitters; m_id++)
{
if((m_pXmtr + m_id)->m_config.attached)
{
// Transmitter selection is a system function.
// Using the SELECT_TRANSMITTER parameter we send the id of the
// transmitter that we want to run with the SetSystemParameter() call
m_errorCode = SetSystemParameter(SELECT_TRANSMITTER, &m_id, sizeof(m_id));
if(m_errorCode!=BIRD_ERROR_SUCCESS)
{
errorHandler_(m_errorCode);
emit statusChanged(EM_INITIALIZE_FAILED);
return status = false;
}
break;
}
}
// report the transmitter being used
emit logEventWithMessage(SRC_EM, LOG_INFO, QTime::currentTime(), EM_TRANSMITTER_SET,
QString::number(m_id));
// report the detected sampling rate
m_samplingFreq = m_ATC3DG.m_config.measurementRate;
emit logEventWithMessage(SRC_EM, LOG_INFO, QTime::currentTime(), EM_FREQ_DETECTED,
QString::number(m_samplingFreq));
// Set sensor output to position + rotation matrix + time stamp
for(m_sensorID = 0; m_sensorID < m_numSensorsAttached; m_sensorID++)
{
DATA_FORMAT_TYPE buf = DOUBLE_POSITION_MATRIX_TIME_Q;
DATA_FORMAT_TYPE *pBuf = &buf;
m_errorCode = SetSensorParameter(m_sensorID, DATA_FORMAT, pBuf, sizeof(buf));
if(m_errorCode!=BIRD_ERROR_SUCCESS) {
errorHandler_(m_errorCode);
emit statusChanged(EM_INITIALIZE_FAILED);
return status = false;
}
}
// resize container based on the number of sensors
m_latestReading.resize(m_numSensorsAttached);
// set flag to ready
m_isReady = status;
//locker.unlock();
// set sample rate
setSampleRate(EM_DEFAULT_SAMPLE_RATE);
// set to METRIC
BOOL isMetric = TRUE;
m_errorCode = SetSystemParameter(METRIC, &isMetric, sizeof(isMetric));
if(m_errorCode!=BIRD_ERROR_SUCCESS) {
errorHandler_(m_errorCode);
emit statusChanged(EM_INITIALIZE_FAILED);
return status = false;
}
emit logEvent(SRC_EM, LOG_INFO, QTime::currentTime(), EM_INITIALIZED);
emit statusChanged(EM_INITIALIZED);
return status;
}
void AscensionThread::startAcquisition() // start timer
{
QMutexLocker locker(m_mutex);
// reset stats
m_deltaT.clear();
m_deltaT.resize(EM_DELTA_T_SIZE,0);
m_avgSamplingFreq = 0;
// start timer
m_timer = new QTimer(this);
connect(m_timer,SIGNAL(timeout()),this,SLOT(getSample()));
m_timer->start(1000./m_samplingFreq);
m_keepRecording = true;
m_i = 0;
emit logEvent(SRC_EM, LOG_INFO, QTime::currentTime(), EM_ACQUISITION_STARTED);
emit statusChanged(EM_ACQUISITION_STARTED);
}
void AscensionThread::getSample() // called by timer
{
// Collect data from all birds
// Note: The default data format is DOUBLE_POSITION_ANGLES. We can use this
// format without first setting it.
// 4 sensors
DOUBLE_POSITION_MATRIX_TIME_Q_RECORD record[8*4], *pRecord = record;
//DOUBLE_POSITION_MATRIX_TIME_STAMP_RECORD *pRecord = record
//DOUBLE_POSITION_MATRIX_TIME_STAMP_RECORD record, *pRecord = &record;
QMutexLocker locker(m_mutex);
// request all sensor readings at once
m_errorCode = GetSynchronousRecord(ALL_SENSORS, pRecord, sizeof(record[0]) * m_numSensorsAttached);
QTime tstamp = QTime::currentTime(); // get time
if(m_errorCode != BIRD_ERROR_SUCCESS)
{
errorHandler_(m_errorCode);
emit statusChanged(EM_ACQUIRE_FAILED);
//locker.unlock();
stopAcquisition();
return;
}
// async version, not prefered, therefore commented out
/*
// // scan the sensors and request a record - this is async, not preferred
// for(m_sensorID = 0; m_sensorID < m_numSensorsAttached; m_sensorID++)
// {
// m_errorCode = GetAsynchronousRecord(m_sensorID, &record[m_sensorID], sizeof(record[m_sensorID]));
// //m_errorCode = GetSynchronousRecord(m_sensorID, &record[m_sensorID], sizeof(record[m_sensorID]));
// if(m_errorCode != BIRD_ERROR_SUCCESS)
// {
// errorHandler_(m_errorCode);
// emit statusChanged(EM_ACQUIRE_FAILED);
// //locker.unlock();
// stopAcquisition();
// return;
// }
// // Weirdly, the vector part is reported with a flipped sign. Scalar part is fine.
// // You can check this in MATLAB
// // Use the Cubes.exe provided by Ascension to get the azimuth, elevation, and roll.
// // These are the Z,Y,X rotation angles.
// // You can use the Robotics Toolbox by P. Corke and run convert from quat to rpy
// // rad2deg(quat2rpy(q0,q1,q2,q3)) -> this gives you the X,Y,Z rotation angles (notice the flipped order!)
// // Flipping the sign of q1,q2,q3 will fix the mismatch
// record[m_sensorID].q[1] *= -1.0;
// record[m_sensorID].q[2] *= -1.0;
// record[m_sensorID].q[3] *= -1.0;
// }
*/
// get time difference between readings
// m_deltaT hold the latest index as the last element in the vector
// this index is incremented to essentially create a circular buffer
m_deltaT[m_deltaT[EM_DELTA_T_SIZE-1]] = record[0].time - m_latestReading[0].time;
m_deltaT[EM_DELTA_T_SIZE-1] = ((int)(m_deltaT[EM_DELTA_T_SIZE-1] + 1))%(EM_DELTA_T_SIZE-1);
// average the deltaT's
m_avgSamplingFreq = std::accumulate(m_deltaT.begin(),m_deltaT.end()-1,0.0)/(EM_DELTA_T_SIZE-1);
m_latestReading.clear();
m_latestReading.resize(4);
for(m_sensorID = 0; m_sensorID < m_numSensorsAttached; m_sensorID++)
{
// get the status of the last data record
// only report the data if everything is okay
unsigned int status = GetSensorStatus( m_sensorID );
if( status == VALID_STATUS)
{
// The rotations are reported in inverted form.
// You can check this in MATLAB
// Use the Cubes.exe provided by Ascension to get the azimuth, elevation, and roll.
// These are the Z,Y,X rotation angles.
// You can use the Robotics Toolbox by P. Corke and run convert from quat to rpy
// rad2deg(quat2rpy(q0,q1,q2,q3)) -> this gives you the X,Y,Z rotation angles (notice the flipped order!)
// Flipping the sign of q1,q2,q3 will fix the mismatch
// For a quaternion, this corresponds to the vector part being negated.
// record[m_sensorID].q[1] *= -1.0;
// record[m_sensorID].q[2] *= -1.0;
// record[m_sensorID].q[3] *= -1.0;
// transpose rotation matrix to invert it (R transpose = R inverse)
double temp = record[m_sensorID].s[1][0];
record[m_sensorID].s[1][0] = record[m_sensorID].s[0][1];
record[m_sensorID].s[0][1] = temp;
temp = record[m_sensorID].s[2][0];
record[m_sensorID].s[2][0] = record[m_sensorID].s[0][2];
record[m_sensorID].s[0][2] = temp;
temp = record[m_sensorID].s[1][2];
record[m_sensorID].s[1][2] = record[m_sensorID].s[2][1];
record[m_sensorID].s[2][1] = temp;
// transpose done
m_latestReading[m_sensorID] = record[m_sensorID];
emit logData(tstamp, m_sensorID, record[m_sensorID]);
//emit logData(tstamp, m_sensorID, record);
if( m_i == 0 ){
//emit sendDataToGUI(m_sensorID, formatOutput(tstamp, m_sensorID, record));
emit sendDataToGUI(m_sensorID, formatOutput(tstamp, m_sensorID, record[m_sensorID]));
}
}
else
qDebug() << "Invalid data received, sensorID:" << m_sensorID;
}
// if( m_i == 0 ){
// std::printf("EM rate: %.3f ms\n", m_avgSamplingFreq*1000.0);
// }
m_i = (m_i + 1)%(int)(m_samplingFreq/10);
// emit m_latestReading for use with the controller
emit sendLatestReading(m_latestReading);
}
void AscensionThread::stopAcquisition() // stop timer
{
QMutexLocker locker(m_mutex);
if ( m_keepRecording )
{
m_keepRecording = false;
m_timer->stop();
disconnect(m_timer,SIGNAL(timeout()),0,0);
delete m_timer;
emit logEvent(SRC_EM, LOG_INFO, QTime::currentTime(), EM_ACQUISITION_STOPPED);
emit statusChanged(EM_ACQUISITION_STOPPED);
}
}
bool AscensionThread::disconnectEM() // disconnect from EM
{
bool status = true;
stopAcquisition();
QMutexLocker locker(m_mutex);
// Turn off the transmitter before exiting
// We turn off the transmitter by "selecting" a transmitter with an id of "-1"
if(m_id != -1)
{
m_id = -1;
m_errorCode = SetSystemParameter(SELECT_TRANSMITTER, &m_id, sizeof(m_id));
if(m_errorCode != BIRD_ERROR_SUCCESS)
{
errorHandler_(m_errorCode);
emit statusChanged(EM_DISCONNECT_FAILED);
return status = false;
}
// Free memory allocations before exiting
delete[] m_pSensor;
delete[] m_pXmtr;
emit logEvent(SRC_EM, LOG_INFO, QTime::currentTime(), EM_DISCONNECTED);
emit statusChanged(EM_DISCONNECTED);
}
return status;
}
void AscensionThread::setEpoch(const QDateTime &datetime) // set Epoch
{
QMutexLocker locker(m_mutex);
if(!m_keepRecording)
{
m_epoch = datetime;
m_isEpochSet = true;
emit logEventWithMessage(SRC_EM, LOG_INFO, QTime::currentTime(), EM_EPOCH_SET,
m_epoch.toString("yyyy/MM/dd - hh:mm:ss.zzz"));
}
else
emit logEvent(SRC_EM, LOG_INFO, QTime::currentTime(), EM_EPOCH_SET_FAILED);
}
void AscensionThread::setSampleRate(int freq) // set freq
{
QMutexLocker locker(m_mutex);
// not recording
if(!m_keepRecording)
{
// freq too low, clamp
if( EM_MIN_SAMPLE_RATE > freq )
{
freq = EM_MIN_SAMPLE_RATE;
emit logError(SRC_EM, LOG_ERROR, QTime::currentTime(),
EM_BELOW_MIN_SAMPLE_RATE, QString::number(freq));
}
// freq too high, clamp
else if( EM_MAX_SAMPLE_RATE < freq )
{
freq = EM_ABOVE_MAX_SAMPLE_RATE;
emit logError(SRC_EM, LOG_ERROR, QTime::currentTime(),
EM_ABOVE_MAX_SAMPLE_RATE, QString::number(freq));
}
// set freq
double rate = freq*1.0f;
m_errorCode = SetSystemParameter(MEASUREMENT_RATE, &rate, sizeof(rate));
if(m_errorCode!=BIRD_ERROR_SUCCESS)
{
errorHandler_(m_errorCode);
emit statusChanged(EM_FREQ_SET_FAILED);
}
else
{
m_samplingFreq = freq;
// log event
emit logEventWithMessage(SRC_EM, LOG_INFO, QTime::currentTime(), EM_FREQ_SET,
QString::number(m_samplingFreq));
// emit status change
emit statusChanged(EM_FREQ_SET);
}
}
else
{
emit logError(SRC_EM, LOG_ERROR, QTime::currentTime(),
EM_CANT_MUTATE_WHILE_RUNNING, QString(""));
emit statusChanged(EM_FREQ_SET_FAILED);
}
}
// ----------------
// ACCESSORS
// ----------------
int AscensionThread::getSampleRate()
{
QMutexLocker locker(m_mutex);
return m_samplingFreq;
}
int AscensionThread::getNumSensors()
{
QMutexLocker locker(m_mutex);
return m_numSensorsAttached;
}
void AscensionThread::getLatestReading(const int sensorID, DOUBLE_POSITION_MATRIX_TIME_Q_RECORD &dataContainer)
{
QMutexLocker locker(m_mutex);
if(sensorID < 0)
qDebug() << "sensorID can not be negative!";
else if(sensorID < m_numSensorsAttached)
dataContainer = m_latestReading[sensorID];
else
qDebug() << "sensorID exceeds number of sensors!";
}
void AscensionThread::getLatestReadingsAll(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> &dataContainer)
{
QMutexLocker locker(m_mutex);
dataContainer = m_latestReading;
}
// ----------------
// HELPER FUNCTIONS
// ----------------
void AscensionThread::errorHandler_(int error)
{
char buffer[1024];
char *pBuffer = &buffer[0];
int numberBytes;
while(error!=BIRD_ERROR_SUCCESS)
{
QString msg(QString("Error Code %1: ").arg(QString::number(error)));
error = GetErrorText(error, pBuffer, sizeof(buffer), SIMPLE_MESSAGE);
numberBytes = strlen(buffer);
//buffer[numberBytes] = '\n'; // append a newline to buffer
//printf("%s", buffer);
msg.append(buffer);
qDebug() << msg;
emit logError(SRC_EM, LOG_ERROR, QTime::currentTime(), EM_FAIL, msg);
}
}
QString AscensionThread::formatOutput(QTime &timeStamp, const int sensorID, DOUBLE_POSITION_MATRIX_TIME_Q_RECORD &data)
{
QDateTime ts;
ts.setMSecsSinceEpoch(data.time*1000);
QString output;
output.append(QString("[Sensor %1 - %2] - ").arg(sensorID + 1).arg(EM_SENSOR_NAMES[sensorID]));
output.append(timeStamp.toString("HH.mm.ss.zzz\n"));
// output.append(QString("%1\t%2\t%3\n")
// .arg(QString::number(data.x,'f',m_prec))
// .arg(QString::number(data.y,'f',m_prec))
// .arg(QString::number(data.z,'f',m_prec)));
// TODO: comment out the quaternion
// output.append("Rot (Quat)\n");
// output.append(QString("%1\t%2\t%3\n%4\n")
// .arg(QString::number(data.q[0],'f',m_prec))
// .arg(QString::number(data.q[1],'f',m_prec))
// .arg(QString::number(data.q[2],'f',m_prec))
// .arg(QString::number(data.q[3],'f',m_prec)));
// QQuaternion qu = QQuaternion(data.q[0], data.q[1], data.q[2], data.q[3]);
// QMatrix3x3 mat = qu.toRotationMatrix();
output.append(QString("%1 %2 %3 %4\n%5 %6 %7 %8\n%9 %10 %11 %12\n")
.arg(QString::number(data.s[0][0],'f',m_prec))
.arg(QString::number(data.s[0][1],'f',m_prec))
.arg(QString::number(data.s[0][2],'f',m_prec))
.arg(QString::number(data.x ,'f',m_prec))
.arg(QString::number(data.s[1][0],'f',m_prec))
.arg(QString::number(data.s[1][1],'f',m_prec))
.arg(QString::number(data.s[1][2],'f',m_prec))
.arg(QString::number(data.y ,'f',m_prec))
.arg(QString::number(data.s[2][0],'f',m_prec))
.arg(QString::number(data.s[2][1],'f',m_prec))
.arg(QString::number(data.s[2][2],'f',m_prec))
.arg(QString::number(data.z ,'f',m_prec)));
output.append("Quality: ");
output.append(QString("%1\n")
.arg(QString::number(data.quality,'f',1)));
output.append(QString("Time: %1").arg(ts.toString("hh:mm:ss.zzz\n")));
return output;
}
inline const QString getCurrTimeStr()
{
return QTime::currentTime().toString("HH.mm.ss.zzz");
}
inline const QString getCurrDateTimeStr()
{
return QDateTime::currentDateTime().toString("yyyy/MM/dd - hh:mm:ss.zzz");
}
| 20,677 | C++ | 35.793594 | 128 | 0.5997 |
adegirmenci/HBL-ICEbot/AscensionWidget/ascensionwidget.cpp | #include "ascensionwidget.h"
#include "ui_ascensionwidget.h"
AscensionWidget::AscensionWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::AscensionWidget)
{
ui->setupUi(this);
m_worker = new AscensionThread;
m_worker->moveToThread(&m_thread);
connect(&m_thread, &QThread::finished, m_worker, &QObject::deleteLater);
m_thread.start();
connect(ui->initButton, SIGNAL(clicked()), m_worker, SLOT(initializeEM()));
connect(ui->acquireButton, SIGNAL(clicked()), m_worker, SLOT(startAcquisition()));
connect(ui->stopButton, SIGNAL(clicked()), m_worker, SLOT(stopAcquisition()));
connect(ui->disconnectButton, SIGNAL(clicked()), m_worker, SLOT(disconnectEM()));
connect(m_worker, SIGNAL(statusChanged(int)), this, SLOT(workerStatusChanged(int)));
connect(m_worker, SIGNAL(sendDataToGUI(int,QString)),
this, SLOT(receiveDataFromWorker(int,QString)));
}
AscensionWidget::~AscensionWidget()
{
m_thread.quit();
m_thread.wait();
qDebug() << "Ascension thread quit.";
delete ui;
}
void AscensionWidget::workerStatusChanged(int status)
{
switch(status)
{
case EM_INITIALIZE_BEGIN:
ui->initButton->setEnabled(false);
ui->statusLineEdit->setText("Initializing...");
ui->outputTextEdit->appendPlainText("Initializing...This will take a minute.");
break;
case EM_INITIALIZE_FAILED:
ui->initButton->setEnabled(true);
ui->statusLineEdit->setText("Initialization failed!");
ui->outputTextEdit->appendPlainText("Initialization failed!");
break;
case EM_INITIALIZED:
ui->initButton->setEnabled(false);
ui->disconnectButton->setEnabled(true);
ui->acquireButton->setEnabled(true);
ui->outputTextEdit->appendPlainText(QString("%1 sensor(s) plugged in.")
.arg(m_worker->getNumSensors()));
ui->outputTextEdit->appendPlainText(QString("Measurement Rate: %1Hz")
.arg(m_worker->getSampleRate()));
ui->numBirdsComboBox->setCurrentIndex(m_worker->getNumSensors());
break;
case EM_DISCONNECT_FAILED:
ui->statusLineEdit->setText("Disconnection failed.");
ui->outputTextEdit->appendPlainText("Disconnection failed! FATAL ERROR!");
break;
case EM_DISCONNECTED:
ui->initButton->setEnabled(true);
ui->disconnectButton->setEnabled(false);
ui->acquireButton->setEnabled(false);
ui->statusLineEdit->setText("Disconnected.");
ui->outputTextEdit->appendPlainText("Disconnected.");
break;
case EM_FREQ_SET_FAILED:
ui->outputTextEdit->appendPlainText("Sample rate could not be changed!");
break;
case EM_FREQ_SET:
ui->outputTextEdit->appendPlainText(QString("Sample rate changed to %1Hz.")
.arg(m_worker->getSampleRate()));
break;
case EM_ACQUISITION_STARTED:
ui->statusLineEdit->setText("Acquiring data.");
ui->acquireButton->setEnabled(false);
ui->stopButton->setEnabled(true);
break;
case EM_ACQUISITION_STOPPED:
ui->statusLineEdit->setText("Acquisition stopped.");
ui->acquireButton->setEnabled(true);
ui->stopButton->setEnabled(false);
break;
case EM_ACQUIRE_FAILED:
ui->statusLineEdit->setText("Acquisition failed.");
break;
default:
ui->statusLineEdit->setText("Unknown state!");
break;
}
}
void AscensionWidget::receiveDataFromWorker(int sensorID, const QString &data)
{
if(sensorID == 0)
ui->outputTextEdit->clear();
ui->outputTextEdit->appendPlainText(data);
}
void AscensionWidget::on_initButton_clicked()
{
ui->initButton->setEnabled(false);
}
| 3,849 | C++ | 34.321101 | 88 | 0.639127 |
adegirmenci/HBL-ICEbot/AscensionWidget/ascensionwidget.h | #ifndef ASCENSIONWIDGET_H
#define ASCENSIONWIDGET_H
#include <QWidget>
#include <QThread>
#include "ascensionthread.h"
namespace Ui {
class AscensionWidget;
}
class AscensionWidget : public QWidget
{
Q_OBJECT
public:
explicit AscensionWidget(QWidget *parent = 0);
~AscensionWidget();
AscensionThread *m_worker;
private slots:
void workerStatusChanged(int status);
void on_initButton_clicked();
void receiveDataFromWorker(int sensorID, const QString &data);
private:
Ui::AscensionWidget *ui;
QThread m_thread; // Ascension Thread will live in here
};
#endif // ASCENSIONWIDGET_H
| 625 | C | 16.388888 | 66 | 0.728 |
adegirmenci/HBL-ICEbot/AscensionWidget/3DGAPI/ATC3DG.h | //*****************************************************************************//
//*****************************************************************************//
//
// Author: crobertson
//
// Revision for ATC3DG 36.0.19.7
//
//
// Date: 02/01/2012
//
// COPYRIGHT: COPYRIGHT ASCENSION TECHNOLOGY CORPORATION - 2012
//
//*****************************************************************************//
//*****************************************************************************//
//
// DESCRIPTION: ATC3DG3.h
//
// Header file containing function prototypes for the BIRD system API
// Also contains definitions of constants and structures required.
//
//*****************************************************************************//
//*****************************************************************************//
#ifndef ATC3DG_H
#define ATC3DG_H
#ifdef LINUX
#define ATC3DG_API
#else
#ifdef MAC
#define ATC3DG_API
#else
#ifdef DEF_FILE
#define ATC3DG_API
#else
#ifdef ATC3DG_EXPORTS
#define ATC3DG_API extern "C" __declspec(dllexport)
#else
#define ATC3DG_API extern "C" __declspec(dllimport)
#endif
#endif
#endif
#endif
/*****************************************************************************
ENUMERATED CONSTANTS
*****************************************************************************/
//*****************************************************************************
//
// ERROR MESSAGE format is as follows:
// ===================================
//
// All commands return a 32-bit integer with the following bit definitions:
//
// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
// +-+-+-+-+-+-+---------+---------+-------------------------------+
// |E|W|X|R|B|M| Reserved| Address | Code |
// +-+-+-+-+-+-+---------+---------+-------------------------------+
//
// where
//
// E - indicates an ERROR
// (Operation either cannot or will not proceed as intended
// e.g. EEPROM error of some kind. Requires hardware reset
// of system and/or replacement of hardware)
// W - indicates a WARNING
// (Operation may proceed but remedial action needs to be taken
// e.g. Sensor has been removed. Fix by replacing Sensor)
// X - indicates Transmitter related message
// R - indicates Sensor related message
// (If neither X nor R is set then the message is a SYSTEM message)
// B - indicates message originated in the BIRD hardware
// M - indicates there are more messages pending (no longer used)
//
// Address gives the index number of the device generating the message
// (Driver and system messages always have address 0)
//
// Code - is the status code as enumerated in BIRD_ERROR_CODES
//
//*****************************************************************************
enum BIRD_ERROR_CODES
{
// ERROR CODE DISPOSITION
// | (Some error codes have been retired.
// | The column below describes which codes
// | have been retired and why. O = Obolete,
// V I = handled internally)
BIRD_ERROR_SUCCESS=0, //00 < > No error
BIRD_ERROR_PCB_HARDWARE_FAILURE, //01 < > indeterminate failure on PCB
BIRD_ERROR_TRANSMITTER_EEPROM_FAILURE, //02 <I> transmitter bad eeprom
BIRD_ERROR_SENSOR_SATURATION_START, //03 <I> sensor has gone into saturation
BIRD_ERROR_ATTACHED_DEVICE_FAILURE, //04 <O> either a sensor or transmitter reports bad
BIRD_ERROR_CONFIGURATION_DATA_FAILURE, //05 <O> device EEPROM detected but corrupt
BIRD_ERROR_ILLEGAL_COMMAND_PARAMETER, //06 < > illegal PARAMETER_TYPE passed to driver
BIRD_ERROR_PARAMETER_OUT_OF_RANGE, //07 < > PARAMETER_TYPE legal, but PARAMETER out of range
BIRD_ERROR_NO_RESPONSE, //08 <O> no response at all from target card firmware
BIRD_ERROR_COMMAND_TIME_OUT, //09 < > time out before response from target board
BIRD_ERROR_INCORRECT_PARAMETER_SIZE, //10 < > size of parameter passed is incorrect
BIRD_ERROR_INVALID_VENDOR_ID, //11 <O> driver started with invalid PCI vendor ID
BIRD_ERROR_OPENING_DRIVER, //12 < > couldn't start driver
BIRD_ERROR_INCORRECT_DRIVER_VERSION, //13 < > wrong driver version found
BIRD_ERROR_NO_DEVICES_FOUND, //14 < > no BIRDs were found anywhere
BIRD_ERROR_ACCESSING_PCI_CONFIG, //15 < > couldn't access BIRDs config space
BIRD_ERROR_INVALID_DEVICE_ID, //16 < > device ID out of range
BIRD_ERROR_FAILED_LOCKING_DEVICE, //17 < > couldn't lock driver
BIRD_ERROR_BOARD_MISSING_ITEMS, //18 < > config space items missing
BIRD_ERROR_NOTHING_ATTACHED, //19 <O> card found but no sensors or transmitters attached
BIRD_ERROR_SYSTEM_PROBLEM, //20 <O> non specific system problem
BIRD_ERROR_INVALID_SERIAL_NUMBER, //21 <O> serial number does not exist in system
BIRD_ERROR_DUPLICATE_SERIAL_NUMBER, //22 <O> 2 identical serial numbers passed in set command
BIRD_ERROR_FORMAT_NOT_SELECTED, //23 <O> data format not selected yet
BIRD_ERROR_COMMAND_NOT_IMPLEMENTED, //24 < > valid command, not implemented yet
BIRD_ERROR_INCORRECT_BOARD_DEFAULT, //25 < > incorrect response to reading parameter
BIRD_ERROR_INCORRECT_RESPONSE, //26 <O> response received, but data,values in error
BIRD_ERROR_NO_TRANSMITTER_RUNNING, //27 < > there is no transmitter running
BIRD_ERROR_INCORRECT_RECORD_SIZE, //28 < > data record size does not match data format size
BIRD_ERROR_TRANSMITTER_OVERCURRENT, //29 <I> transmitter over-current detected
BIRD_ERROR_TRANSMITTER_OPEN_CIRCUIT, //30 <I> transmitter open circuit or removed
BIRD_ERROR_SENSOR_EEPROM_FAILURE, //31 <I> sensor bad eeprom
BIRD_ERROR_SENSOR_DISCONNECTED, //32 <I> previously good sensor has been removed
BIRD_ERROR_SENSOR_REATTACHED, //33 <I> previously good sensor has been reattached
BIRD_ERROR_NEW_SENSOR_ATTACHED, //34 <O> new sensor attached
BIRD_ERROR_UNDOCUMENTED, //35 <I> undocumented error code received from bird
BIRD_ERROR_TRANSMITTER_REATTACHED, //36 <I> previously good transmitter has been reattached
BIRD_ERROR_WATCHDOG, //37 < > watchdog timeout
BIRD_ERROR_CPU_TIMEOUT_START, //38 <I> CPU ran out of time executing algorithm (start)
BIRD_ERROR_PCB_RAM_FAILURE, //39 <I> BIRD on-board RAM failure
BIRD_ERROR_INTERFACE, //40 <I> BIRD PCI interface error
BIRD_ERROR_PCB_EPROM_FAILURE, //41 <I> BIRD on-board EPROM failure
BIRD_ERROR_SYSTEM_STACK_OVERFLOW, //42 <I> BIRD program stack overrun
BIRD_ERROR_QUEUE_OVERRUN, //43 <I> BIRD error message queue overrun
BIRD_ERROR_PCB_EEPROM_FAILURE, //44 <I> PCB bad EEPROM
BIRD_ERROR_SENSOR_SATURATION_END, //45 <I> Sensor has gone out of saturation
BIRD_ERROR_NEW_TRANSMITTER_ATTACHED, //46 <O> new transmitter attached
BIRD_ERROR_SYSTEM_UNINITIALIZED, //47 < > InitializeBIRDSystem not called yet
BIRD_ERROR_12V_SUPPLY_FAILURE, //48 <I > 12V Power supply not within specification
BIRD_ERROR_CPU_TIMEOUT_END, //49 <I> CPU ran out of time executing algorithm (end)
BIRD_ERROR_INCORRECT_PLD, //50 < > PCB PLD not compatible with this API DLL
BIRD_ERROR_NO_TRANSMITTER_ATTACHED, //51 < > No transmitter attached to this ID
BIRD_ERROR_NO_SENSOR_ATTACHED, //52 < > No sensor attached to this ID
// new error codes added 2/27/03
// (Version 1,31,5,01) multi-sensor, synchronized
BIRD_ERROR_SENSOR_BAD, //53 < > Non-specific hardware problem
BIRD_ERROR_SENSOR_SATURATED, //54 < > Sensor saturated error
BIRD_ERROR_CPU_TIMEOUT, //55 < > CPU unable to complete algorithm on current cycle
BIRD_ERROR_UNABLE_TO_CREATE_FILE, //56 < > Could not create and open file for saving setup
BIRD_ERROR_UNABLE_TO_OPEN_FILE, //57 < > Could not open file for restoring setup
BIRD_ERROR_MISSING_CONFIGURATION_ITEM, //58 < > Mandatory item missing from configuration file
BIRD_ERROR_MISMATCHED_DATA, //59 < > Data item in file does not match system value
BIRD_ERROR_CONFIG_INTERNAL, //60 < > Internal error in config file handler
BIRD_ERROR_UNRECOGNIZED_MODEL_STRING, //61 < > Board does not have a valid model string
BIRD_ERROR_INCORRECT_SENSOR, //62 < > Invalid sensor type attached to this board
BIRD_ERROR_INCORRECT_TRANSMITTER, //63 < > Invalid transmitter type attached to this board
// new error code added 1/18/05
// (Version 1.31.5.22)
// multi-sensor,
// synchronized-fluxgate,
// integrating micro-sensor,
// flat panel transmitter
BIRD_ERROR_ALGORITHM_INITIALIZATION, //64 < > Flat panel algorithm initialization failed
// new error code for multi-sync
BIRD_ERROR_LOST_CONNECTION, //65 < > USB connection has been lost
BIRD_ERROR_INVALID_CONFIGURATION, //66 < > Invalid configuration
// VPD error code
BIRD_ERROR_TRANSMITTER_RUNNING, //67 < > TX running while reading/writing VPD
BIRD_ERROR_MAXIMUM_VALUE = 0x7F // ## value = number of error codes ##
};
// error message defines
#define ERROR_FLAG 0x80000000
#define WARNING_FLAG 0x40000000
#define XMTR_ERROR_SOURCE 0x20000000
#define RCVR_ERROR_SOURCE 0x10000000
#define BIRD_ERROR_SOURCE 0x08000000
#define DIAG_ERROR_SOURCE 0x04000000
// SYSTEM error = none of the above
// NOTE: The MULTIPLE_ERRORS flag is no longer generated
// It has been left in for backwards compatibility
#define MULTIPLE_ERRORS 0x04000000
// DEVICE STATUS ERROR BIT DEFINITIONS
#define VALID_STATUS 0x00000000
#define GLOBAL_ERROR 0x00000001
#define NOT_ATTACHED 0x00000002
#define SATURATED 0x00000004
#define BAD_EEPROM 0x00000008
#define HARDWARE 0x00000010
#define NON_EXISTENT 0x00000020
#define UNINITIALIZED 0x00000040
#define NO_TRANSMITTER_RUNNING 0x00000080
#define BAD_12V 0x00000100
#define CPU_TIMEOUT 0x00000200
#define INVALID_DEVICE 0x00000400
#define NO_TRANSMITTER_ATTACHED 0x00000800
#define OUT_OF_MOTIONBOX 0x00001000
#define ALGORITHM_INITIALIZING 0x00002000
#define TRUE 1
#define FALSE 0
enum MESSAGE_TYPE
{
SIMPLE_MESSAGE, // short string describing error code
VERBOSE_MESSAGE, // long string describing error code
};
enum TRANSMITTER_PARAMETER_TYPE
{
SERIAL_NUMBER_TX, // attached transmitter's serial number
REFERENCE_FRAME, // structure of type DOUBLE_ANGLES_RECORD
XYZ_REFERENCE_FRAME, // boolean value to select/deselect mode
VITAL_PRODUCT_DATA_TX, // single byte parameter to be read/write from VPD section of xmtr EEPROM
MODEL_STRING_TX, // 11 byte null terminated character string
PART_NUMBER_TX, // 16 byte null terminated character string
END_OF_TX_LIST
};
enum SENSOR_PARAMETER_TYPE
{
DATA_FORMAT, // enumerated constant of type DATA_FORMAT_TYPE
ANGLE_ALIGN, // structure of type DOUBLE_ANGLES_RECORD
HEMISPHERE, // enumerated constant of type HEMISPHERE_TYPE
FILTER_AC_WIDE_NOTCH, // boolean value to select/deselect filter
FILTER_AC_NARROW_NOTCH, // boolean value to select/deselect filter
FILTER_DC_ADAPTIVE, // double value in range 0.0 (no filtering) to 1.0 (max)
FILTER_ALPHA_PARAMETERS,// structure of type ADAPTIVE_PARAMETERS
FILTER_LARGE_CHANGE, // boolean value to select/deselect filter
QUALITY, // structure of type QUALITY_PARAMETERS
SERIAL_NUMBER_RX, // attached sensor's serial number
SENSOR_OFFSET, // structure of type DOUBLE_POSITION_RECORD
VITAL_PRODUCT_DATA_RX, // single byte parameter to be read/write from VPD section of sensor EEPROM
VITAL_PRODUCT_DATA_PREAMP, // single byte parameter to be read/write from VPD section of preamp EEPROM
MODEL_STRING_RX, // 11 byte null terminated character string
PART_NUMBER_RX, // 16 byte null terminated character string
MODEL_STRING_PREAMP, // 11 byte null terminated character string
PART_NUMBER_PREAMP, // 16 byte null terminated character string
PORT_CONFIGURATION, // enumerated constant of type PORT_CONFIGURATION_TYPE
END_OF_RX_LIST
};
enum BOARD_PARAMETER_TYPE
{
SERIAL_NUMBER_PCB, // installed board's serial number
BOARD_SOFTWARE_REVISIONS, // BOARD_REVISIONS structure
POST_ERROR_PCB, // board POST_ERROR_PARAMETER
DIAGNOSTIC_TEST_PCB, // board DIAGNOSTIC_TEST_PARAMETER
VITAL_PRODUCT_DATA_PCB, // single byte parameter to be read/write from VPD section of board EEPROM
MODEL_STRING_PCB, // 11 byte null terminated character string
PART_NUMBER_PCB, // 16 byte null terminated character string
END_OF_PCB_LIST_BRD
};
enum SYSTEM_PARAMETER_TYPE
{
SELECT_TRANSMITTER, // short int equal to transmitterID of selected transmitter
POWER_LINE_FREQUENCY, // double value (range is hardware dependent)
AGC_MODE, // enumerated constant of type AGC_MODE_TYPE
MEASUREMENT_RATE, // double value (range is hardware dependent)
MAXIMUM_RANGE, // double value (range is hardware dependent)
METRIC, // boolean value to select metric units for position
VITAL_PRODUCT_DATA, // single byte parameter to be read/write from VPD section of board EEPROM
POST_ERROR, // system (board 0) POST_ERROR_PARAMETER
DIAGNOSTIC_TEST, // system (board 0) DIAGNOSTIC_TEST_PARAMETER
REPORT_RATE, // single byte 1-127
COMMUNICATIONS_MEDIA, // Media structure
LOGGING, // Boolean
RESET, // Boolean
AUTOCONFIG, // BYTE 1-127
AUXILIARY_PORT, // structure of type AUXILIARY_PORT_PARAMETERS
COMMUTATION_MODE, // boolean value to select commutation of sensor data for interconnect pickup rejection
END_OF_LIST // end of list place holder
};
enum COMMUNICATIONS_MEDIA_TYPE
{
USB, // Auto select USB driver
RS232, // Force to RS232
TCPIP // Force to TCP/IP
};
enum FILTER_OPTION
{
NO_FILTER,
DEFAULT_FLOCK_FILTER
};
enum HEMISPHERE_TYPE
{
FRONT,
BACK,
TOP,
BOTTOM,
LEFT,
RIGHT
};
enum AGC_MODE_TYPE
{
TRANSMITTER_AND_SENSOR_AGC, // Old style normal addressing mode
SENSOR_AGC_ONLY // Old style extended addressing mode
};
enum PORT_CONFIGURATION_TYPE
{
DOF_NOT_ACTIVE, // No sensor associated with this ID, e.g. ID 5 on a 6DOF port
DOF_6_XYZ_AER, // 6 degrees of freedom
DOF_5_XYZ_AE, // 5 degrees of freedom, no roll
};
enum AUXILIARY_PORT_TYPE
{
AUX_PORT_NOT_SUPPORTED, // There is no auxiliary port associated with this sensor port
AUX_PORT_NOT_SELECTED, // The auxiliary port is not selected.
AUX_PORT_SELECTED, // The auxiliary port is selected.
};
enum DATA_FORMAT_TYPE
{
NO_FORMAT_SELECTED=0,
// SHORT (integer) formats
SHORT_POSITION,
SHORT_ANGLES,
SHORT_MATRIX,
SHORT_QUATERNIONS,
SHORT_POSITION_ANGLES,
SHORT_POSITION_MATRIX,
SHORT_POSITION_QUATERNION,
// DOUBLE (floating point) formats
DOUBLE_POSITION,
DOUBLE_ANGLES,
DOUBLE_MATRIX,
DOUBLE_QUATERNIONS,
DOUBLE_POSITION_ANGLES, // system default
DOUBLE_POSITION_MATRIX,
DOUBLE_POSITION_QUATERNION,
// DOUBLE (floating point) formats with time stamp appended
DOUBLE_POSITION_TIME_STAMP,
DOUBLE_ANGLES_TIME_STAMP,
DOUBLE_MATRIX_TIME_STAMP,
DOUBLE_QUATERNIONS_TIME_STAMP,
DOUBLE_POSITION_ANGLES_TIME_STAMP,
DOUBLE_POSITION_MATRIX_TIME_STAMP,
DOUBLE_POSITION_QUATERNION_TIME_STAMP,
// DOUBLE (floating point) formats with time stamp appended and quality #
DOUBLE_POSITION_TIME_Q,
DOUBLE_ANGLES_TIME_Q,
DOUBLE_MATRIX_TIME_Q,
DOUBLE_QUATERNIONS_TIME_Q,
DOUBLE_POSITION_ANGLES_TIME_Q,
DOUBLE_POSITION_MATRIX_TIME_Q,
DOUBLE_POSITION_QUATERNION_TIME_Q,
// These DATA_FORMAT_TYPE codes contain every format in a single structure
SHORT_ALL,
DOUBLE_ALL,
DOUBLE_ALL_TIME_STAMP,
DOUBLE_ALL_TIME_STAMP_Q,
DOUBLE_ALL_TIME_STAMP_Q_RAW, // this format contains a raw data matrix and
// is for factory use only...
// DOUBLE (floating point) formats with time stamp appended, quality # and button
DOUBLE_POSITION_ANGLES_TIME_Q_BUTTON,
DOUBLE_POSITION_MATRIX_TIME_Q_BUTTON,
DOUBLE_POSITION_QUATERNION_TIME_Q_BUTTON,
// New types for button and wrapper
DOUBLE_POSITION_ANGLES_MATRIX_QUATERNION_TIME_Q_BUTTON,
MAXIMUM_FORMAT_CODE
};
enum BOARD_TYPES
{
ATC3DG_MEDSAFE, // Standalone, DSP, 4 sensor
PCIBIRD_STD1, // single standard sensor
PCIBIRD_STD2, // dual standard sensor
PCIBIRD_8mm1, // single 8mm sensor
PCIBIRD_8mm2, // dual 8mm sensor
PCIBIRD_2mm1, // single 2mm sensor (microsensor)
PCIBIRD_2mm2, // dual 2mm sensor (microsensor)
PCIBIRD_FLAT, // flat transmitter, 8mm
PCIBIRD_FLAT_MICRO1, // flat transmitter, single TEM sensor (all types)
PCIBIRD_FLAT_MICRO2, // flat transmitter, dual TEM sensor (all types)
PCIBIRD_DSP4, // Standalone, DSP, 4 sensor
PCIBIRD_UNKNOWN, // default
ATC3DG_BB // BayBird
};
enum DEVICE_TYPES
{
STANDARD_SENSOR, // 25mm standard sensor
TYPE_800_SENSOR, // 8mm sensor
STANDARD_TRANSMITTER, // TX for 25mm sensor
MINIBIRD_TRANSMITTER, // TX for 8mm sensor
SMALL_TRANSMITTER, // "compact" transmitter
TYPE_500_SENSOR, // 5mm sensor
TYPE_180_SENSOR, // 1.8mm microsensor
TYPE_130_SENSOR, // 1.3mm microsensor
TYPE_TEM_SENSOR, // 1.8mm, 1.3mm, 0.Xmm microsensors
UNKNOWN_SENSOR, // default
UNKNOWN_TRANSMITTER, // default
TYPE_800_BB_SENSOR, // BayBird sensor
TYPE_800_BB_STD_TRANSMITTER, // BayBird standard TX
TYPE_800_BB_SMALL_TRANSMITTER, // BayBird small TX
TYPE_090_BB_SENSOR // Baybird 0.9 mm sensor
};
// Async and Sync sensor id parameter
#define ALL_SENSORS 0xffff
/*****************************************************************************
TYPEDEF DEFINITIONS
*****************************************************************************/
#ifndef BASETYPES
#define BASETYPES
typedef unsigned long ULONG;
typedef ULONG *PULONG;
typedef unsigned short USHORT;
typedef USHORT *PUSHORT;
typedef short SHORT;
typedef SHORT *PSHORT;
typedef unsigned char UCHAR;
typedef UCHAR *PUCHAR;
typedef char *PSZ;
#endif /* !BASETYPES */
typedef char CHAR;
typedef const CHAR *LPCSTR, *PCSTR;
typedef int BOOL;
typedef ULONG DEVICE_STATUS;
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef unsigned long DWORD;
/*****************************************************************************
STRUCTURE DEFINITIONS
*****************************************************************************/
typedef struct tagTRANSMITTER_CONFIGURATION
{
ULONG serialNumber;
USHORT boardNumber;
USHORT channelNumber;
enum DEVICE_TYPES type;
BOOL attached;
} TRANSMITTER_CONFIGURATION;
typedef struct tagSENSOR_CONFIGURATION
{
ULONG serialNumber;
USHORT boardNumber;
USHORT channelNumber;
enum DEVICE_TYPES type;
BOOL attached;
} SENSOR_CONFIGURATION;
typedef struct tagBOARD_CONFIGURATION
{
ULONG serialNumber;
enum BOARD_TYPES type;
USHORT revision;
USHORT numberTransmitters;
USHORT numberSensors;
USHORT firmwareNumber;
USHORT firmwareRevision;
char modelString[10];
} BOARD_CONFIGURATION;
typedef struct tagSYSTEM_CONFIGURATION
{
double measurementRate;
double powerLineFrequency;
double maximumRange;
enum AGC_MODE_TYPE agcMode;
int numberBoards;
int numberSensors;
int numberTransmitters;
int transmitterIDRunning;
BOOL metric;
} SYSTEM_CONFIGURATION;
typedef struct tagCOMMUNICATIONS_MEDIA_PARAMETERS
{
COMMUNICATIONS_MEDIA_TYPE mediaType;
union
{
struct
{
CHAR comport[64];
} rs232;
struct
{
USHORT port;
CHAR ipaddr[64];
} tcpip;
};
} COMMUNICATIONS_MEDIA_PARAMETERS;
typedef struct tagADAPTIVE_PARAMETERS
{
USHORT alphaMin[7];
USHORT alphaMax[7];
USHORT vm[7];
BOOL alphaOn;
} ADAPTIVE_PARAMETERS;
typedef struct tagQUALITY_PARAMETERS
{
SHORT error_slope;
SHORT error_offset;
USHORT error_sensitivity;
USHORT filter_alpha;
} QUALITY_PARAMETERS;
// New Drivebay system parameter structure(s)
typedef struct tagVPD_COMMAND_PARAMETER
{
USHORT address;
UCHAR value;
} VPD_COMMAND_PARAMETER;
typedef struct tagPOST_ERROR_PARAMETER
{
USHORT error;
UCHAR channel;
UCHAR fatal;
UCHAR moreErrors;
} POST_ERROR_PARAMETER;
typedef struct tagDIAGNOSTIC_TEST_PARAMETER
{
UCHAR suite; // User sets this, 0 - All Suites
UCHAR test; // User sets this, 0 - All Tests
UCHAR suites; // set, returns suites run
// get, returns num of suites, not used for # test query
UCHAR tests; // set, returns tests run in the given suite
// get, returns num of tests for given suite, not used for suite query
PUCHAR pTestName; // User supplied ptr to 64 bytes, we fill it in
USHORT testNameLen;
USHORT diagError; // set only, result of diagnostic execution
} DIAGNOSTIC_TEST_PARAMETER;
typedef struct tagBOARD_REVISIONS
{
USHORT boot_loader_sw_number; // example 3.1 -> revision is 3, number is 1
USHORT boot_loader_sw_revision;
USHORT mdsp_sw_number;
USHORT mdsp_sw_revision;
USHORT nondipole_sw_number;
USHORT nondipole_sw_revision;
USHORT fivedof_sw_number;
USHORT fivedof_sw_revision;
USHORT sixdof_sw_number;
USHORT sixdof_sw_revision;
USHORT dipole_sw_number;
USHORT dipole_sw_revision;
} BOARD_REVISIONS;
typedef struct tagAUXILIARY_PORT_PARAMETERS
{
AUXILIARY_PORT_TYPE auxstate[4]; // one state for each sensor port
} AUXILIARY_PORT_PARAMETERS;
//
// Data formatting structures
//
typedef struct tagSHORT_POSITION
{
short x;
short y;
short z;
} SHORT_POSITION_RECORD;
typedef struct tagSHORT_ANGLES
{
short a; // azimuth
short e; // elevation
short r; // roll
} SHORT_ANGLES_RECORD;
typedef struct tagSHORT_MATRIX
{
short s[3][3];
} SHORT_MATRIX_RECORD;
typedef struct tagSHORT_QUATERNIONS
{
short q[4];
} SHORT_QUATERNIONS_RECORD;
typedef struct tagSHORT_POSITION_ANGLES
{
short x;
short y;
short z;
short a;
short e;
short r;
} SHORT_POSITION_ANGLES_RECORD;
typedef struct tagSHORT_POSITION_MATRIX
{
short x;
short y;
short z;
short s[3][3];
} SHORT_POSITION_MATRIX_RECORD;
typedef struct tagSHORT_POSITION_QUATERNION
{
short x;
short y;
short z;
short q[4];
} SHORT_POSITION_QUATERNION_RECORD;
typedef struct tagDOUBLE_POSITION
{
double x;
double y;
double z;
} DOUBLE_POSITION_RECORD;
typedef struct tagDOUBLE_ANGLES
{
double a; // azimuth
double e; // elevation
double r; // roll
} DOUBLE_ANGLES_RECORD;
typedef struct tagDOUBLE_MATRIX
{
double s[3][3];
} DOUBLE_MATRIX_RECORD;
typedef struct tagDOUBLE_QUATERNIONS
{
double q[4];
} DOUBLE_QUATERNIONS_RECORD;
typedef struct tagDOUBLE_POSITION_ANGLES
{
double x;
double y;
double z;
double a;
double e;
double r;
} DOUBLE_POSITION_ANGLES_RECORD;
typedef struct tagDOUBLE_POSITION_MATRIX
{
double x;
double y;
double z;
double s[3][3];
} DOUBLE_POSITION_MATRIX_RECORD;
typedef struct tagDOUBLE_POSITION_QUATERNION
{
double x;
double y;
double z;
double q[4];
} DOUBLE_POSITION_QUATERNION_RECORD;
typedef struct tagDOUBLE_POSITION_TIME_STAMP
{
double x;
double y;
double z;
double time;
} DOUBLE_POSITION_TIME_STAMP_RECORD;
typedef struct tagDOUBLE_ANGLES_TIME_STAMP
{
double a; // azimuth
double e; // elevation
double r; // roll
double time;
} DOUBLE_ANGLES_TIME_STAMP_RECORD;
typedef struct tagDOUBLE_MATRIX_TIME_STAMP
{
double s[3][3];
double time;
} DOUBLE_MATRIX_TIME_STAMP_RECORD;
typedef struct tagDOUBLE_QUATERNIONS_TIME_STAMP
{
double q[4];
double time;
} DOUBLE_QUATERNIONS_TIME_STAMP_RECORD;
typedef struct tagDOUBLE_POSITION_ANGLES_TIME_STAMP
{
double x;
double y;
double z;
double a;
double e;
double r;
double time;
} DOUBLE_POSITION_ANGLES_TIME_STAMP_RECORD;
typedef struct tagDOUBLE_POSITION_MATRIX_STAMP_RECORD
{
double x;
double y;
double z;
double s[3][3];
double time;
} DOUBLE_POSITION_MATRIX_TIME_STAMP_RECORD;
typedef struct tagDOUBLE_POSITION_QUATERNION_STAMP_RECORD
{
double x;
double y;
double z;
double q[4];
double time;
} DOUBLE_POSITION_QUATERNION_TIME_STAMP_RECORD;
typedef struct tagDOUBLE_POSITION_TIME_Q
{
double x;
double y;
double z;
double time;
USHORT quality;
} DOUBLE_POSITION_TIME_Q_RECORD;
typedef struct tagDOUBLE_ANGLES_TIME_Q
{
double a; // azimuth
double e; // elevation
double r; // roll
double time;
USHORT quality;
} DOUBLE_ANGLES_TIME_Q_RECORD;
typedef struct tagDOUBLE_MATRIX_TIME_Q
{
double s[3][3];
double time;
USHORT quality;
} DOUBLE_MATRIX_TIME_Q_RECORD;
typedef struct tagDOUBLE_QUATERNIONS_TIME_Q
{
double q[4];
double time;
USHORT quality;
} DOUBLE_QUATERNIONS_TIME_Q_RECORD;
typedef struct tagDOUBLE_POSITION_ANGLES_TIME_Q_RECORD
{
double x;
double y;
double z;
double a;
double e;
double r;
double time;
USHORT quality;
} DOUBLE_POSITION_ANGLES_TIME_Q_RECORD;
typedef struct tagDOUBLE_POSITION_MATRIX_TIME_Q_RECORD
{
double x;
double y;
double z;
double s[3][3];
double time;
USHORT quality;
} DOUBLE_POSITION_MATRIX_TIME_Q_RECORD;
typedef struct tagDOUBLE_POSITION_QUATERNION_TIME_Q_RECORD
{
double x;
double y;
double z;
double q[4];
double time;
USHORT quality;
} DOUBLE_POSITION_QUATERNION_TIME_Q_RECORD;
typedef struct tagDOUBLE_POSITION_ANGLES_TIME_Q_BUTTON_RECORD
{
double x;
double y;
double z;
double a;
double e;
double r;
double time;
USHORT quality;
USHORT button;
} DOUBLE_POSITION_ANGLES_TIME_Q_BUTTON_RECORD;
typedef struct tagDOUBLE_POSITION_MATRIX_TIME_Q_BUTTON_RECORD
{
double x;
double y;
double z;
double s[3][3];
double time;
USHORT quality;
USHORT button;
} DOUBLE_POSITION_MATRIX_TIME_Q_BUTTON_RECORD;
typedef struct tagDOUBLE_POSITION_QUATERNION_TIME_Q_BUTTON_RECORD
{
double x;
double y;
double z;
double q[4];
double time;
USHORT quality;
USHORT button;
} DOUBLE_POSITION_QUATERNION_TIME_Q_BUTTON_RECORD;
typedef struct tagDOUBLE_POSITION_ANGLES_MATRIX_QUATERNION_TIME_Q_BUTTON_RECORD
{
double x;
double y;
double z;
double a;
double e;
double r;
double s[3][3];
double q[4];
double time;
USHORT quality;
USHORT button;
} DOUBLE_POSITION_ANGLES_MATRIX_QUATERNION_TIME_Q_BUTTON_RECORD;
typedef struct tagSHORT_ALL_RECORD
{
short x;
short y;
short z;
short a; // azimuth
short e; // elevation
short r; // roll
short s[3][3];
short q[4];
}SHORT_ALL_RECORD;
typedef struct tagDOUBLE_ALL_RECORD
{
double x;
double y;
double z;
double a; // azimuth
double e; // elevation
double r; // roll
double s[3][3];
double q[4];
}DOUBLE_ALL_RECORD;
typedef struct tagDOUBLE_ALL_TIME_STAMP_RECORD
{
double x;
double y;
double z;
double a; // azimuth
double e; // elevation
double r; // roll
double s[3][3];
double q[4];
double time;
}DOUBLE_ALL_TIME_STAMP_RECORD;
typedef struct tagDOUBLE_ALL_TIME_STAMP_Q_RECORD
{
double x;
double y;
double z;
double a; // azimuth
double e; // elevation
double r; // roll
double s[3][3];
double q[4];
double time;
USHORT quality;
}DOUBLE_ALL_TIME_STAMP_Q_RECORD;
typedef struct tagDOUBLE_ALL_TIME_STAMP_Q_RAW_RECORD
{
double x;
double y;
double z;
double a; // azimuth
double e; // elevation
double r; // roll
double s[3][3];
double q[4];
double time;
USHORT quality;
double raw[3][3];
}DOUBLE_ALL_TIME_STAMP_Q_RAW_RECORD;
/*****************************************************************************
FUNCTION PROTOTYPES
*****************************************************************************/
/*
InitializeBIRDSystem Starts and initializes driver, resets
hardware and interrogates hardware. Builds
local database of system resources.
Parameters Passed: none
Return Value: error status
Remarks: Can be used anytime a catastrophic failure
has occurred and the system needs to be
restarted.
*/
ATC3DG_API int InitializeBIRDSystem(void);
/*
GetBIRDSystemConfiguration
Parameters Passed: SYSTEM_CONFIGURATION*
Return Value: error status
Remarks: Returns SYSTEM_CONFIGURATION structure
It contains values equal to the number of
transmitters, sensors and boards detected
in the system. (The board information is for
test/diagnostic purposes, all commands
reference sensors and transmitters only) Once
the number of devices is known, (e.g. n) the
range of IDs for those devices becomes 0..(n-1)
*/
ATC3DG_API int GetBIRDSystemConfiguration(
SYSTEM_CONFIGURATION* systemConfiguration
);
/*
GetTransmitterConfiguration
Parameters Passed: USHORT transmitterID
TRANSMITTER_CONFIGURATION *transmitterConfiguration
Return Value: error status
Remarks: After getting system config the user can then pass
the index of a transmitter of interest to this function
which will then return the config for that transmitter.
Items of interest are the serial number and status.
*/
ATC3DG_API int GetTransmitterConfiguration(
USHORT transmitterID,
TRANSMITTER_CONFIGURATION* transmitterConfiguration
);
/*
GetSensorConfiguration
Parameters Passed: USHORT sensorID,
SENSOR_CONFIGURATION* sensorConfiguration
Return Value: error status
Remarks: Similar to the transmitter function.
*/
ATC3DG_API int GetSensorConfiguration(
USHORT sensorID,
SENSOR_CONFIGURATION* sensorConfiguration
);
/*
GetBoardConfiguration
Parameters Passed: USHORT boardID,
BOARD_CONFIGURATION* boardConfiguration
Return Value: error status
Remarks: Similar to the Sensor and Transmitter
functions. Also returns information on
how many sensors and transmitters are
attached. NOTE: Board information is not
needed during normal operation this is
only provided for "accounting" purposes.
*/
ATC3DG_API int GetBoardConfiguration(
USHORT boardID,
BOARD_CONFIGURATION* boardConfiguration
);
/*
GetAsynchronousRecord
Parameters Passed: USHORT sensorID,
void *pRecord,
int recordSize
Return Value: error status
Remarks: Returns data immediately in the currently
selected format from the last measurement
cycle. Requires user providing a buffer large
enough for the result otherwise an error is
generated and data lost.
(Old style BIRD POINT mode)
*/
ATC3DG_API int GetAsynchronousRecord(
USHORT sensorID,
void *pRecord,
int recordSize
);
/*
GetSynchronousRecord
Parameters Passed: USHORT sensorID,
void *pRecord,
int recordSize
Return Value: error status
Remarks: Returns a record after next measurement cycle. Puts
system into mode where records are generated 1/cycle.
Will return one and only one record per measurement
cycle. Will queue the records for each measurement
cycle if command not issued sufficiently often. If
command issued too often will time-out with no data.
(old style BIRD STREAM mode)
*/
ATC3DG_API int GetSynchronousRecord(
USHORT sensorID,
void *pRecord,
int recordSize
);
/*
GetSystemParameter
Parameters Passed: PARAMETER_TYPE parameterType,
void *pBuffer,
int bufferSize
Return Value: error status
Remarks: When a properly enumerated parameter type constant
is used, the command will return the parameter value
to the buffer provided by the user. An error is
generated if the buffer is incorrectly sized
*/
ATC3DG_API int GetSystemParameter(
enum SYSTEM_PARAMETER_TYPE parameterType,
void *pBuffer,
int bufferSize
);
/*
SetSystemParameter
Parameters Passed: PARAMETER_TYPE parameterType,
void *pBuffer,
int bufferSize
Return Value: error status
Remarks: Similar to GetSystemParameter but allows user
to set (write) the parameter.
*/
ATC3DG_API int SetSystemParameter(
enum SYSTEM_PARAMETER_TYPE parameterType,
void *pBuffer,
int bufferSize
);
/*
GetSensorParameter
Parameters Passed: USHORT sensorID,
PARAMETER_TYPE parameterType,
void *pBuffer,
int bufferSize
Return Value: error status
Remarks: When a sensor is selected with a valid index (ID)
and a properly enumerated parameter type constant
is used, the command will return the parameter value
to the buffer provided by the user. An error is
generated if the buffer is incorrectly sized
*/
ATC3DG_API int GetSensorParameter(
USHORT sensorID,
enum SENSOR_PARAMETER_TYPE parameterType,
void *pBuffer,
int bufferSize
);
/*
SetSensorParameter
Parameters Passed: USHORT sensorID,
PARAMETER_TYPE parameterType,
void *pBuffer,
int bufferSize
Return Value: error status
Remarks: Similar to GetSensorParameter but allows user
to set (write) the parameter.
*/
ATC3DG_API int SetSensorParameter(
USHORT sensorID,
enum SENSOR_PARAMETER_TYPE parameterType,
void *pBuffer,
int bufferSize
);
/*
GetTransmitterParameter
Parameters Passed: USHORT transmitterID,
PARAMETER_TYPE parameterType,
void *pBuffer,
int bufferSize
Return Value: error status
Remarks: Same as Sensor command
*/
ATC3DG_API int GetTransmitterParameter(
USHORT transmitterID,
enum TRANSMITTER_PARAMETER_TYPE parameterType,
void *pBuffer,
int bufferSize
);
/*
SetTransmitterParameter
Parameters Passed: USHORT transmitterID,
PARAMETER_TYPE parameterType,
void *pBuffer,
int bufferSize
Return Value: error status
Remarks: Same as sensor command
*/
ATC3DG_API int SetTransmitterParameter(
USHORT transmitterID,
enum TRANSMITTER_PARAMETER_TYPE parameterType,
void *pBuffer,
int bufferSize
);
/*
GetBIRDError
Parameters Passed: none
Return Value: error status
Remarks: Returns next error in queue
if available
*/
ATC3DG_API int GetBIRDError(
void
);
#define GetPOSTError GetBIRDError
#define GetDIAGError GetBIRDError
/*
GetErrorText
Parameters Passed: int errorCode
char *pBuffer
int bufferSize
int type
Return Value: error status as a text string
Remarks: ErrorCode contains the error code returned from
either a command or in response to GetBIRDError
and which is to be described by a text string.
Pass a pointer pBuffer to a buffer to contain
the result of the command. The size of the
buffer is contained in bufferSize. The type
parameter is an enumerated constant of
the type MESSAGE_TYPE.
*/
ATC3DG_API int GetErrorText(
int errorCode,
char *pBuffer,
int bufferSize,
enum MESSAGE_TYPE type
);
/*
*/
ATC3DG_API DEVICE_STATUS GetSensorStatus(
USHORT sensorID
);
/*
*/
ATC3DG_API DEVICE_STATUS GetTransmitterStatus(
USHORT transmitterID
);
/*
*/
ATC3DG_API DEVICE_STATUS GetBoardStatus(
USHORT boardID
);
/*
*/
ATC3DG_API DEVICE_STATUS GetSystemStatus(
// no id required
);
/*
*/
ATC3DG_API int SaveSystemConfiguration(
LPCSTR lpFileName
);
/*
*/
ATC3DG_API int RestoreSystemConfiguration(
LPCSTR lpFileName
);
/*
*/
ATC3DG_API int GetBoardParameter(
USHORT boardID,
enum BOARD_PARAMETER_TYPE parameterType,
void *pBuffer,
int bufferSize
);
/*
*/
ATC3DG_API int SetBoardParameter(
USHORT boardID,
enum BOARD_PARAMETER_TYPE parameterType,
void *pBuffer,
int bufferSize
);
/*
*/
ATC3DG_API int CloseBIRDSystem(void);
#endif // ATC3DG_H
| 35,275 | C | 25.208024 | 107 | 0.686889 |
adegirmenci/HBL-ICEbot/FrameClientWidget/frameclientthread.cpp | #include "frameclientthread.h"
FrameClientThread::FrameClientThread(QObject *parent) : QObject(parent)
{
qRegisterMetaType< FrameExtd >("FrameExtd");
m_isEpochSet = false;
m_isReady = false;
m_keepStreaming = false;
m_continuousStreaming = false;
m_frameCount = 0;
m_abort = false;
m_serverAddress = QHostAddress(QHostAddress::LocalHost);
m_serverPort = (quint16)4417;
m_TcpSocket = Q_NULLPTR;
m_currExtdFrame = FrameExtd();
m_currFrame = nullptr;
m_currFramePhase = 0.0;
m_currBird = EMreading();
m_cardiacPhases.resize(N_PHASES,0.0);
m_phaseTimes.resize(N_PHASES,0.0);
m_mutex = new QMutex(QMutex::Recursive);
}
FrameClientThread::~FrameClientThread()
{
m_mutex->lock();
m_abort = true;
m_isReady = false;
m_keepStreaming = false;
m_continuousStreaming = false;
if(m_TcpSocket)
{
m_TcpSocket->flush();
m_TcpSocket->disconnectFromHost();
m_TcpSocket->deleteLater();
}
m_mutex->unlock();
qDebug() << "Ending FrameClientThread - ID: " << reinterpret_cast<int>(QThread::currentThreadId()) << ".";
delete m_mutex;
emit finished();
}
void FrameClientThread::initializeFrameClient()
{
QMutexLocker locker(m_mutex);
m_TcpSocket = new QTcpSocket(this);
connect(m_TcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(handleTcpError(QAbstractSocket::SocketError)));
connect(this, SIGNAL(tcpError(QAbstractSocket::SocketError)),
this, SLOT(handleTcpError(QAbstractSocket::SocketError)));
connect(m_TcpSocket, SIGNAL(connected()), this, SLOT(connectedToHost()));
connect(m_TcpSocket, SIGNAL(disconnected()), this, SLOT(disconnectedFromHost()));
m_isReady = true;
}
void FrameClientThread::sendFrame()
{
QMutexLocker locker(m_mutex);
if(!m_isReady)
initializeFrameClient();
if(m_keepStreaming && (m_currFramePhase < 0.06))
{
m_continuousStreaming = false;
// construct frame - rot matrix from Ascension is transposed
QMatrix4x4 tmp(m_currBird.data.s[0][0], m_currBird.data.s[0][1], m_currBird.data.s[0][2], m_currBird.data.x,
m_currBird.data.s[1][0], m_currBird.data.s[1][1], m_currBird.data.s[1][2], m_currBird.data.y,
m_currBird.data.s[2][0], m_currBird.data.s[2][1], m_currBird.data.s[2][2], m_currBird.data.z,
0.0, 0.0, 0.0, 1.0);
Qt3DCore::QTransform tform;
tform.setMatrix(tmp);
// QQuaternion q(m_currBird.data.q[0],
// m_currBird.data.q[1],
// m_currBird.data.q[2],
// m_currBird.data.q[3]);
QQuaternion q = tform.rotation();
QVector3D v = tform.translation();
m_currExtdFrame.EMq_ = q;
m_currExtdFrame.EMv_ = v;
m_currExtdFrame.phaseHR_ = (float)m_currFramePhase;
m_currExtdFrame.image_ = saveFrame(m_currFrame); // write to disk
m_currExtdFrame.index_ = m_currFrame->index_;
m_currExtdFrame.mask_ = tr("C:\\Users\\Alperen\\Documents\\QT Projects\\RT3DReconst_GUI\\Acuson_Epiphan.bin");
m_currExtdFrame.timestamp_ = m_currFrame->timestamp_;
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_7);
out << (quint16)0;
out << m_currExtdFrame;
out.device()->seek(0);
out << (quint16)(block.size() - sizeof(quint16));
m_TcpSocket->connectToHost(m_serverAddress, m_serverPort, QIODevice::WriteOnly);
if (m_TcpSocket->waitForConnected(100))
{
qDebug("Connected!");
m_TcpSocket->write(block);
m_TcpSocket->flush();
m_TcpSocket->disconnectFromHost();
if( (m_TcpSocket->state() != QAbstractSocket::UnconnectedState) &&
(!m_TcpSocket->waitForDisconnected(100)) ) {
emit statusChanged(FRMCLNT_DISCONNECTION_FAILED); }
}
else
emit statusChanged(FRMCLNT_CONNECTION_FAILED);
}
else
emit statusChanged(FRMCLNT_FIRST_FRAME_NOT_RECEIVED);
}
void FrameClientThread::receiveFrame(std::shared_ptr<Frame> frame)
{
QMutexLocker locker(m_mutex);
// qDebug() << "FrameClientThread: receiveFrame";
m_currFrame = frame;
// determine phase
// take the difference of time stamps
std::valarray<qint64> Tdiff(m_phaseTimes.data(), m_phaseTimes.size());
Tdiff = std::abs(Tdiff - m_currFrame->timestamp_);
// find closest timestamp
auto idx = std::distance(std::begin(Tdiff), std::min_element(std::begin(Tdiff), std::end(Tdiff)));
m_currFramePhase = m_cardiacPhases[idx];
if(m_continuousStreaming)
sendFrame();
}
void FrameClientThread::receiveEMreading(QTime timeStamp, int sensorID, DOUBLE_POSITION_MATRIX_TIME_Q_RECORD data)
{
QMutexLocker locker(m_mutex);
// qDebug() << "FrameClientThread: receiveEMreading";
if(m_currFrame)
{
qint64 tBirdCurr(m_currBird.data.time*1000);
qint64 tBirdNext(data.time*1000);
qint64 diffCurr = qAbs(m_currFrame->timestamp_ - tBirdCurr);
qint64 diffNext = qAbs(m_currFrame->timestamp_ - tBirdNext);
if(diffNext < diffCurr)
{
m_currBird.data = data;
m_currBird.sensorID = sensorID;
m_currBird.timeStamp = timeStamp;
}
}
if(m_currFrame)
m_keepStreaming = true;
}
void FrameClientThread::receiveLatestEMreading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> readings)
{
QMutexLocker locker(m_mutex);
Q_ASSERT(4 == readings.size());
if(m_currFrame)
{
qint64 tBirdCurr(m_currBird.data.time*1000);
qint64 tBirdNext(readings[EM_SENSOR_BT].time*1000);
qint64 diffCurr = qAbs(m_currFrame->timestamp_ - tBirdCurr);
qint64 diffNext = qAbs(m_currFrame->timestamp_ - tBirdNext);
if(diffNext < diffCurr)
{
m_currBird.data = readings[EM_SENSOR_BT];
m_currBird.sensorID = EM_SENSOR_BT;
m_currBird.timeStamp = QTime::currentTime();
}
}
if(m_currFrame)
m_keepStreaming = true;
}
void FrameClientThread::receive_T_CT(std::vector<double> T_BB_CT, double time)
{
QMutexLocker locker(m_mutex);
if(m_currFrame && (T_BB_CT.size() == 16))
{
qint64 tBirdCurr(m_currBird.data.time*1000);
qint64 tBirdNext(time*1000);
qint64 diffCurr = qAbs(m_currFrame->timestamp_ - tBirdCurr);
qint64 diffNext = qAbs(m_currFrame->timestamp_ - tBirdNext);
if(diffNext < diffCurr)
{
// data in Eigen is stored as column-major
m_currBird.data.s[0][0] = T_BB_CT[0];
m_currBird.data.s[1][0] = T_BB_CT[1];
m_currBird.data.s[2][0] = T_BB_CT[2];
m_currBird.data.s[0][1] = T_BB_CT[4];
m_currBird.data.s[1][1] = T_BB_CT[5];
m_currBird.data.s[2][1] = T_BB_CT[6];
m_currBird.data.s[0][2] = T_BB_CT[8];
m_currBird.data.s[1][2] = T_BB_CT[9];
m_currBird.data.s[2][2] = T_BB_CT[10];
m_currBird.data.x = T_BB_CT[12];
m_currBird.data.y = T_BB_CT[13];
m_currBird.data.z = T_BB_CT[14];
m_currBird.data.time = time;
m_currBird.sensorID = EM_SENSOR_BT;
m_currBird.timeStamp = QTime::currentTime();
}
}
if(m_currFrame)
m_keepStreaming = true;
}
void FrameClientThread::receivePhase(qint64 timeStamp, double phase)
{
m_cardiacPhases.erase(m_cardiacPhases.begin());
m_phaseTimes.erase(m_phaseTimes.begin());
m_cardiacPhases.push_back(phase);
m_phaseTimes.push_back(timeStamp);
}
void FrameClientThread::connectedToHost()
{
emit statusChanged(FRMCLNT_CONNECTED);
}
void FrameClientThread::disconnectedFromHost()
{
emit statusChanged(FRMCLNT_DISCONNECTED);
}
QString FrameClientThread::saveFrame(std::shared_ptr<Frame> frm)
{
QMutexLocker locker(m_mutex);
QDateTime imgTime;
imgTime.setMSecsSinceEpoch(frm->timestamp_);
// file name of frame
QString m_imgFname = imgTime.toString("ddMMyyyy_hhmmsszzz");
// populate m_imgFname with index
m_imgFname.append( QString("_%1").arg(frm->index_) );
QString m_DirImgFname = QDir::currentPath();
m_DirImgFname.append("/");
m_DirImgFname.append(m_imgFname);
// save frame
//state = frame->image_.save(m_imgFname, "JPG", 100);
cv::imwrite((m_DirImgFname + tr(".jp2")).toStdString().c_str(), frm->image_ ); // write frame
// save EM data to file
QFile txtfile(m_DirImgFname + tr(".txt"));
if (txtfile.open(QFile::WriteOnly)) {
QTextStream txtout(&txtfile);
txtout << tr("%1\t%2\t%3\n")
.arg(m_currExtdFrame.EMv_.x())
.arg(m_currExtdFrame.EMv_.y())
.arg(m_currExtdFrame.EMv_.z());
txtout << tr("%1\t%2\t%3\t%4\n")
.arg(m_currExtdFrame.EMq_.x())
.arg(m_currExtdFrame.EMq_.y())
.arg(m_currExtdFrame.EMq_.z())
.arg(m_currExtdFrame.EMq_.scalar());
txtout << QString::number(m_currExtdFrame.phaseHR_, 'f', 3);
txtout << "\nLine 1: QVector3D, Line2: QQuaternion, Line3: (float)phaseHR_";
}
txtfile.close();
return m_DirImgFname;
}
void FrameClientThread::handleTcpError(QAbstractSocket::SocketError error)
{
QMutexLocker locker(m_mutex);
QString errStr;
switch(error)
{
case QAbstractSocket::ConnectionRefusedError:
errStr = "ConnectionRefusedError"; break;
case QAbstractSocket::RemoteHostClosedError:
errStr = "RemoteHostClosedError"; break;
case QAbstractSocket::HostNotFoundError:
errStr = "HostNotFoundError"; break;
case QAbstractSocket::SocketAccessError:
errStr = "SocketAccessError"; break;
case QAbstractSocket::SocketResourceError:
errStr = "SocketResourceError"; break;
case QAbstractSocket::SocketTimeoutError:
errStr = "SocketTimeoutError"; break;
case QAbstractSocket::DatagramTooLargeError:
errStr = "DatagramTooLargeError"; break;
case QAbstractSocket::NetworkError:
errStr = "NetworkError"; break;
case QAbstractSocket::AddressInUseError:
errStr = "AddressInUseError"; break;
case QAbstractSocket::SocketAddressNotAvailableError:
errStr = "SocketAddressNotAvailableError"; break;
case QAbstractSocket::UnsupportedSocketOperationError:
errStr = "UnsupportedSocketOperationError"; break;
case QAbstractSocket::OperationError:
errStr = "OperationError"; break;
case QAbstractSocket::TemporaryError:
errStr = "TemporaryError"; break;
case QAbstractSocket::UnknownSocketError:
errStr = "UnknownSocketError"; break;
default:
errStr = "UnknownError";
}
qDebug() << tr("Error in FrameClientThread: %1.")
.arg(errStr);
}
void FrameClientThread::setEpoch(const QDateTime &datetime)
{
QMutexLocker locker(m_mutex);
if(!m_keepStreaming)
{
m_epoch = datetime;
m_isEpochSet = true;
// emit logEventWithMessage(SRC_FRMCLNT, LOG_INFO, QTime::currentTime(), FRMCLNT_EPOCH_SET,
// m_epoch.toString("yyyy/MM/dd - hh:mm:ss.zzz"));
}
// else
// emit logEvent(SRC_FRMCLNT, LOG_INFO, QTime::currentTime(), FRMCLNT_EPOCH_SET_FAILED);
}
QDataStream & operator << (QDataStream &o, const FrameExtd& f)
{
return o << f.image_
<< f.index_
<< f.timestamp_
<< f.EMq_
<< f.EMv_
<< f.mask_
<< f.phaseHR_
<< f.phaseResp_
<< '\0';
}
QDataStream & operator >> (QDataStream &i, FrameExtd& f)
{
i >> f.image_
>> f.index_
>> f.timestamp_
>> f.EMq_
>> f.EMv_
>> f.mask_
>> f.phaseHR_
>> f.phaseResp_;
return i;
}
| 12,154 | C++ | 31.413333 | 118 | 0.606961 |
adegirmenci/HBL-ICEbot/FrameClientWidget/frameclientwidget.h | #ifndef FRAMECLIENTWIDGET_H
#define FRAMECLIENTWIDGET_H
#include <QWidget>
#include <QTimer>
#include "frameclientthread.h"
namespace Ui {
class FrameClientWidget;
}
class FrameClientWidget : public QWidget
{
Q_OBJECT
public:
explicit FrameClientWidget(QWidget *parent = 0);
~FrameClientWidget();
FrameClientThread *m_worker;
signals:
void sendFrame();
private slots:
void workerStatusChanged(int status);
void on_sendFrameButton_clicked();
void on_toggleAutoButton_clicked();
private:
Ui::FrameClientWidget *ui;
bool m_keepTransmitting;
QTimer *m_transmitTimer;
QThread m_thread; // FrameClientThread will live in here
};
#endif // FRAMECLIENTWIDGET_H
| 715 | C | 15.651162 | 60 | 0.725874 |
adegirmenci/HBL-ICEbot/FrameClientWidget/frameclientwidget.cpp | #include "frameclientwidget.h"
#include "ui_frameclientwidget.h"
FrameClientWidget::FrameClientWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::FrameClientWidget)
{
ui->setupUi(this);
m_keepTransmitting = false;
m_worker = new FrameClientThread;
m_worker->moveToThread(&m_thread);
connect(&m_thread, SIGNAL(finished()), m_worker, SLOT(deleteLater()));
m_thread.start();
connect(m_worker, SIGNAL(statusChanged(int)), this, SLOT(workerStatusChanged(int)));
connect(this, SIGNAL(sendFrame()), m_worker, SLOT(sendFrame()));
m_transmitTimer = new QTimer(this);
connect(m_transmitTimer, SIGNAL(timeout()),
this, SLOT(on_sendFrameButton_clicked()));
}
FrameClientWidget::~FrameClientWidget()
{
m_keepTransmitting = false;
if(m_transmitTimer)
m_transmitTimer->stop();
m_thread.quit();
m_thread.wait();
qDebug() << "FrameClientWidget thread quit.";
delete ui;
}
void FrameClientWidget::workerStatusChanged(int status)
{
switch(status)
{
case FRMCLNT_CONNECTED:
ui->statusTextEdit->appendPlainText("Connected to server.");
ui->addrPortLineEdit->setText(tr("%1:%2")
.arg(m_worker->getServerAddress().toString())
.arg(m_worker->getServerPort()));
break;
case FRMCLNT_CONNECTION_FAILED:
ui->statusTextEdit->appendPlainText("Server connection failed.");
break;
case FRMCLNT_DISCONNECTED:
ui->statusTextEdit->appendPlainText("Server connection closed.");
break;
case FRMCLNT_DISCONNECTION_FAILED:
ui->statusTextEdit->appendPlainText("Server disconnect failed.");
break;
case FRMCLNT_SOCKET_NOT_WRITABLE:
ui->statusTextEdit->appendPlainText("Incoming connection.");
break;
case FRMCLNT_FRAME_SENT:
ui->statusTextEdit->appendPlainText("Frame sent.");
break;
case FRMCLNT_EPOCH_SET:
ui->statusTextEdit->appendPlainText("Epoch set.");
break;
case FRMCLNT_EPOCH_SET_FAILED:
ui->statusTextEdit->appendPlainText("Epoch set failed.");
break;
case FRMCLNT_FIRST_FRAME_NOT_RECEIVED:
ui->statusTextEdit->appendPlainText("First frame not yet received.");
break;
default:
ui->statusTextEdit->appendPlainText("Unknown worker state.");
}
}
void FrameClientWidget::on_sendFrameButton_clicked()
{
emit sendFrame();
}
void FrameClientWidget::on_toggleAutoButton_clicked()
{
if(m_keepTransmitting)
{
m_keepTransmitting = false;
ui->toggleAutoButton->setText("Start Automatic Collection");
m_transmitTimer->stop();
}
else
{
m_keepTransmitting = true;
ui->toggleAutoButton->setText("Stop Automatic Collection");
m_transmitTimer->start(30);
}
}
| 2,882 | C++ | 28.121212 | 88 | 0.644344 |
adegirmenci/HBL-ICEbot/FrameClientWidget/frameclientthread.h | #ifndef FRAMECLIENTTHREAD_H
#define FRAMECLIENTTHREAD_H
#include <QObject>
#include <QMutex>
#include <QMutexLocker>
#include <QThread>
#include <QString>
#include <QTime>
#include <QTimer>
#include <QDebug>
#include <QSharedPointer>
#include <QDir>
#include <QNetworkInterface>
#include <QTcpSocket>
#include <QDataStream>
#include <QByteArray>
#include <QHostAddress>
#include <QMatrix4x4>
#include <Qt3DCore/QTransform>
#include <QQuaternion>
#include <QVector3D>
#include <vector>
#include <memory>
#include <valarray>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "../icebot_definitions.h"
#include "../AscensionWidget/3DGAPI/ATC3DG.h"
#include "../FrmGrabWidget/frmgrabthread.h"
#define N_PHASES 500 // keep track of the last N_PHASES cardiac phases and corresponding time stamps
struct FrameExtd{
QString image_; /*!< Image data. */
QQuaternion EMq_; /*!< EM reading - rotation as Quaternion. */
QVector3D EMv_; /*!< EM reading - translation. */
float phaseHR_; /*!< Phase in the heart cycle (0.0 - 1.0). */
float phaseResp_; /*!< Phase in the respiration cycle (0.0 - 1.0). */
qint64 timestamp_; /*!< Timestamp, msec since some epoch. */
int index_; /*!< Index value of Frame, indicate order of acquisition. */
QString mask_; /*!< Image mask. */
//! Constructor.
explicit FrameExtd(QString img = QString(),
QQuaternion emq = QQuaternion(),
QVector3D emv = QVector3D(),
qint64 ts = -1,
float pHR = 0.f,
float pResp = 0.f,
int id = -1,
QString mask = QString()) :
timestamp_(ts), phaseHR_(pHR), phaseResp_(pResp), index_(id)
{
image_ = img;
EMq_ = emq;
EMv_ = emv;
mask_ = mask;
}
//! Destructor
~FrameExtd() {
}
};
struct EMreading{
QTime timeStamp;
int sensorID;
DOUBLE_POSITION_MATRIX_TIME_Q_RECORD data;
explicit EMreading(QTime t_ = QTime(),
int s_ = -1,
DOUBLE_POSITION_MATRIX_TIME_Q_RECORD r_ = DOUBLE_POSITION_MATRIX_TIME_Q_RECORD()) :
timeStamp(t_), sensorID(s_)
{
data = r_;
}
~EMreading(){}
};
Q_DECLARE_METATYPE(FrameExtd)
class FrameClientThread : public QObject
{
Q_OBJECT
public:
explicit FrameClientThread(QObject *parent = 0);
~FrameClientThread();
friend QDataStream & operator << (QDataStream &o, const FrameExtd& f);
friend QDataStream & operator >> (QDataStream &i, FrameExtd& f);
signals:
void statusChanged(int event);
void finished(); // emit upon termination
void tcpError(QAbstractSocket::SocketError error);
public slots:
void setEpoch(const QDateTime &datetime); // set Epoch
void initializeFrameClient();
void sendFrame(); // change to Frame type
void receiveFrame(std::shared_ptr<Frame> frame);
void receiveEMreading(QTime timeStamp,
int sensorID,
DOUBLE_POSITION_MATRIX_TIME_Q_RECORD data);
void receiveLatestEMreading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> readings);
void receive_T_CT(std::vector<double> T_BB_CT, double time);
void receivePhase(qint64 timeStamp, double phase);
void handleTcpError(QAbstractSocket::SocketError error);
void connectedToHost();
void disconnectedFromHost();
const QHostAddress getServerAddress() { return m_serverAddress; }
const quint16 getServerPort() { return m_serverPort; }
void toggleContinuousSteaming(bool state) { m_continuousStreaming = state; }
private:
QString saveFrame(std::shared_ptr<Frame>);
// Instead of using "m_mutex.lock()"
// use "QMutexLocker locker(&m_mutex);"
// this will unlock the mutex when the locker goes out of scope
mutable QMutex *m_mutex;
// Epoch for time stamps
// During initializeFrameClient(), check 'isEpochSet' flag
// If Epoch is set externally from MainWindow, the flag will be true
// Otherwise, Epoch will be set internally
QDateTime m_epoch;
bool m_isEpochSet;
// Flag to indicate if Frame Client is ready
// True if initializeFrameClient was successful
bool m_isReady;
// Flag to tell that we are still streaming
bool m_keepStreaming;
bool m_continuousStreaming;
// Flag to abort actions (e.g. initialize, acquire, etc.)
bool m_abort;
int m_frameCount; // keep a count of number of transmitted frames
// server info
QHostAddress m_serverAddress;
quint16 m_serverPort;
QTcpSocket *m_TcpSocket;
FrameExtd m_currExtdFrame;
std::shared_ptr<Frame> m_currFrame;
double m_currFramePhase;
EMreading m_currBird;
std::vector<double> m_cardiacPhases;
std::vector<qint64> m_phaseTimes;
};
#endif // FRAMECLIENTTHREAD_H
| 4,950 | C | 28.825301 | 106 | 0.650303 |
adegirmenci/HBL-ICEbot/EPOS2Widget/epos2thread.h | #ifndef EPOS2THREAD_H
#define EPOS2THREAD_H
#include <QObject>
#include <QMutex>
#include <QMutexLocker>
#include <QThread>
#include <QString>
#include <QDateTime>
#include <QTimer>
#include <QElapsedTimer>
#include <QDebug>
#include <QSharedPointer>
#include <vector>
#include <memory>
#include "../icebot_definitions.h"
#include "MaxonLibs/Definitions.h"
#include <stdio.h>
#include <Windows.h>
Q_DECLARE_METATYPE(std::vector<long>)
//Q_DECLARE_METATYPE(std::vector<int>)
struct eposMotor
{
__int8 m_bMode;
WORD m_nodeID; // motor ID
DWORD m_ulProfileAcceleration; // acceleration value
DWORD m_ulProfileDeceleration; // deceleration value
DWORD m_ulProfileVelocity; // velocity value
bool m_enabled;
EPOS_MOTOR_STATUS m_motorStatus;
long m_lActualValue; // volatile?
long m_lStartPosition; // volatile?
long m_lTargetPosition; // volatile?
long m_maxQC; // upper limit
long m_minQC; // lower limit
};
class EPOS2Thread : public QObject
{
Q_OBJECT
public:
explicit EPOS2Thread(QObject *parent = 0);
~EPOS2Thread();
bool isInServoLoop(){QMutexLocker locker(m_mutex); return m_keepServoing;}
signals:
void statusChanged(int event);
void motorStatusChanged(const int motID, const int status);
void motorStatusChanged(std::vector<int> status);
void motorQcChanged(const int motID, const long QC);
void motorQcChanged(std::vector<long> QCs);
//void EPOS_Ready(bool status); // tells the widget that the EPOS is ready
void logData(QTime timeStamp,
int dataType, // EPOS_DATA_IDS
const int motID,
long data);
void logData(QTime timeStamp,
int dataType, // EPOS_DATA_IDS
std::vector<long> data);
void logEvent(int source, // LOG_SOURCE
int logType, // LOG_TYPE
QTime timeStamp,
int eventID); // EPOS_EVENT_IDS
void logEventWithMessage(int source, // LOG_SOURCE
int logType, // LOG_TYPE
QTime timeStamp,
int eventID, // EPOS_EVENT_IDS
QString &message);
void logError(int source, // LOG_SOURCE
int logType, // LOG_TYPE
QTime timeStamp,
int errCode, // EPOS_ERROR_CODES
QString message);
void sendDataToGUI(const int id, const QString &output);
void finished(); // emit upon termination
public slots:
bool initializeEPOS(); // open connection to EPOS
void startServoing(); // start timer
void setServoTargetPos(const int axisID, long targetPos, bool moveAbsOrRel); // update target for one motor
void setServoTargetPos(std::vector<long> targetPos, bool moveAbsOrRel); // update target for all motors
void servoToPosition(); // called by timer
void servoToPosition(const int axisID);
void haltMotor(const int axisID); // immediately stop all motors
void stopServoing(); // stop timer
bool disconnectEPOS(); // disconnect from EPOS
void setEpoch(const QDateTime &datetime); // set Epoch
void updateMotorQC(const int axisID);
void updateMotorQCs();
const int getMotorStatus(const int axisID);
bool initializeMotor(const int motID);
bool disableMotor(const int motID);
void homeAxis(const int axisID);
void homeAllAxes();
private:
// Instead of using "m_mutex.lock()"
// use "QMutexLocker locker(&m_mutex);"
// this will unlock the mutex when the locker goes out of scope
mutable QMutex *m_mutex;
// Timer for calling servoToPosition every xxx msecs
QTimer *m_timer;
// Epoch for time stamps
// During initializeEPOS(), check 'isEpochSet' flag
// If Epoch is set externally from MainWindow, the flag will be true
// Otherwise, Epoch will be set internally
QDateTime m_epoch;
bool m_isEpochSet;
// Flag to indicate if EPOS tracker is ready
// True if InitializeEPOS was successful
bool m_isReady;
// Flag to tell that we are still servoing
bool m_keepServoing;
// Flag to abort actions (e.g. initialize, acquire, etc.)
bool m_abort;
// EPOS variables
BOOL m_oImmediately;
BOOL m_oInitialisation;
BOOL m_oUpdateActive;
DWORD m_ulErrorCode;
HANDLE m_KeyHandle;
// list of motors
std::vector< std::shared_ptr<eposMotor> > m_motors;
const int m_prec = 4; // precision for print operations
// error handler
bool ShowErrorInformation(DWORD p_ulErrorCode);
QString formatOutput(QTime &timeStamp,
const int motorID,
long pos);
// -----
int checkMotorLimits(const int axisID, const long targetPos);
long clampToMotorLimits(const int axisID, const long targetPos);
bool checkMotorID(const int motID);
};
// ----------------
// HELPER FUNCTIONS
// ----------------
inline const QString getCurrTimeStr();
inline const QString getCurrDateTimeStr();
#endif // EPOS2THREAD_H
| 5,033 | C | 29.695122 | 111 | 0.654878 |
adegirmenci/HBL-ICEbot/EPOS2Widget/epos2widget.cpp | #include "epos2widget.h"
#include "ui_epos2widget.h"
EPOS2Widget::EPOS2Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::EPOS2Widget)
{
ui->setupUi(this);
m_worker = new EPOS2Thread;
m_worker->moveToThread(&m_thread);
connect(&m_thread, &QThread::finished, m_worker, &QObject::deleteLater);
m_thread.start();
connect(ui->connectButton, SIGNAL(clicked(bool)), m_worker, SLOT(initializeEPOS()));
// connect(ui->acquireButton, SIGNAL(clicked(bool)), m_worker, SLOT(startAcquisition()));
// connect(ui->stopButton, SIGNAL(clicked(bool)), m_worker, SLOT(stopAcquisition()));
connect(ui->disconnectButton, SIGNAL(clicked(bool)), m_worker, SLOT(disconnectEPOS()));
connect(m_worker, SIGNAL(statusChanged(int)),
this, SLOT(workerStatusChanged(int)));
connect(m_worker, SIGNAL(motorStatusChanged(int,int)),
this, SLOT(workerMotorStatusChanged(int,int)));
connect(m_worker, SIGNAL(motorStatusChanged(std::vector<int>)),
this, SLOT(workerMotorStatusChanged(std::vector<int>)));
connect(m_worker, SIGNAL(motorQcChanged(int,long)),
this, SLOT(workerMotorQcChanged(int,long)));
connect(m_worker, SIGNAL(motorQcChanged(std::vector<long>)),
this, SLOT(workerMotorQcChanged(std::vector<long>)));
connect(m_worker, SIGNAL(sendDataToGUI(int,QString)),
this, SLOT(receiveDataFromWorker(int,QString)));
connect(this, SIGNAL(setServoTargetPos(int,long,bool)), m_worker, SLOT(setServoTargetPos(int,long,bool)));
connect(this, SIGNAL(setServoTargetPos(std::vector<long>,bool)), m_worker, SLOT(setServoTargetPos(std::vector<long>,bool)));
connect(this, SIGNAL(servoToPos()), m_worker, SLOT(servoToPosition()));
connect(this, SIGNAL(servoToPos(int)), m_worker, SLOT(servoToPosition(int)));
connect(this, SIGNAL(haltMotor(int)), m_worker, SLOT(haltMotor(int)));
connect(this, SIGNAL(enableMotor(int)), m_worker, SLOT(initializeMotor(int)));
connect(this, SIGNAL(disableMotor(int)), m_worker, SLOT(disableMotor(int)));
connect(this, SIGNAL(startServoLoop()), m_worker, SLOT(startServoing()));
connect(this, SIGNAL(stopServoLoop()), m_worker, SLOT(stopServoing()));
connect(this, SIGNAL(homeAxis(int)), m_worker, SLOT(homeAxis(int)));
connect(this, SIGNAL(homeAllAxes()), m_worker, SLOT(homeAllAxes()));
// status labels
motLabels.push_back(ui->transStatusLabel);
motLabels.push_back(ui->pitchStatusLabel);
motLabels.push_back(ui->yawStatusLabel);
motLabels.push_back(ui->rollStatusLabel);
// LCD numbers
motQCs.push_back(ui->transQC_LCD);
motQCs.push_back(ui->pitchQC_LCD);
motQCs.push_back(ui->yawQC_LCD);
motQCs.push_back(ui->rollQC_LCD);
// trajectory
m_keepDriving = false;
m_currTrajIdx = 0;
}
EPOS2Widget::~EPOS2Widget()
{
//motLabels.clear();
m_thread.quit();
m_thread.wait();
qDebug() << "EPOS thread quit.";
delete ui;
}
void EPOS2Widget::workerStatusChanged(int status)
{
// TODO: consider putting this in a truth table and reading the entry based on the status code
// then we will get rid of the entire switch/case and just have a few lines of code
switch(status)
{
case EPOS_INITIALIZE_BEGIN:
ui->connectButton->setEnabled(false);
ui->outputTextEdit->appendPlainText("Connecting to EPOS...");
break;
case EPOS_INITIALIZE_FAILED:
ui->connectButton->setEnabled(true);
ui->outputTextEdit->appendPlainText("Connection failed!");
break;
case EPOS_INITIALIZED:
ui->connectButton->setEnabled(false);
ui->disconnectButton->setEnabled(true);
ui->nodeIDcomboBox->setEnabled(true);
ui->enableServoLoopButton->setEnabled(true);
ui->disableServoLoopButton->setEnabled(false);
ui->outputTextEdit->appendPlainText("Connected to EPOS.");
// ui->outputTextEdit->appendPlainText(QString("%1 motor(s) plugged in.")
// .arg(m_worker->getNumMotors()));
break;
case EPOS_DISCONNECTED:
ui->connectButton->setEnabled(true);
ui->disconnectButton->setEnabled(false);
ui->enableNodeButton->setEnabled(false);
ui->nodeIDcomboBox->setEnabled(false);
ui->enableServoLoopButton->setEnabled(false);
ui->disableServoLoopButton->setEnabled(false);
ui->outputTextEdit->appendPlainText("Disconnected from EPOS.");
break;
case EPOS_DISCONNECT_FAILED:
ui->outputTextEdit->appendPlainText("Disconnection from EPOS failed!");
break;
case EPOS_SERVO_LOOP_STARTED:
ui->enableServoLoopButton->setEnabled(false);
ui->disableServoLoopButton->setEnabled(true);
ui->haltButton->setEnabled(false); // disable halt button, use 'Disable Servo Loop' button to halt motors
ui->outputTextEdit->appendPlainText("Servo loop started.");
break;
case EPOS_SERVO_LOOP_STOPPED:
ui->enableServoLoopButton->setEnabled(true);
ui->disableServoLoopButton->setEnabled(false);
//ui->haltButton->setEnabled(true);
updateManualControls(m_worker->getMotorStatus( ui->nodeIDcomboBox->currentIndex() ));
ui->outputTextEdit->appendPlainText("Servo loop stopped.");
break;
case EPOS_SERVO_TO_POS_FAILED:
ui->outputTextEdit->appendPlainText("Servo to position failed!");
break;
case EPOS_EPOCH_SET:
ui->outputTextEdit->appendPlainText("Epoch set.");
break;
case EPOS_EPOCH_SET_FAILED:
ui->outputTextEdit->appendPlainText("Epoch set failed!");
break;
case EPOS_DISABLE_MOTOR_FAILED:
ui->outputTextEdit->appendPlainText("Motor disabled.");
break;
case EPOS_DISABLE_MOTOR_SUCCESS:
ui->outputTextEdit->appendPlainText("Disable motor failed!");
break;
case EPOS_DEVICE_CANT_CONNECT:
ui->outputTextEdit->appendPlainText("Can't connect to device!");
break;
case EPOS_UPDATE_QC_FAILED:
ui->outputTextEdit->appendPlainText("Update QC failed!");
break;
case EPOS_HALT_FAILED:
ui->outputTextEdit->appendPlainText("Halt failed!");
break;
default:
ui->outputTextEdit->appendPlainText("Unknown state!");
break;
}
}
void EPOS2Widget::workerMotorStatusChanged(const int motID, const int status)
{
int currID = ui->nodeIDcomboBox->currentIndex();
if(currID == motID)
updateManualControls(status);
if( status == EPOS_MOTOR_ENABLED )
{
motLabels[motID]->setText("Enabled");
motLabels[motID]->setStyleSheet("QLabel { background-color : green;}");
ui->outputTextEdit->appendPlainText(QString("Motor %1 enabled.").arg(motID+1));
}
else if( status == EPOS_MOTOR_DISABLED )
{
motLabels[motID]->setText("Disabled");
motLabels[motID]->setStyleSheet("QLabel { background-color : yellow;}");
ui->outputTextEdit->appendPlainText(QString("Motor %1 disabled.").arg(motID+1));
}
else if(status == EPOS_MOTOR_FAULT)
{
motLabels[motID]->setText("FAULT!");
motLabels[motID]->setStyleSheet("QLabel { background-color : red; color : white; }");
ui->outputTextEdit->appendPlainText(QString("Motor %1 fault!").arg(motID+1));
}
else if(status == EPOS_MOTOR_CANT_CONNECT)
{
motLabels[motID]->setText("Can't connect!");
motLabels[motID]->setStyleSheet("QLabel { background-color : red; color : white; }");
ui->outputTextEdit->appendPlainText(QString("Cannot connect to Motor %1.").arg(motID+1));
}
else
{
motLabels[motID]->setText("Unknown state!");// UNKNOWN STATE!
motLabels[motID]->setStyleSheet("QLabel { background-color : red; color : white; }");
ui->outputTextEdit->appendPlainText(QString("Motor %1 in inknown state.").arg(motID+1));
}
}
void EPOS2Widget::workerMotorStatusChanged(std::vector<int> status)
{
for(size_t i = 0; i < status.size(); i++)
workerMotorStatusChanged(i, status[i]);
}
void EPOS2Widget::workerMotorQcChanged(const int motID, const long QC)
{
if( motID < static_cast<int>(motQCs.size()) )
motQCs[motID]->display(QC);
else
qDebug() << "MotorID out of bounds!";
}
void EPOS2Widget::workerMotorQcChanged(std::vector<long> QCs)
{
for(size_t i = 0; i < QCs.size(); i++)
workerMotorQcChanged(i, QCs[i]);
}
void EPOS2Widget::receiveDataFromWorker(int motorID, const QString &data)
{
if(motorID == 0)
ui->outputTextEdit->clear();
ui->outputTextEdit->appendPlainText(data);
}
void EPOS2Widget::on_moveAbsButton_clicked()
{
int axisID = ui->nodeIDcomboBox->currentIndex();
long targetPos = ui->targetQCspinBox->value();
emit setServoTargetPos(axisID, targetPos, true);
if(!m_worker->isInServoLoop())
emit servoToPos();
}
void EPOS2Widget::on_moveRelButton_clicked()
{
int axisID = ui->nodeIDcomboBox->currentIndex();
long targetPos = ui->targetQCspinBox->value();
emit setServoTargetPos(axisID, targetPos, false);
if(!m_worker->isInServoLoop())
emit servoToPos();
}
void EPOS2Widget::on_homingButton_clicked()
{
int axisID = ui->nodeIDcomboBox->currentIndex();
//long targetPos = 0;
qDebug() << "Homing axis " << axisID;
//if(!m_worker->isInServoLoop())
emit stopServoLoop(); // stop servo loop
//emit setServoTargetPos(axisID, 0, true); // set target position
emit homeAxis(axisID);
emit servoToPos(); // servo to position
}
void EPOS2Widget::on_haltButton_clicked()
{
int axisID = ui->nodeIDcomboBox->currentIndex();
emit haltMotor(axisID);
}
void EPOS2Widget::updateManualControls(const int motorStatus)
{
if( motorStatus == EPOS_MOTOR_ENABLED )
{
ui->enableNodeButton->setEnabled(false);
ui->disableNodeButton->setEnabled(true);
ui->homingButton->setEnabled(true);
ui->moveAbsButton->setEnabled(true);
ui->moveRelButton->setEnabled(true);
if(!m_worker->isInServoLoop())
ui->haltButton->setEnabled(true);
else
ui->haltButton->setEnabled(false);
ui->homeAllButton->setEnabled(true);
}
else if( motorStatus == EPOS_MOTOR_DISABLED )
{
ui->enableNodeButton->setEnabled(true);
ui->disableNodeButton->setEnabled(false);
ui->homingButton->setEnabled(false);
ui->moveAbsButton->setEnabled(false);
ui->moveRelButton->setEnabled(false);
ui->haltButton->setEnabled(false);
ui->homeAllButton->setEnabled(false);
}
else if(motorStatus == EPOS_MOTOR_FAULT)
{
ui->enableNodeButton->setEnabled(true);
ui->disableNodeButton->setEnabled(false);
ui->homingButton->setEnabled(false);
ui->moveAbsButton->setEnabled(false);
ui->moveRelButton->setEnabled(false);
ui->haltButton->setEnabled(false);
ui->homeAllButton->setEnabled(false);
}
else if(motorStatus == EPOS_MOTOR_CANT_CONNECT)
{
ui->enableNodeButton->setEnabled(true);
ui->disableNodeButton->setEnabled(false);
ui->homingButton->setEnabled(false);
ui->moveAbsButton->setEnabled(false);
ui->moveRelButton->setEnabled(false);
ui->haltButton->setEnabled(false);
ui->homeAllButton->setEnabled(false);
}
else
{
ui->enableNodeButton->setEnabled(true);
ui->disableNodeButton->setEnabled(false);
ui->homingButton->setEnabled(false);
ui->moveAbsButton->setEnabled(false);
ui->moveRelButton->setEnabled(false);
ui->haltButton->setEnabled(false);
ui->homeAllButton->setEnabled(false);
}
}
void EPOS2Widget::on_nodeIDcomboBox_currentIndexChanged(int index)
{
const int motorStatus = m_worker->getMotorStatus(index);
if(motorStatus != EPOS_INVALID_MOTOR_ID)
updateManualControls(motorStatus);
else
qDebug() << "Invalid motorID!";
}
void EPOS2Widget::on_enableNodeButton_clicked()
{
const int axisID = ui->nodeIDcomboBox->currentIndex();
emit enableMotor(axisID);
}
void EPOS2Widget::on_disableNodeButton_clicked()
{
const int axisID = ui->nodeIDcomboBox->currentIndex();
emit disableMotor(axisID);
}
void EPOS2Widget::on_enableServoLoopButton_clicked()
{
emit startServoLoop();
}
void EPOS2Widget::on_disableServoLoopButton_clicked()
{
emit stopServoLoop();
}
void EPOS2Widget::on_homeAllButton_clicked()
{
// stop servo loop
emit stopServoLoop();
emit homeAllAxes();
}
void EPOS2Widget::on_trajOpenFileButton_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Open CSV File"),
"../ICEbot_QT_v1/LoggedData",
tr("CSV File (*.csv)"));
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << file.errorString();
return;
}
QTextStream in(&file);
m_pyrtQCs.clear();
while (!in.atEnd()) {
QString line = in.readLine();
QStringList split = line.split(',');
if(split.size() == 4)
{
PYRT qc;
qc.pitchQC = split[0].toLong();
qc.yawQC = split[1].toLong();
qc.rollQC = split[2].toLong();
qc.transQC = split[3].toLong();
m_pyrtQCs.push_back(qc);
}
else
{
qDebug() << "Error reading CSV - number of elements in line is not equal to 4!";
break;
}
}
qDebug() << "Read" << m_pyrtQCs.size() << "setpoints from trajectory file.";
if(m_pyrtQCs.size() > 0){
ui->trajDriveButton->setEnabled(true);
ui->trajStepLineEdit->setText(QString("%1 points loaded.").arg(m_pyrtQCs.size()));
}
else{
ui->trajDriveButton->setEnabled(false);
ui->trajStepLineEdit->setText("Error reading file.");
}
}
void EPOS2Widget::on_trajDriveButton_clicked()
{
if(m_keepDriving)
{
m_keepDriving = false;
ui->trajDriveButton->setText("Drive");
// stop timer
m_trajTimer->stop();
disconnect(m_trajTimer, SIGNAL(timeout()), 0, 0);
delete m_trajTimer;
}
else
{
m_keepDriving = true;
ui->trajDriveButton->setText("Stop");
m_currTrajIdx = 0;
ui->trajStepLineEdit->setText(QString("%1 of %2.").arg(m_currTrajIdx).arg(m_pyrtQCs.size()));
PYRT currPYRT = m_pyrtQCs[m_currTrajIdx];
std::vector<long> newPos(4);
newPos[TRANS_AXIS_ID] = currPYRT.transQC;
newPos[PITCH_AXIS_ID] = currPYRT.pitchQC;
newPos[YAW_AXIS_ID] = currPYRT.yawQC;
newPos[ROLL_AXIS_ID] = currPYRT.rollQC;
setServoTargetPos(newPos, true);
// start timer
m_trajTimer = new QTimer(this);
connect(m_trajTimer, SIGNAL(timeout()), this, SLOT(driveTrajectory()));
m_trajTimer->start(10);
}
}
void EPOS2Widget::driveTrajectory()
{
PYRT currPYRT = m_pyrtQCs[m_currTrajIdx];
if( (abs(ui->pitchQC_LCD->intValue() - ui->rollQC_LCD->intValue() - currPYRT.pitchQC) < 5) &&
(abs(ui->yawQC_LCD->intValue() + ui->rollQC_LCD->intValue() - currPYRT.yawQC) < 5) &&
(abs(ui->rollQC_LCD->intValue() - currPYRT.rollQC) < 5) &&
(abs(ui->transQC_LCD->intValue() - currPYRT.transQC) < 5) && m_keepDriving)
{
m_currTrajIdx++;
ui->trajStepLineEdit->setText(QString("%1 of %2.").arg(m_currTrajIdx).arg(m_pyrtQCs.size()));
if(m_currTrajIdx < m_pyrtQCs.size())
{
currPYRT = m_pyrtQCs[m_currTrajIdx];
std::vector<long> newPos(4);
newPos[TRANS_AXIS_ID] = currPYRT.transQC;
newPos[PITCH_AXIS_ID] = currPYRT.pitchQC;
newPos[YAW_AXIS_ID] = currPYRT.yawQC;
newPos[ROLL_AXIS_ID] = currPYRT.rollQC;
setServoTargetPos(newPos, true); // absolute
qDebug() << "Drive to" << newPos[TRANS_AXIS_ID] << newPos[PITCH_AXIS_ID] << newPos[YAW_AXIS_ID] << newPos[ROLL_AXIS_ID];
}
else
{
m_keepDriving = false;
ui->trajDriveButton->setText("Drive");
}
}
}
| 16,314 | C++ | 33.27521 | 132 | 0.635773 |
adegirmenci/HBL-ICEbot/EPOS2Widget/epos2widget.h | #ifndef EPOS2WIDGET_H
#define EPOS2WIDGET_H
#include <QWidget>
#include <QThread>
#include <QLabel>
#include <QLCDNumber>
#include <QFileDialog>
#include <QTextStream>
#include <QStringList>
#include <QTimer>
#include <vector>
#include "epos2thread.h"
namespace Ui {
class EPOS2Widget;
}
struct PYRT
{
long pitchQC;
long yawQC;
long rollQC;
long transQC;
};
class EPOS2Widget : public QWidget
{
Q_OBJECT
public:
explicit EPOS2Widget(QWidget *parent = 0);
~EPOS2Widget();
EPOS2Thread *m_worker;
signals:
void setServoTargetPos(const int axisID, long targetPos, bool moveAbsOrRel);
void setServoTargetPos(std::vector<long> targetPos, bool moveAbsOrRel);
void servoToPos();
void servoToPos(const int axisID);
void haltMotor(const int axisID);
void enableMotor(const int axisID);
void disableMotor(const int axisID);
void startServoLoop();
void stopServoLoop();
void homeAxis(const int axisID);
void homeAllAxes();
private slots:
void workerStatusChanged(int status);
void workerMotorStatusChanged(const int motID, const int status);
void workerMotorStatusChanged(std::vector<int> status);
void workerMotorQcChanged(const int motID, const long QC);
void workerMotorQcChanged(std::vector<long> QCs);
void receiveDataFromWorker(int motorID, const QString &data);
void on_moveAbsButton_clicked();
void on_moveRelButton_clicked();
void on_homingButton_clicked();
void on_haltButton_clicked();
void on_nodeIDcomboBox_currentIndexChanged(int index);
void on_enableNodeButton_clicked();
void on_disableNodeButton_clicked();
void on_enableServoLoopButton_clicked();
void on_disableServoLoopButton_clicked();
void on_homeAllButton_clicked();
void on_trajOpenFileButton_clicked();
void on_trajDriveButton_clicked();
void driveTrajectory();
private:
Ui::EPOS2Widget *ui;
QThread m_thread; // EPOS Thread will live in here
std::vector<QLabel*> motLabels;
std::vector<QLCDNumber*> motQCs;
void updateManualControls(const int motorStatus);
// trajectory
std::vector<PYRT> m_pyrtQCs;
bool m_keepDriving;
size_t m_currTrajIdx;
QTimer *m_trajTimer;
};
#endif // EPOS2WIDGET_H
| 2,277 | C | 20.695238 | 80 | 0.711902 |
adegirmenci/HBL-ICEbot/EPOS2Widget/epos2thread.cpp | #include "epos2thread.h"
EPOS2Thread::EPOS2Thread(QObject *parent) : QObject(parent)
{
qRegisterMetaType< std::vector<long> >("std::vector<long>");
m_isEpochSet = false;
m_isReady = false;
m_keepServoing = false;
m_abort = false;
m_KeyHandle = 0;
m_mutex = new QMutex(QMutex::Recursive);
qDebug() << "Initizializing pointers to eposMotor";
for(size_t i = 0; i < EPOS_NUM_MOTORS; i++)
{
m_motors.push_back(std::shared_ptr<eposMotor>(new eposMotor));
m_motors[i]->m_nodeID = EPOS_MOTOR_IDS[i];
m_motors[i]->m_minQC = EPOS_MOTOR_LIMITS[i][0]; // lower limit
m_motors[i]->m_maxQC = EPOS_MOTOR_LIMITS[i][1]; // upper limit
m_motors[i]->m_enabled = false;
}
}
EPOS2Thread::~EPOS2Thread()
{
disconnectEPOS();
m_mutex->lock();
m_abort = true;
qDebug() << "Ending EPOS2Thread - ID: " << reinterpret_cast<int>(QThread::currentThreadId()) << ".";
m_mutex->unlock();
delete m_mutex;
emit finished();
}
bool EPOS2Thread::initializeEPOS()
{
QMutexLocker locker(m_mutex);
emit logEvent(SRC_EPOS, LOG_INFO, QTime::currentTime(), EPOS_INITIALIZE_BEGIN);
emit statusChanged(EPOS_INITIALIZE_BEGIN);
qDebug() << "Opening connection to EPOS...";
if(m_KeyHandle)
{
//Close Previous Device
if(!VCS_CloseDevice(m_KeyHandle, &m_ulErrorCode))
ShowErrorInformation(m_ulErrorCode);
m_KeyHandle = 0;
}
else
m_KeyHandle = 0;
//Settings
m_oImmediately = true; // don't wait until end of last move
m_oUpdateActive = false;
HANDLE hNewKeyHandle;
hNewKeyHandle = VCS_OpenDeviceDlg(&m_ulErrorCode);
if(hNewKeyHandle)
m_KeyHandle = hNewKeyHandle;
else
{
ShowErrorInformation(m_ulErrorCode);
emit logEvent(SRC_EPOS, LOG_INFO, QTime::currentTime(), EPOS_INITIALIZE_FAILED);
emit statusChanged(EPOS_INITIALIZE_FAILED);
return false;
}
// Set properties of each motor
bool status = true;
//locker.unlock();
for(int i = 0; i < EPOS_NUM_MOTORS; i++)
{
if(!initializeMotor( EPOS_AXIS_IDS[i]) )
{
status = false;
ShowErrorInformation(m_ulErrorCode);
}
else
status = status && true;
}
//locker.relock();
emit logEvent(SRC_EPOS, LOG_INFO, QTime::currentTime(), EPOS_INITIALIZED);
emit statusChanged(EPOS_INITIALIZED);
return status;
}
void EPOS2Thread::startServoing()
{
QMutexLocker locker(m_mutex);
m_timer = new QTimer(this);
m_timer->start(0);
connect(m_timer,SIGNAL(timeout()),this,SLOT(servoToPosition()));
m_keepServoing = true;
// QElapsedTimer elTimer;
// elTimer.start();
// QTime::currentTime();
// qint64 elNsec = elTimer.nsecsElapsed();
// qDebug() << "Nsec elapsed:" << elNsec;
emit logEvent(SRC_EPOS, LOG_INFO, QTime::currentTime(), EPOS_SERVO_LOOP_STARTED);
emit statusChanged(EPOS_SERVO_LOOP_STARTED);
qDebug() << "Servo loop started.";
}
void EPOS2Thread::setServoTargetPos(const int axisID, long targetPos, bool moveAbsOrRel)
{
QMutexLocker locker(m_mutex);
// check axis limits
if(checkMotorID(axisID))
{
if(moveAbsOrRel)
targetPos = clampToMotorLimits(axisID, targetPos); // abs
else
targetPos = clampToMotorLimits(axisID, m_motors[axisID]->m_lActualValue + targetPos); // rel
// compensate for roll
if(ROLL_AXIS_ID == axisID)
{
// #relativeRoll = #currentIncrement - #oldPosition
long relativeRoll;
if(moveAbsOrRel)
relativeRoll = targetPos; // this got added later (1/17/17)
else
relativeRoll = targetPos - m_motors[ROLL_AXIS_ID]->m_lActualValue; // it was just this before (1/17/17)
// this works because roll is the last to update
// if roll is not the last to get updated, then these target values
// would get overwritten
m_motors[PITCH_AXIS_ID]->m_lTargetPosition += relativeRoll; //pitch
m_motors[YAW_AXIS_ID]->m_lTargetPosition -= relativeRoll; //yaw
//update limits
// m_motors[PITCH_AXIS_ID]->m_minQC += relativeRoll;
// m_motors[PITCH_AXIS_ID]->m_maxQC += relativeRoll;
// m_motors[YAW_AXIS_ID]->m_minQC -= relativeRoll;
// m_motors[YAW_AXIS_ID]->m_maxQC -= relativeRoll;
m_motors[PITCH_AXIS_ID]->m_minQC = EPOS_PITCH_MIN + targetPos;
m_motors[PITCH_AXIS_ID]->m_maxQC = EPOS_PITCH_MAX + targetPos;
m_motors[YAW_AXIS_ID]->m_minQC = EPOS_YAW_MIN - targetPos;
m_motors[YAW_AXIS_ID]->m_maxQC = EPOS_YAW_MAX - targetPos;
// recheck pitch and yaw
m_motors[PITCH_AXIS_ID]->m_lTargetPosition = clampToMotorLimits(PITCH_AXIS_ID, m_motors[PITCH_AXIS_ID]->m_lTargetPosition);
m_motors[YAW_AXIS_ID]->m_lTargetPosition = clampToMotorLimits(YAW_AXIS_ID, m_motors[YAW_AXIS_ID]->m_lTargetPosition);
}
// finally, update the target
m_motors[axisID]->m_lTargetPosition = targetPos;
}
}
void EPOS2Thread::setServoTargetPos(std::vector<long> targetPos, bool moveAbsOrRel)
{
QMutexLocker locker(m_mutex);
if(targetPos.size() != EPOS_NUM_MOTORS)
qDebug() << "Wrong vector size in setServoTargetPos.";
// reset the limit changes due to roll
if(moveAbsOrRel)
{
m_motors[PITCH_AXIS_ID]->m_minQC = EPOS_PITCH_MIN;
m_motors[PITCH_AXIS_ID]->m_maxQC = EPOS_PITCH_MAX;
m_motors[YAW_AXIS_ID]->m_minQC = EPOS_YAW_MIN;
m_motors[YAW_AXIS_ID]->m_maxQC = EPOS_YAW_MAX;
}
for(int i = 0; i < EPOS_NUM_MOTORS; i++)
{
// if(moveAbsOrRel)
// m_motors[i]->m_lTargetPosition = targetPos[i];
// else
// m_motors[i]->m_lTargetPosition += targetPos[i];
setServoTargetPos(i, targetPos[i], moveAbsOrRel);
}
}
int EPOS2Thread::checkMotorLimits(const int axisID, const long targetPos)
{
QMutexLocker locker(m_mutex);
if(targetPos < m_motors[axisID]->m_minQC) // too small
return -1;
else if(targetPos > m_motors[axisID]->m_maxQC) // too large
return 1;
else // just right
return 0;
}
long EPOS2Thread::clampToMotorLimits(const int axisID, const long targetPos)
{
QMutexLocker locker(m_mutex);
if(targetPos < m_motors[axisID]->m_minQC) // too small
return m_motors[axisID]->m_minQC;
else if(targetPos > m_motors[axisID]->m_maxQC) // too large
return m_motors[axisID]->m_maxQC;
else // just right
return targetPos;
}
// Calls to the motors will ALWAYS be executed SEQUENTIALLY over a single USB line, because data can only travel sequentially
// over a serial port.
// If we need to REDUCE the LATENCY, then we should consider using two USB cables.
// If the main concern is SYNCING the MOTION COMMANDS, then we can have the master (root) EPOS send a trigger signal to the
// slave boards AFTER all the motor target positions have been updated.
void EPOS2Thread::servoToPosition()
{
QMutexLocker locker(m_mutex);
updateMotorQCs();
// QElapsedTimer elTimer;
// qDebug() << "Using clock type " << elTimer.clockType();
// elTimer.start();
for(int i = 0; i < EPOS_NUM_MOTORS; i++)
{
servoToPosition(i);
}
// qDebug() << "Elapsed Time: " << elTimer.nsecsElapsed()/1000000. << " ms";
}
void EPOS2Thread::servoToPosition(const int axisID)
{
QMutexLocker locker(m_mutex);
if(checkMotorID(axisID))
{
WORD usNodeId = m_motors[axisID]->m_nodeID;
if(m_motors[axisID]->m_enabled)
{
//updateMotorQC(axisID); // this may not be the best place to put this
emit logData(QTime::currentTime(), EPOS_COMMANDED, axisID, m_motors[axisID]->m_lTargetPosition);
if(!VCS_MoveToPosition(m_KeyHandle, usNodeId, m_motors[axisID]->m_lTargetPosition, true, m_oImmediately, &m_ulErrorCode))
{
ShowErrorInformation(m_ulErrorCode);
qDebug() << QString("Servo to pos failed! Axis %1, Node %2").arg(axisID).arg(usNodeId);
emit statusChanged(EPOS_SERVO_TO_POS_FAILED);
}
}
}
}
void EPOS2Thread::stopServoing()
{
QMutexLocker locker(m_mutex);
if ( m_keepServoing )
{
m_keepServoing = false;
m_timer->stop();
disconnect(m_timer,SIGNAL(timeout()),0,0);
delete m_timer;
emit logEvent(SRC_EPOS, LOG_INFO, QTime::currentTime(), EPOS_SERVO_LOOP_STOPPED);
emit statusChanged(EPOS_SERVO_LOOP_STOPPED);
qDebug() << "Servo loop stopped.";
}
}
void EPOS2Thread::updateMotorQC(const int axisID)
{
QMutexLocker locker(m_mutex);
if(checkMotorID(axisID))
{
//Read Actual Position
if(VCS_GetPositionIs(m_KeyHandle, m_motors[axisID]->m_nodeID,
&(m_motors[axisID]->m_lActualValue),
&m_ulErrorCode))
{
emit logData(QTime::currentTime(), EPOS_READ, axisID, m_motors[axisID]->m_lActualValue);
emit motorQcChanged(axisID, m_motors[axisID]->m_lActualValue);
}
else
{
ShowErrorInformation(m_ulErrorCode);
emit statusChanged(EPOS_UPDATE_QC_FAILED);
}
}
}
void EPOS2Thread::updateMotorQCs()
{
QMutexLocker locker(m_mutex);
for(int i = 0; i < EPOS_NUM_MOTORS; i++)
{
if(m_motors[i]->m_enabled)
updateMotorQC(i);
}
}
void EPOS2Thread::haltMotor(const int axisID)
{
QMutexLocker locker(m_mutex);
if(checkMotorID(axisID))
{
if(VCS_HaltPositionMovement(m_KeyHandle, m_motors[axisID]->m_nodeID, &m_ulErrorCode))
{
//Read Actual Position
updateMotorQC(axisID);
}
else
{
ShowErrorInformation(m_ulErrorCode);
qDebug() << QString("Halt failed! Node %1").arg(m_motors[axisID]->m_nodeID);
emit statusChanged(EPOS_HALT_FAILED);
}
}
}
void EPOS2Thread::homeAxis(const int axisID)
{
QMutexLocker locker(m_mutex);
if(checkMotorID(axisID))
{
// set a lower speed
if(m_motors[axisID]->m_enabled)
{
WORD nodeID = m_motors[axisID]->m_nodeID;
if(!VCS_SetPositionProfile(m_KeyHandle,nodeID,
1400,2000,2000,&m_ulErrorCode))
{
ShowErrorInformation(m_ulErrorCode);
}
m_motors[axisID]->m_minQC = EPOS_MOTOR_LIMITS[axisID][0]; // reset lower limit
m_motors[axisID]->m_maxQC = EPOS_MOTOR_LIMITS[axisID][1]; // reset upper limit
setServoTargetPos(axisID, 0, true); // set target position to 0
// TODO: this should be a blocking call, otherwise speed gets reset during motion
servoToPosition(axisID); // servo motor
// reset speed
if(!VCS_SetPositionProfile(m_KeyHandle,nodeID,
EPOS_VELOCITY[axisID],EPOS_ACCEL[axisID],EPOS_DECEL[axisID],&m_ulErrorCode))
{
ShowErrorInformation(m_ulErrorCode);
}
}
}
}
void EPOS2Thread::homeAllAxes()
{
QMutexLocker locker(m_mutex);
for(int i = 0; i < EPOS_NUM_MOTORS; i++)
{
if(m_motors[i]->m_enabled)
{
// set a lower speed
WORD nodeID = m_motors[i]->m_nodeID;
if(!VCS_SetPositionProfile(m_KeyHandle,nodeID,
1400,2000,2000,&m_ulErrorCode))
{
ShowErrorInformation(m_ulErrorCode);
}
m_motors[i]->m_minQC = EPOS_MOTOR_LIMITS[i][0]; // reset lower limit
m_motors[i]->m_maxQC = EPOS_MOTOR_LIMITS[i][1]; // reset upper limit
// don't use setServoPos here, since that will compensate for roll
// self comment: setServoPos(vector) would probably work though?
m_motors[i]->m_lTargetPosition = 0;
// TODO: a better strategy is probably to get the catheter straight first, then home
}
}
// TODO: this should be a blocking call, otherwise speed gets reset during motion
servoToPosition(); // servo motors
// reset speed
for(int i = 0; i < EPOS_NUM_MOTORS; i++)
{
if(m_motors[i]->m_enabled)
{
WORD nodeID = m_motors[i]->m_nodeID;
if(!VCS_SetPositionProfile(m_KeyHandle,nodeID,
EPOS_VELOCITY[i],EPOS_ACCEL[i],EPOS_DECEL[i],&m_ulErrorCode))
{
ShowErrorInformation(m_ulErrorCode);
}
}
}
}
bool EPOS2Thread::disconnectEPOS()
{
bool status = true;
homeAllAxes();
QThread::sleep(2);
stopServoing();
QMutexLocker locker(m_mutex);
if(m_KeyHandle)
{
//locker.unlock();
for(int i = 0; i < EPOS_NUM_MOTORS; i++)
{
status = status && disableMotor( EPOS_AXIS_IDS[i] );
}
//locker.relock();
if(status)
qDebug() << "Motors disabled.";
status = VCS_CloseDevice(m_KeyHandle, &m_ulErrorCode);
if(status)
{
m_KeyHandle = 0;
qDebug() << "EPOS closed successfully.";
emit statusChanged(EPOS_DISCONNECTED);
}
else
{
ShowErrorInformation(m_ulErrorCode);
emit statusChanged(EPOS_DISCONNECT_FAILED);
}
}
else
{
qDebug() << ("EPOS is already closed.");
}
return status;
}
void EPOS2Thread::setEpoch(const QDateTime &datetime)
{
QMutexLocker locker(m_mutex);
if(!m_keepServoing)
{
m_epoch = datetime;
m_isEpochSet = true;
emit logEventWithMessage(SRC_EPOS, LOG_INFO, QTime::currentTime(), EPOS_EPOCH_SET,
m_epoch.toString("yyyy/MM/dd - hh:mm:ss.zzz"));
}
else
emit logEvent(SRC_EPOS, LOG_INFO, QTime::currentTime(), EPOS_EPOCH_SET_FAILED);
}
// ----------------
// HELPER FUNCTIONS
// ----------------
bool EPOS2Thread::initializeMotor(const int motID)
{
QMutexLocker locker(m_mutex);
bool result = checkMotorID(motID);
if(result && !m_motors[motID]->m_enabled)
{
std::shared_ptr<eposMotor> mot = m_motors[motID];
mot->m_bMode = 0;
mot->m_lActualValue = 0;
mot->m_lStartPosition = 0;
mot->m_lTargetPosition = 0;
WORD usNodeID = mot->m_nodeID;
qDebug() << QString("Connecting to Node %1...").arg(usNodeID);
mot->m_enabled = false;
if(m_KeyHandle)
{
//Clear Error History
if(VCS_ClearFault(m_KeyHandle, usNodeID, &m_ulErrorCode))
{
//Enable
if( VCS_SetEnableState(m_KeyHandle, usNodeID, &m_ulErrorCode) )
{
//Read Operation Mode
if(VCS_GetOperationMode(m_KeyHandle, usNodeID,
&(mot->m_bMode),
&m_ulErrorCode))
{
//Read Position Profile Objects
if(VCS_GetPositionProfile(m_KeyHandle, usNodeID,
&(mot->m_ulProfileVelocity),
&(mot->m_ulProfileAcceleration),
&(mot->m_ulProfileDeceleration),
&m_ulErrorCode))
{
//Write Profile Position Mode
if(VCS_SetOperationMode(m_KeyHandle, usNodeID,
OMD_PROFILE_POSITION_MODE,
&m_ulErrorCode))
{
//Write Profile Position Objects
if(VCS_SetPositionProfile(m_KeyHandle, usNodeID,
EPOS_VELOCITY[motID],
EPOS_ACCEL[motID],
EPOS_DECEL[motID],
&m_ulErrorCode))
{
mot->m_ulProfileVelocity = EPOS_VELOCITY[motID];
mot->m_ulProfileAcceleration = EPOS_ACCEL[motID];
mot->m_ulProfileDeceleration = EPOS_DECEL[motID];
//Read Actual Position
if(VCS_GetPositionIs(m_KeyHandle, usNodeID,
&(mot->m_lStartPosition),
&m_ulErrorCode))
{
qDebug() << "DONE!";
mot->m_lActualValue = mot->m_lStartPosition;
mot->m_lTargetPosition = mot->m_lStartPosition;
mot->m_enabled = true;
mot->m_motorStatus = EPOS_MOTOR_ENABLED;
result = true;
emit motorStatusChanged(motID, EPOS_MOTOR_ENABLED);
emit motorQcChanged(motID, mot->m_lActualValue);
}
}
}
}
}
}
}
if(!mot->m_enabled)
{
qDebug() << "Can't connect to motor!";
ShowErrorInformation(m_ulErrorCode);
mot->m_motorStatus = EPOS_MOTOR_CANT_CONNECT;
emit motorStatusChanged(motID, EPOS_MOTOR_CANT_CONNECT);
result = false;
}
}
else
{
qDebug() << "Can't open device!";
mot->m_enabled = false;
mot->m_motorStatus = EPOS_MOTOR_CANT_CONNECT;
result = false;
emit statusChanged(EPOS_DEVICE_CANT_CONNECT);
}
}
return result;
}
bool EPOS2Thread::disableMotor(const int motID)
{
QMutexLocker locker(m_mutex);
bool result = checkMotorID(motID);
if(result && m_motors[motID]->m_enabled)
{
std::shared_ptr<eposMotor> mot = m_motors[motID];
WORD usNodeID = mot->m_nodeID; //get motor ID
mot->m_enabled = false; // set flag to false
mot->m_motorStatus = EPOS_MOTOR_DISABLED;
// disable motor
result = VCS_SetDisableState(m_KeyHandle, usNodeID, &m_ulErrorCode);
if(result)
{
qDebug() <<"Motor " << usNodeID << " disabled.";
emit motorStatusChanged(motID, EPOS_MOTOR_DISABLED);
}
else
ShowErrorInformation(m_ulErrorCode);
}
return result;
}
const int EPOS2Thread::getMotorStatus(const int axisID)
{
QMutexLocker locker(m_mutex);
bool result = checkMotorID(axisID);
if(result)
return m_motors[axisID]->m_motorStatus;
else
return EPOS_INVALID_MOTOR_ID;
}
bool EPOS2Thread::ShowErrorInformation(DWORD p_ulErrorCode)
{
char* pStrErrorInfo;
const char* strDescription;
QString msg(QString("Error Code %1: ").arg(QString::number(p_ulErrorCode)));
if((pStrErrorInfo = (char*)malloc(100)) == NULL)
{
msg.append("Not enough memory to allocate buffer for error information string.");
qDebug() << "Maxon: " << msg;
return false;
}
if(VCS_GetErrorInfo(p_ulErrorCode, pStrErrorInfo, 100))
{
strDescription = pStrErrorInfo;
msg.append(strDescription);
qDebug() << "Maxon: " << msg;
emit logError(SRC_EPOS, LOG_ERROR, QTime::currentTime(), EPOS_FAIL, msg);
free(pStrErrorInfo);
return true;
}
else
{
msg.append("Error information can't be read!");
free(pStrErrorInfo);
qDebug() << "Maxon: " << msg;
emit logError(SRC_EPOS, LOG_ERROR, QTime::currentTime(), EPOS_FAIL, msg);
return false;
}
}
bool EPOS2Thread::checkMotorID(const int motID)
{
if( (motID >= EPOS_NUM_MOTORS) || (motID < 0) )
{
QString msg = QString("Motor ID (%1) out of bounds").arg(motID);
emit logEventWithMessage(SRC_EPOS, LOG_ERROR,
QTime::currentTime(),
EPOS_DISABLE_MOTOR_FAILED,
msg);
qDebug() << msg;
return false;
}
return true;
}
QString EPOS2Thread::formatOutput(QTime &timeStamp,
const int motorID,
long pos)
{
QString output;
output.append(timeStamp.toString("HH.mm.ss.zzz\n"));
output.append(QString("[Motor %1] - %2 QCs").arg(motorID).arg(pos));
return QString();
}
inline const QString getCurrTimeStr()
{
return QTime::currentTime().toString("HH.mm.ss.zzz");
}
inline const QString getCurrDateTimeStr()
{
return QDateTime::currentDateTime().toString("yyyy/MM/dd - hh:mm:ss.zzz");
}
| 21,645 | C++ | 29.359046 | 135 | 0.54225 |
adegirmenci/HBL-ICEbot/EPOS2Widget/MaxonLibs/Definitions.h | /*********************************************************************
** maxon motor ag, CH-6072 Sachseln
**********************************************************************
**
** File: Definitions.h
** Description: Functions definitions for EposCmd.dll/EposCmd64.dll library for Developer Platform Microsoft Visual C++
**
** Date: 20.10.03
** Dev. Platform: Microsoft Visual C++
** Target: Windows Operating Systems
** Written by: maxon motor ag, CH-6072 Sachseln
**
** History: 1.00 (20.10.03): Initial version
** 1.01 (01.12.03): Changed Functions: VCS_GetDeviceNameSelection, BOOL VCS_GetDeviceName, VCS_GetProtocolStackNameSelection,
** VCS_GetInterfaceNameSelection, VCS_GetPortNameSelection, VCS_GetBaudrateSelection,
** VCS_GetProtocolStackModeSelection, VCS_GetProtocolStackName, VCS_GetInterfaceName, VCS_GetPortName
** 1.1.0.0 (13.01.04): Bugfix: If the functions GetXXXSelection were alone called, no manager was initialized. Again an inquiry inserted
** (21.01.04): New Functions: VCS_CloseAllDevices, VCS_DigitalInputConfiguration, VCS_DigitalOutputConfiguration,
** VCS_GetAllDigitalInputs, VCS_GetAllDigitalOutputs, VCS_GetAnalogInput, VCS_SetAllDigitalOutputs
** (29.03.04): New Functions: VCS_OpenDeviceDlg, SendNMTService
** Changed Functions: VCS_OpenDevice, VCS_SetObject, VCS_GetObject, VCS_FindHome, VCS_SetOperationMode, VCS_GetOperationMode, VCS_MoveToPosition
** Deleted Functions: VCS_GetProtocolStackMode, VCS_GetProtocolStackModeSelection
** 2.0.0.0 (07.04.04): Release version
** 2.0.1.0 (13.04.04): Bugfix version
** 2.0.2.0 (15.04.04): Bugfix version
** 2.0.3.0 (11.05.04): Bugfix version
** (07.12.04): New Functions: VCS_SendCANFrame, VCS_RequestCANFrame
** 3.0.0.0 (31.03.05): Changes: All EPOS - functions => new with the handle for the Journal
** New Functions: VCS_StartJournal, VCS_StopJournal
** 3.0.1.0 (08.03.05): Internal version
** 3.0.2.0 (09.09.05): BugFix: Support IXXAT interfaces with 2 ports
** 4.0.0.0 (21.10.05): Release version
** 4.1.0.0 (02.02.06): Internal version: New DLL structure (Dtms and GUI Version 2.01)
** 4.1.1.0 (12.04.06): Internal version
** 4.1.2.0 (12.06.06): Internal version
** 4.1.3.0 (03.07.06): Internal version: GUI Version 2.04
** 4.1.4.0 (16.08.06): New: LSS functions implemented
** 4.2.0.0 (12.10.06): Customer version
** 4.3.0.0 (01.02.07): New: Support National Instruments CANopen interfaces
** 4.4.0.0 (10.08.07): Expansion: VCI3 driver support for IXXAT CANopen interfaces
** 4.5.0.0 (01.05.08): Internal: Converted to development environment Visual Studio 2005
** New: Read device error history (VCS_GetNbOfDeviceError, VCS_GetDeviceErrorCode)
** 4.6.1.0 (04.09.09): New: Support for EPOS2 functionality, data recorder, parameter export and import. VCS_ReadCANFrame
** 4.7.1.0 (30.08.10): New: Add parameter DialogMode for Findxxx functions
** 4.7.2.0 (11.10.10): BugFix: Deadlock when closing application
** Communication for IXXAT VCI V3.3
** 4.7.3.0 (28.10.10): Bugfix: Functions VCS_CloseDevice, VCS_CloseAllDevices
** 4.8.1.0 (28.01.11): New: Enlargement of 64-Bit operating systems
** Bugfix: Segmented Write
** 4.8.2.0 (02.02.11): Changes: Detect properly LIN devices
** 4.8.5.x (10.04.12): Bugfix: Sporadic CAN failure with IXXAT VCI V3.3
** 4.8.6.x (08.10.12): New: Add support for Vector VN1600 series
** 4.8.7.x (10.10.12): New functions: VCS_GetVelocityRegulatorFeedForward, VCS_SetVelocityRegulatorFeedForward
** Bugfix: Command VCS_SendNmtService
** 4.9.1.0 (04.01.13): New Functions: VCS_GetHomingState, VCS_WaitForHomingAttained, VCS_GetVelocityIsAveraged, VCS_GetCurrentIsAveraged
** 4.9.2.0 (22.03.13): Bugfix: Function ExportParameter: Parameters renamed
** 4.9.3.0 (25.07.13): Internal version
** 4.9.4.0 (01.10.13): Bugfix: Function VCS_GetDriverInfo 64-Bit variant
** 4.9.5.0 (17.12.13): Changes: VCS_ExportChannelDataToFile: Check path exists
** 5.0.1.0 (24.10.14): New: Support Kvaser CANopen interfaces
** New: Support for NI-XNET driver
**
*********************************************************************/
// --------------------------------------------------------------------------
// DIRECTIVES
// --------------------------------------------------------------------------
#ifndef _WINDOWS_
#include <windows.h>
#endif
#if !defined(EposCommandLibraryDefinitions)
#define EposCommandLibraryDefinitions
// --------------------------------------------------------------------------
// IMPORTED FUNCTIONS PROTOTYPE
// --------------------------------------------------------------------------
// INITIALISATION FUNCTIONS
#define Initialisation_DllExport extern "C" __declspec( dllexport )
#define HelpFunctions_DllExport extern "C" __declspec( dllexport )
// CONFIGURATION FUNCTIONS
#define Configuration_DllExport extern "C" __declspec( dllexport )
// OPERATION FUNCTIONS
#define Status_DllExport extern "C" __declspec( dllexport )
#define StateMachine_DllExport extern "C" __declspec( dllexport )
#define ErrorHandling_DllExport extern "C" __declspec( dllexport )
#define MotionInfo_DllExport extern "C" __declspec( dllexport )
#define ProfilePositionMode_DllExport extern "C" __declspec( dllexport )
#define ProfileVelocityMode_DllExport extern "C" __declspec( dllexport )
#define HomingMode_DllExport extern "C" __declspec( dllexport )
#define InterpolatedPositionMode_DllExport extern "C" __declspec( dllexport )
#define PositionMode_DllExport extern "C" __declspec( dllexport )
#define VelocityMode_DllExport extern "C" __declspec( dllexport )
#define CurrentMode_DllExport extern "C" __declspec( dllexport )
#define MasterEncoderMode_DllExport extern "C" __declspec( dllexport )
#define StepDirectionMode_DllExport extern "C" __declspec( dllexport )
#define InputsOutputs_DllExport extern "C" __declspec( dllexport )
// DATA RECORDING FUNCTIONS
#define DataRecording_DllExport extern "C" __declspec( dllexport )
// LOW LAYER FUNCTIONS
#define CanLayer_DllExport extern "C" __declspec( dllexport )
/*************************************************************************************************************************************
* INITIALISATION FUNCTIONS
*************************************************************************************************************************************/
//Communication
Initialisation_DllExport HANDLE __stdcall VCS_OpenDevice(char* DeviceName, char* ProtocolStackName, char* InterfaceName, char* PortName, DWORD* pErrorCode);
Initialisation_DllExport HANDLE __stdcall VCS_OpenDeviceDlg(DWORD* pErrorCode);
Initialisation_DllExport BOOL __stdcall VCS_SetProtocolStackSettings(HANDLE KeyHandle, DWORD Baudrate, DWORD Timeout, DWORD* pErrorCode);
Initialisation_DllExport BOOL __stdcall VCS_GetProtocolStackSettings(HANDLE KeyHandle, DWORD* pBaudrate, DWORD* pTimeout, DWORD* pErrorCode);
Initialisation_DllExport BOOL __stdcall VCS_FindDeviceCommunicationSettings(HANDLE *pKeyHandle, char *pDeviceName, char *pProtocolStackName, char *pInterfaceName, char *pPortName, WORD SizeName, DWORD *pBaudrate, DWORD *pTimeout, WORD *pNodeId, int DialogMode, DWORD *pErrorCode);
Initialisation_DllExport BOOL __stdcall VCS_CloseDevice(HANDLE KeyHandle, DWORD* pErrorCode);
Initialisation_DllExport BOOL __stdcall VCS_CloseAllDevices(DWORD* pErrorCode);
//Info
HelpFunctions_DllExport BOOL __stdcall VCS_GetDriverInfo(char* pLibraryName, WORD MaxNameSize, char* pLibraryVersion, WORD MaxVersionSize, DWORD* pErrorCode);
HelpFunctions_DllExport BOOL __stdcall VCS_GetVersion(HANDLE KeyHandle, WORD NodeId, WORD* pHardwareVersion, WORD* pSoftwareVersion, WORD* pApplicationNumber, WORD* pApplicationVersion, DWORD* pErrorCode);
HelpFunctions_DllExport BOOL __stdcall VCS_GetErrorInfo(DWORD ErrorCodeValue, char* pErrorInfo, WORD MaxStrSize);
//Advanced Functions
HelpFunctions_DllExport BOOL __stdcall VCS_GetDeviceNameSelection(BOOL StartOfSelection, char* pDeviceNameSel, WORD MaxStrSize, BOOL* pEndOfSelection, DWORD* pErrorCode);
HelpFunctions_DllExport BOOL __stdcall VCS_GetProtocolStackNameSelection(char* DeviceName, BOOL StartOfSelection, char* pProtocolStackNameSel, WORD MaxStrSize, BOOL* pEndOfSelection, DWORD* pErrorCode);
HelpFunctions_DllExport BOOL __stdcall VCS_GetInterfaceNameSelection(char* DeviceName, char* ProtocolStackName, BOOL StartOfSelection, char* pInterfaceNameSel, WORD MaxStrSize, BOOL* pEndOfSelection, DWORD* pErrorCode);
HelpFunctions_DllExport BOOL __stdcall VCS_GetPortNameSelection(char* DeviceName, char* ProtocolStackName, char* InterfaceName, BOOL StartOfSelection, char* pPortSel, WORD MaxStrSize, BOOL* pEndOfSelection, DWORD* pErrorCode);
HelpFunctions_DllExport BOOL __stdcall VCS_GetBaudrateSelection(char* DeviceName, char* ProtocolStackName, char* InterfaceName, char* PortName, BOOL StartOfSelection, DWORD* pBaudrateSel, BOOL* pEndOfSelection, DWORD* pErrorCode);
HelpFunctions_DllExport BOOL __stdcall VCS_GetKeyHandle(char* DeviceName, char* ProtocolStackName, char* InterfaceName, char* PortName, HANDLE* pKeyHandle, DWORD* pErrorCode);
HelpFunctions_DllExport BOOL __stdcall VCS_GetDeviceName(HANDLE KeyHandle, char* pDeviceName, WORD MaxStrSize, DWORD* pErrorCode);
HelpFunctions_DllExport BOOL __stdcall VCS_GetProtocolStackName(HANDLE KeyHandle, char* pProtocolStackName, WORD MaxStrSize, DWORD* pErrorCode);
HelpFunctions_DllExport BOOL __stdcall VCS_GetInterfaceName(HANDLE KeyHandle, char* pInterfaceName, WORD MaxStrSize, DWORD* pErrorCode);
HelpFunctions_DllExport BOOL __stdcall VCS_GetPortName(HANDLE KeyHandle, char* pPortName, WORD MaxStrSize, DWORD* pErrorCode);
/*************************************************************************************************************************************
* CONFIGURATION FUNCTIONS
*************************************************************************************************************************************/
//General
Configuration_DllExport BOOL __stdcall VCS_ImportParameter(HANDLE KeyHandle, WORD NodeId, char *pParameterFileName, BOOL ShowDlg, BOOL ShowMsg, DWORD *pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_ExportParameter(HANDLE KeyHandle, WORD NodeId, char *pParameterFileName, char *pFirmwareFileName, char *pUserID, char *pComment, BOOL ShowDlg, BOOL ShowMsg, DWORD *pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_SetObject(HANDLE KeyHandle, WORD NodeId, WORD ObjectIndex, BYTE ObjectSubIndex, void* pData, DWORD NbOfBytesToWrite, DWORD* pNbOfBytesWritten, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_GetObject(HANDLE KeyHandle, WORD NodeId, WORD ObjectIndex, BYTE ObjectSubIndex, void* pData, DWORD NbOfBytesToRead, DWORD* pNbOfBytesRead, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_Restore(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_Store(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
//Advanced Functions
//Motor
Configuration_DllExport BOOL __stdcall VCS_SetMotorType(HANDLE KeyHandle, WORD NodeId, WORD MotorType, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_SetDcMotorParameter(HANDLE KeyHandle, WORD NodeId, WORD NominalCurrent, WORD MaxOutputCurrent, WORD ThermalTimeConstant, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_SetEcMotorParameter(HANDLE KeyHandle, WORD NodeId, WORD NominalCurrent, WORD MaxOutputCurrent, WORD ThermalTimeConstant, BYTE NbOfPolePairs, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_GetMotorType(HANDLE KeyHandle, WORD NodeId, WORD* pMotorType, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_GetDcMotorParameter(HANDLE KeyHandle, WORD NodeId, WORD* pNominalCurrent, WORD* pMaxOutputCurrent, WORD* pThermalTimeConstant, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_GetEcMotorParameter(HANDLE KeyHandle, WORD NodeId, WORD* pNominalCurrent, WORD* pMaxOutputCurrent, WORD* pThermalTimeConstant, BYTE* pNbOfPolePairs, DWORD* pErrorCode);
//Sensor
Configuration_DllExport BOOL __stdcall VCS_SetSensorType(HANDLE KeyHandle, WORD NodeId, WORD SensorType, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_SetIncEncoderParameter(HANDLE KeyHandle, WORD NodeId, DWORD EncoderResolution, BOOL InvertedPolarity, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_SetHallSensorParameter(HANDLE KeyHandle, WORD NodeId, BOOL InvertedPolarity, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_SetSsiAbsEncoderParameter(HANDLE KeyHandle, WORD NodeId, WORD DataRate, WORD NbOfMultiTurnDataBits, WORD NbOfSingleTurnDataBits, BOOL InvertedPolarity, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_GetSensorType(HANDLE KeyHandle, WORD NodeId, WORD* pSensorType, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_GetIncEncoderParameter(HANDLE KeyHandle, WORD NodeId, DWORD* pEncoderResolution, BOOL* pInvertedPolarity, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_GetHallSensorParameter(HANDLE KeyHandle, WORD NodeId, BOOL* pInvertedPolarity, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_GetSsiAbsEncoderParameter(HANDLE KeyHandle, WORD NodeId, WORD* pDataRate, WORD* pNbOfMultiTurnDataBits, WORD* pNbOfSingleTurnDataBits, BOOL* pInvertedPolarity, DWORD* pErrorCode);
//Safety
Configuration_DllExport BOOL __stdcall VCS_SetMaxFollowingError(HANDLE KeyHandle, WORD NodeId, DWORD MaxFollowingError, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_GetMaxFollowingError(HANDLE KeyHandle, WORD NodeId, DWORD* pMaxFollowingError, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_SetMaxProfileVelocity(HANDLE KeyHandle, WORD NodeId, DWORD MaxProfileVelocity, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_GetMaxProfileVelocity(HANDLE KeyHandle, WORD NodeId, DWORD* pMaxProfileVelocity, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_SetMaxAcceleration(HANDLE KeyHandle, WORD NodeId, DWORD MaxAcceleration, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_GetMaxAcceleration(HANDLE KeyHandle, WORD NodeId, DWORD* pMaxAcceleration, DWORD* pErrorCode);
//Position Regulator
Configuration_DllExport BOOL __stdcall VCS_SetPositionRegulatorGain(HANDLE KeyHandle, WORD NodeId, WORD P, WORD I, WORD D, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_SetPositionRegulatorFeedForward(HANDLE KeyHandle, WORD NodeId, WORD VelocityFeedForward, WORD AccelerationFeedForward, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_GetPositionRegulatorGain(HANDLE KeyHandle, WORD NodeId, WORD* pP, WORD* pI, WORD* pD, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_GetPositionRegulatorFeedForward(HANDLE KeyHandle, WORD NodeId, WORD* pVelocityFeedForward, WORD* pAccelerationFeedForward, DWORD* pErrorCode);
//Velocity Regulator
Configuration_DllExport BOOL __stdcall VCS_SetVelocityRegulatorGain(HANDLE KeyHandle, WORD NodeId, WORD P, WORD I, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_SetVelocityRegulatorFeedForward(HANDLE KeyHandle, WORD NodeId, WORD VelocityFeedForward, WORD AccelerationFeedForward, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_GetVelocityRegulatorGain(HANDLE KeyHandle, WORD NodeId, WORD* pP, WORD* pI, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_GetVelocityRegulatorFeedForward(HANDLE KeyHandle, WORD NodeId, WORD* pVelocityFeedForward, WORD* pAccelerationFeedForward, DWORD* pErrorCode);
//Current Regulator
Configuration_DllExport BOOL __stdcall VCS_SetCurrentRegulatorGain(HANDLE KeyHandle, WORD NodeId, WORD P, WORD I, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_GetCurrentRegulatorGain(HANDLE KeyHandle, WORD NodeId, WORD* pP, WORD* pI, DWORD* pErrorCode);
//Inputs/Outputs
Configuration_DllExport BOOL __stdcall VCS_DigitalInputConfiguration(HANDLE KeyHandle, WORD NodeId, WORD DigitalInputNb, WORD Configuration, BOOL Mask, BOOL Polarity, BOOL ExecutionMask, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_DigitalOutputConfiguration(HANDLE KeyHandle, WORD NodeId, WORD DigitalOutputNb, WORD Configuration, BOOL State, BOOL Mask, BOOL Polarity, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_AnalogInputConfiguration(HANDLE KeyHandle, WORD NodeId, WORD AnlogInputNb, WORD Configuration, BOOL ExecutionMask, DWORD* pErrorCode);
//Units
Configuration_DllExport BOOL __stdcall VCS_SetVelocityUnits(HANDLE KeyHandle, WORD NodeId, BYTE VelDimension, char VelNotation, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_GetVelocityUnits(HANDLE KeyHandle, WORD NodeId, BYTE* pVelDimension, char* pVelNotation, DWORD* pErrorCode);
//Compatibility Functions (do not use)
Configuration_DllExport BOOL __stdcall VCS_SetMotorParameter(HANDLE KeyHandle, WORD NodeId, WORD MotorType, WORD ContinuousCurrent, WORD PeakCurrent, BYTE PolePair, WORD ThermalTimeConstant, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_SetEncoderParameter(HANDLE KeyHandle, WORD NodeId, WORD Counts, WORD PositionSensorType, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_GetMotorParameter(HANDLE KeyHandle, WORD NodeId, WORD* pMotorType, WORD* pContinuousCurrent, WORD* pPeakCurrent, BYTE* pPolePair, WORD* pThermalTimeConstant, DWORD* pErrorCode);
Configuration_DllExport BOOL __stdcall VCS_GetEncoderParameter(HANDLE KeyHandle, WORD NodeId, WORD* pCounts, WORD* pPositionSensorType, DWORD* pErrorCode);
/*************************************************************************************************************************************
* OPERATION FUNCTIONS
*************************************************************************************************************************************/
//OperationMode
Status_DllExport BOOL __stdcall VCS_SetOperationMode(HANDLE KeyHandle, WORD NodeId, __int8 OperationMode, DWORD* pErrorCode);
Status_DllExport BOOL __stdcall VCS_GetOperationMode(HANDLE KeyHandle, WORD NodeId, __int8* pOperationMode, DWORD* pErrorCode);
//StateMachine
StateMachine_DllExport BOOL __stdcall VCS_ResetDevice(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
StateMachine_DllExport BOOL __stdcall VCS_SetState(HANDLE KeyHandle, WORD NodeId, WORD State, DWORD* pErrorCode);
StateMachine_DllExport BOOL __stdcall VCS_SetEnableState(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
StateMachine_DllExport BOOL __stdcall VCS_SetDisableState(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
StateMachine_DllExport BOOL __stdcall VCS_SetQuickStopState(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
StateMachine_DllExport BOOL __stdcall VCS_ClearFault(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
StateMachine_DllExport BOOL __stdcall VCS_GetState(HANDLE KeyHandle, WORD NodeId, WORD* pState, DWORD* pErrorCode);
StateMachine_DllExport BOOL __stdcall VCS_GetEnableState(HANDLE KeyHandle, WORD NodeId, BOOL* pIsEnabled, DWORD* pErrorCode);
StateMachine_DllExport BOOL __stdcall VCS_GetDisableState(HANDLE KeyHandle, WORD NodeId, BOOL* pIsDisabled, DWORD* pErrorCode);
StateMachine_DllExport BOOL __stdcall VCS_GetQuickStopState(HANDLE KeyHandle, WORD NodeId, BOOL* pIsQuickStopped, DWORD* pErrorCode);
StateMachine_DllExport BOOL __stdcall VCS_GetFaultState(HANDLE KeyHandle, WORD NodeId, BOOL* pIsInFault, DWORD* pErrorCode);
//ErrorHandling
ErrorHandling_DllExport BOOL __stdcall VCS_GetNbOfDeviceError(HANDLE KeyHandle, WORD NodeId, BYTE *pNbDeviceError, DWORD *pErrorCode);
ErrorHandling_DllExport BOOL __stdcall VCS_GetDeviceErrorCode(HANDLE KeyHandle, WORD NodeId, BYTE DeviceErrorNumber, DWORD *pDeviceErrorCode, DWORD *pErrorCode);
//Motion Info
MotionInfo_DllExport BOOL __stdcall VCS_GetMovementState(HANDLE KeyHandle, WORD NodeId, BOOL* pTargetReached, DWORD* pErrorCode);
MotionInfo_DllExport BOOL __stdcall VCS_GetPositionIs(HANDLE KeyHandle, WORD NodeId, long* pPositionIs, DWORD* pErrorCode);
MotionInfo_DllExport BOOL __stdcall VCS_GetVelocityIs(HANDLE KeyHandle, WORD NodeId, long* pVelocityIs, DWORD* pErrorCode);
MotionInfo_DllExport BOOL __stdcall VCS_GetVelocityIsAveraged(HANDLE KeyHandle, WORD NodeId, long* pVelocityIsAveraged, DWORD* pErrorCode);
MotionInfo_DllExport BOOL __stdcall VCS_GetCurrentIs(HANDLE KeyHandle, WORD NodeId, short* pCurrentIs, DWORD* pErrorCode);
MotionInfo_DllExport BOOL __stdcall VCS_GetCurrentIsAveraged(HANDLE KeyHandle, WORD NodeId, short* pCurrentIsAveraged, DWORD* pErrorCode);
MotionInfo_DllExport BOOL __stdcall VCS_WaitForTargetReached(HANDLE KeyHandle, WORD NodeId, DWORD Timeout, DWORD* pErrorCode);
//Profile Position Mode
ProfilePositionMode_DllExport BOOL __stdcall VCS_ActivateProfilePositionMode(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
ProfilePositionMode_DllExport BOOL __stdcall VCS_SetPositionProfile(HANDLE KeyHandle, WORD NodeId, DWORD ProfileVelocity, DWORD ProfileAcceleration, DWORD ProfileDeceleration, DWORD* pErrorCode);
ProfilePositionMode_DllExport BOOL __stdcall VCS_GetPositionProfile(HANDLE KeyHandle, WORD NodeId, DWORD* pProfileVelocity, DWORD* pProfileAcceleration, DWORD* pProfileDeceleration, DWORD* pErrorCode);
ProfilePositionMode_DllExport BOOL __stdcall VCS_MoveToPosition(HANDLE KeyHandle, WORD NodeId, long TargetPosition, BOOL Absolute, BOOL Immediately, DWORD* pErrorCode);
ProfilePositionMode_DllExport BOOL __stdcall VCS_GetTargetPosition(HANDLE KeyHandle, WORD NodeId, long* pTargetPosition, DWORD* pErrorCode);
ProfilePositionMode_DllExport BOOL __stdcall VCS_HaltPositionMovement(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
//Advanced Functions
ProfilePositionMode_DllExport BOOL __stdcall VCS_EnablePositionWindow(HANDLE KeyHandle, WORD NodeId, DWORD PositionWindow, WORD PositionWindowTime, DWORD* pErrorCode);
ProfilePositionMode_DllExport BOOL __stdcall VCS_DisablePositionWindow(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
//Profile Velocity Mode
ProfileVelocityMode_DllExport BOOL __stdcall VCS_ActivateProfileVelocityMode(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
ProfileVelocityMode_DllExport BOOL __stdcall VCS_SetVelocityProfile(HANDLE KeyHandle, WORD NodeId, DWORD ProfileAcceleration, DWORD ProfileDeceleration, DWORD* pErrorCode);
ProfileVelocityMode_DllExport BOOL __stdcall VCS_GetVelocityProfile(HANDLE KeyHandle, WORD NodeId, DWORD* pProfileAcceleration, DWORD* pProfileDeceleration, DWORD* pErrorCode);
ProfileVelocityMode_DllExport BOOL __stdcall VCS_MoveWithVelocity(HANDLE KeyHandle, WORD NodeId, long TargetVelocity, DWORD* pErrorCode);
ProfileVelocityMode_DllExport BOOL __stdcall VCS_GetTargetVelocity(HANDLE KeyHandle, WORD NodeId, long* pTargetVelocity, DWORD* pErrorCode);
ProfileVelocityMode_DllExport BOOL __stdcall VCS_HaltVelocityMovement(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
//Advanced Functions
ProfileVelocityMode_DllExport BOOL __stdcall VCS_EnableVelocityWindow(HANDLE KeyHandle, WORD NodeId, DWORD VelocityWindow, WORD VelocityWindowTime, DWORD* pErrorCode);
ProfileVelocityMode_DllExport BOOL __stdcall VCS_DisableVelocityWindow(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
//Homing Mode
HomingMode_DllExport BOOL __stdcall VCS_ActivateHomingMode(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
HomingMode_DllExport BOOL __stdcall VCS_SetHomingParameter(HANDLE KeyHandle, WORD NodeId, DWORD HomingAcceleration, DWORD SpeedSwitch, DWORD SpeedIndex, long HomeOffset, WORD CurrentTreshold, long HomePosition, DWORD* pErrorCode);
HomingMode_DllExport BOOL __stdcall VCS_GetHomingParameter(HANDLE KeyHandle, WORD NodeId, DWORD* pHomingAcceleration, DWORD* pSpeedSwitch, DWORD* pSpeedIndex, long* pHomeOffset, WORD* pCurrentTreshold, long* pHomePosition, DWORD* pErrorCode);
HomingMode_DllExport BOOL __stdcall VCS_FindHome(HANDLE KeyHandle, WORD NodeId, __int8 HomingMethod, DWORD* pErrorCode);
HomingMode_DllExport BOOL __stdcall VCS_StopHoming(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
HomingMode_DllExport BOOL __stdcall VCS_DefinePosition(HANDLE KeyHandle, WORD NodeId, long HomePosition, DWORD* pErrorCode);
HomingMode_DllExport BOOL __stdcall VCS_WaitForHomingAttained(HANDLE KeyHandle, WORD NodeId, DWORD Timeout, DWORD* pErrorCode);
HomingMode_DllExport BOOL __stdcall VCS_GetHomingState(HANDLE KeyHandle, WORD NodeId, BOOL* pHomingAttained, BOOL* pHomingError, DWORD* pErrorCode);
//Interpolated Position Mode
InterpolatedPositionMode_DllExport BOOL __stdcall VCS_ActivateInterpolatedPositionMode(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
InterpolatedPositionMode_DllExport BOOL __stdcall VCS_SetIpmBufferParameter(HANDLE KeyHandle, WORD NodeId, WORD UnderflowWarningLimit, WORD OverflowWarningLimit, DWORD* pErrorCode);
InterpolatedPositionMode_DllExport BOOL __stdcall VCS_GetIpmBufferParameter(HANDLE KeyHandle, WORD NodeId, WORD* pUnderflowWarningLimit, WORD* pOverflowWarningLimit, DWORD* pMaxBufferSize, DWORD* pErrorCode);
InterpolatedPositionMode_DllExport BOOL __stdcall VCS_ClearIpmBuffer(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
InterpolatedPositionMode_DllExport BOOL __stdcall VCS_GetFreeIpmBufferSize(HANDLE KeyHandle, WORD NodeId, DWORD* pBufferSize, DWORD* pErrorCode);
InterpolatedPositionMode_DllExport BOOL __stdcall VCS_AddPvtValueToIpmBuffer(HANDLE KeyHandle, WORD NodeId, long Position, long Velocity, BYTE Time, DWORD* pErrorCode);
InterpolatedPositionMode_DllExport BOOL __stdcall VCS_StartIpmTrajectory(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
InterpolatedPositionMode_DllExport BOOL __stdcall VCS_StopIpmTrajectory(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
InterpolatedPositionMode_DllExport BOOL __stdcall VCS_GetIpmStatus(HANDLE KeyHandle, WORD NodeId, BOOL* pTrajectoryRunning, BOOL* pIsUnderflowWarning, BOOL* pIsOverflowWarning, BOOL* pIsVelocityWarning, BOOL* pIsAccelerationWarning, BOOL* pIsUnderflowError, BOOL* pIsOverflowError, BOOL* pIsVelocityError, BOOL* pIsAccelerationError, DWORD* pErrorCode);
//Position Mode
PositionMode_DllExport BOOL __stdcall VCS_ActivatePositionMode(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
PositionMode_DllExport BOOL __stdcall VCS_SetPositionMust(HANDLE KeyHandle, WORD NodeId, long PositionMust, DWORD* pErrorCode);
PositionMode_DllExport BOOL __stdcall VCS_GetPositionMust(HANDLE KeyHandle, WORD NodeId, long* pPositionMust, DWORD* pErrorCode);
//Advanced Functions
PositionMode_DllExport BOOL __stdcall VCS_ActivateAnalogPositionSetpoint(HANDLE KeyHandle, WORD NodeId, WORD AnalogInputNumber, float Scaling, long Offset, DWORD* pErrorCode);
PositionMode_DllExport BOOL __stdcall VCS_DeactivateAnalogPositionSetpoint(HANDLE KeyHandle, WORD NodeId, WORD AnalogInputNumber, DWORD* pErrorCode);
PositionMode_DllExport BOOL __stdcall VCS_EnableAnalogPositionSetpoint(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
PositionMode_DllExport BOOL __stdcall VCS_DisableAnalogPositionSetpoint(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
//Velocity Mode
VelocityMode_DllExport BOOL __stdcall VCS_ActivateVelocityMode(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
VelocityMode_DllExport BOOL __stdcall VCS_SetVelocityMust(HANDLE KeyHandle, WORD NodeId, long VelocityMust, DWORD* pErrorCode);
VelocityMode_DllExport BOOL __stdcall VCS_GetVelocityMust(HANDLE KeyHandle, WORD NodeId, long* pVelocityMust, DWORD* pErrorCode);
//Advanced Functions
VelocityMode_DllExport BOOL __stdcall VCS_ActivateAnalogVelocitySetpoint(HANDLE KeyHandle, WORD NodeId, WORD AnalogInputNumber, float Scaling, long Offset, DWORD* pErrorCode);
VelocityMode_DllExport BOOL __stdcall VCS_DeactivateAnalogVelocitySetpoint(HANDLE KeyHandle, WORD NodeId, WORD AnalogInputNumber, DWORD* pErrorCode);
VelocityMode_DllExport BOOL __stdcall VCS_EnableAnalogVelocitySetpoint(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
VelocityMode_DllExport BOOL __stdcall VCS_DisableAnalogVelocitySetpoint(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
//Current Mode
CurrentMode_DllExport BOOL __stdcall VCS_ActivateCurrentMode(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
CurrentMode_DllExport BOOL __stdcall VCS_SetCurrentMust(HANDLE KeyHandle, WORD NodeId, short CurrentMust, DWORD* pErrorCode);
CurrentMode_DllExport BOOL __stdcall VCS_GetCurrentMust(HANDLE KeyHandle, WORD NodeId, short* pCurrentMust, DWORD* pErrorCode);
//Advanced Functions
CurrentMode_DllExport BOOL __stdcall VCS_ActivateAnalogCurrentSetpoint(HANDLE KeyHandle, WORD NodeId, WORD AnalogInputNumber, float Scaling, short Offset, DWORD* pErrorCode);
CurrentMode_DllExport BOOL __stdcall VCS_DeactivateAnalogCurrentSetpoint(HANDLE KeyHandle, WORD NodeId, WORD AnalogInputNumber, DWORD* pErrorCode);
CurrentMode_DllExport BOOL __stdcall VCS_EnableAnalogCurrentSetpoint(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
CurrentMode_DllExport BOOL __stdcall VCS_DisableAnalogCurrentSetpoint(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
//MasterEncoder Mode
MasterEncoderMode_DllExport BOOL __stdcall VCS_ActivateMasterEncoderMode(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
MasterEncoderMode_DllExport BOOL __stdcall VCS_SetMasterEncoderParameter(HANDLE KeyHandle, WORD NodeId, WORD ScalingNumerator, WORD ScalingDenominator, BYTE Polarity, DWORD MaxVelocity, DWORD MaxAcceleration, DWORD* pErrorCode);
MasterEncoderMode_DllExport BOOL __stdcall VCS_GetMasterEncoderParameter(HANDLE KeyHandle, WORD NodeId, WORD* pScalingNumerator, WORD* pScalingDenominator, BYTE* pPolarity, DWORD* pMaxVelocity, DWORD* pMaxAcceleration, DWORD* pErrorCode);
//StepDirection Mode
StepDirectionMode_DllExport BOOL __stdcall VCS_ActivateStepDirectionMode(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
StepDirectionMode_DllExport BOOL __stdcall VCS_SetStepDirectionParameter(HANDLE KeyHandle, WORD NodeId, WORD ScalingNumerator, WORD ScalingDenominator, BYTE Polarity, DWORD MaxVelocity, DWORD MaxAcceleration, DWORD* pErrorCode);
StepDirectionMode_DllExport BOOL __stdcall VCS_GetStepDirectionParameter(HANDLE KeyHandle, WORD NodeId, WORD* pScalingNumerator, WORD* pScalingDenominator, BYTE* pPolarity, DWORD* pMaxVelocity, DWORD* pMaxAcceleration, DWORD* pErrorCode);
//Inputs Outputs
//General
InputsOutputs_DllExport BOOL __stdcall VCS_GetAllDigitalInputs(HANDLE KeyHandle, WORD NodeId, WORD* pInputs, DWORD* pErrorCode);
InputsOutputs_DllExport BOOL __stdcall VCS_GetAllDigitalOutputs(HANDLE KeyHandle, WORD NodeId, WORD* pOutputs, DWORD* pErrorCode);
InputsOutputs_DllExport BOOL __stdcall VCS_SetAllDigitalOutputs(HANDLE KeyHandle, WORD NodeId, WORD Outputs, DWORD* pErrorCode);
InputsOutputs_DllExport BOOL __stdcall VCS_GetAnalogInput(HANDLE KeyHandle, WORD NodeId, WORD InputNumber, WORD* pAnalogValue, DWORD* pErrorCode);
InputsOutputs_DllExport BOOL __stdcall VCS_SetAnalogOutput(HANDLE KeyHandle, WORD NodeId, WORD OutputNumber, WORD AnalogValue, DWORD* pErrorCode);
//Position Compare
InputsOutputs_DllExport BOOL __stdcall VCS_SetPositionCompareParameter(HANDLE KeyHandle, WORD NodeId, BYTE OperationalMode, BYTE IntervalMode, BYTE DirectionDependency, WORD IntervalWidth, WORD IntervalRepetitions, WORD PulseWidth, DWORD* pErrorCode);
InputsOutputs_DllExport BOOL __stdcall VCS_GetPositionCompareParameter(HANDLE KeyHandle, WORD NodeId, BYTE* pOperationalMode, BYTE* pIntervalMode, BYTE* pDirectionDependency, WORD* pIntervalWidth, WORD* pIntervalRepetitions, WORD* pPulseWidth, DWORD* pErrorCode);
InputsOutputs_DllExport BOOL __stdcall VCS_ActivatePositionCompare(HANDLE KeyHandle, WORD NodeId, WORD DigitalOutputNumber, BOOL Polarity, DWORD* pErrorCode);
InputsOutputs_DllExport BOOL __stdcall VCS_DeactivatePositionCompare(HANDLE KeyHandle, WORD NodeId, WORD DigitalOutputNumber, DWORD* pErrorCode);
InputsOutputs_DllExport BOOL __stdcall VCS_EnablePositionCompare(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
InputsOutputs_DllExport BOOL __stdcall VCS_DisablePositionCompare(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
InputsOutputs_DllExport BOOL __stdcall VCS_SetPositionCompareReferencePosition(HANDLE KeyHandle, WORD NodeId, long ReferencePosition, DWORD* pErrorCode);
//Position Marker
InputsOutputs_DllExport BOOL __stdcall VCS_SetPositionMarkerParameter(HANDLE KeyHandle, WORD NodeId, BYTE PositionMarkerEdgeType, BYTE PositionMarkerMode, DWORD* pErrorCode);
InputsOutputs_DllExport BOOL __stdcall VCS_GetPositionMarkerParameter(HANDLE KeyHandle, WORD NodeId, BYTE* pPositionMarkerEdgeType, BYTE* pPositionMarkerMode, DWORD* pErrorCode);
InputsOutputs_DllExport BOOL __stdcall VCS_ActivatePositionMarker(HANDLE KeyHandle, WORD NodeId, WORD DigitalInputNumber, BOOL Polarity, DWORD* pErrorCode);
InputsOutputs_DllExport BOOL __stdcall VCS_DeactivatePositionMarker(HANDLE KeyHandle, WORD NodeId, WORD DigitalInputNumber, DWORD* pErrorCode);
InputsOutputs_DllExport BOOL __stdcall VCS_ReadPositionMarkerCounter(HANDLE KeyHandle, WORD NodeId, WORD* pCount, DWORD* pErrorCode);
InputsOutputs_DllExport BOOL __stdcall VCS_ReadPositionMarkerCapturedPosition(HANDLE KeyHandle, WORD NodeId, WORD CounterIndex, long* pCapturedPosition, DWORD* pErrorCode);
InputsOutputs_DllExport BOOL __stdcall VCS_ResetPositionMarkerCounter(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
/*************************************************************************************************************************************
* DATA RECORDING FUNCTIONS
*************************************************************************************************************************************/
//DataRecorder Setup
DataRecording_DllExport BOOL __stdcall VCS_SetRecorderParameter(HANDLE KeyHandle, WORD NodeId, WORD SamplingPeriod, WORD NbOfPrecedingSamples, DWORD* pErrorCode);
DataRecording_DllExport BOOL __stdcall VCS_GetRecorderParameter(HANDLE KeyHandle, WORD NodeId, WORD* pSamplingPeriod, WORD* pNbOfPrecedingSamples, DWORD* pErrorCode);
DataRecording_DllExport BOOL __stdcall VCS_EnableTrigger(HANDLE KeyHandle, WORD NodeId, BYTE TriggerType, DWORD* pErrorCode);
DataRecording_DllExport BOOL __stdcall VCS_DisableAllTriggers(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
DataRecording_DllExport BOOL __stdcall VCS_ActivateChannel(HANDLE KeyHandle, WORD NodeId, BYTE ChannelNumber, WORD ObjectIndex, BYTE ObjectSubIndex, BYTE ObjectSize, DWORD* pErrorCode);
DataRecording_DllExport BOOL __stdcall VCS_DeactivateAllChannels(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
//DataRecorder Status
DataRecording_DllExport BOOL __stdcall VCS_StartRecorder(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
DataRecording_DllExport BOOL __stdcall VCS_StopRecorder(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
DataRecording_DllExport BOOL __stdcall VCS_ForceTrigger(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
DataRecording_DllExport BOOL __stdcall VCS_IsRecorderRunning(HANDLE KeyHandle, WORD NodeId, BOOL* pRunning, DWORD* pErrorCode);
DataRecording_DllExport BOOL __stdcall VCS_IsRecorderTriggered(HANDLE KeyHandle, WORD NodeId, BOOL* pTriggered, DWORD* pErrorCode);
//DataRecorder Data
DataRecording_DllExport BOOL __stdcall VCS_ReadChannelVectorSize(HANDLE KeyHandle, WORD NodeId, DWORD* pVectorSize, DWORD* pErrorCode);
DataRecording_DllExport BOOL __stdcall VCS_ReadChannelDataVector(HANDLE KeyHandle, WORD NodeId, BYTE ChannelNumber, BYTE* pDataVector, DWORD VectorSize, DWORD* pErrorCode);
DataRecording_DllExport BOOL __stdcall VCS_ShowChannelDataDlg(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode);
DataRecording_DllExport BOOL __stdcall VCS_ExportChannelDataToFile(HANDLE KeyHandle, WORD NodeId, char* FileName, DWORD* pErrorCode);
//Advanced Functions
DataRecording_DllExport BOOL __stdcall VCS_ReadDataBuffer(HANDLE KeyHandle, WORD NodeId, BYTE* pDataBuffer, DWORD BufferSizeToRead, DWORD* pBufferSizeRead, WORD* pVectorStartOffset, WORD* pMaxNbOfSamples, WORD* pNbOfRecordedSamples, DWORD* pErrorCode);
DataRecording_DllExport BOOL __stdcall VCS_ExtractChannelDataVector(HANDLE KeyHandle, WORD NodeId, BYTE ChannelNumber, BYTE* pDataBuffer, DWORD BufferSize, BYTE* pDataVector, DWORD VectorSize, WORD VectorStartOffset, WORD MaxNbOfSamples, WORD NbOfRecordedSamples, DWORD* pErrorCode);
/*************************************************************************************************************************************
* LOW LAYER FUNCTIONS
*************************************************************************************************************************************/
//CanLayer Functions
CanLayer_DllExport BOOL __stdcall VCS_SendCANFrame(HANDLE KeyHandle, WORD CobID, WORD Length, void* pData, DWORD* pErrorCode);
CanLayer_DllExport BOOL __stdcall VCS_ReadCANFrame(HANDLE KeyHandle, WORD CobID, WORD Length, void* pData, DWORD Timeout, DWORD* pErrorCode);
CanLayer_DllExport BOOL __stdcall VCS_RequestCANFrame(HANDLE KeyHandle, WORD CobID, WORD Length, void* pData, DWORD* pErrorCode);
CanLayer_DllExport BOOL __stdcall VCS_SendNMTService(HANDLE KeyHandle, WORD NodeId, WORD CommandSpecifier, DWORD* pErrorCode);
/*************************************************************************************************************************************
* TYPE DEFINITIONS
*************************************************************************************************************************************/
//Communication
//Dialog Mode
const int DM_PROGRESS_DLG = 0;
const int DM_PROGRESS_AND_CONFIRM_DLG = 1;
const int DM_CONFIRM_DLG = 2;
const int DM_NO_DLG = 3;
//Configuration
//MotorType
const WORD MT_DC_MOTOR = 1;
const WORD MT_EC_SINUS_COMMUTATED_MOTOR = 10;
const WORD MT_EC_BLOCK_COMMUTATED_MOTOR = 11;
//SensorType
const WORD ST_UNKNOWN = 0;
const WORD ST_INC_ENCODER_3CHANNEL = 1;
const WORD ST_INC_ENCODER_2CHANNEL = 2;
const WORD ST_HALL_SENSORS = 3;
const WORD ST_SSI_ABS_ENCODER_BINARY = 4;
const WORD ST_SSI_ABS_ENCODER_GREY = 5;
//In- and outputs
//Digital input configuration
const WORD DIC_NEGATIVE_LIMIT_SWITCH = 0;
const WORD DIC_POSITIVE_LIMIT_SWITCH = 1;
const WORD DIC_HOME_SWITCH = 2;
const WORD DIC_POSITION_MARKER = 3;
const WORD DIC_DRIVE_ENABLE = 4;
const WORD DIC_QUICK_STOP = 5;
const WORD DIC_GENERAL_PURPOSE_J = 6;
const WORD DIC_GENERAL_PURPOSE_I = 7;
const WORD DIC_GENERAL_PURPOSE_H = 8;
const WORD DIC_GENERAL_PURPOSE_G = 9;
const WORD DIC_GENERAL_PURPOSE_F = 10;
const WORD DIC_GENERAL_PURPOSE_E = 11;
const WORD DIC_GENERAL_PURPOSE_D = 12;
const WORD DIC_GENERAL_PURPOSE_C = 13;
const WORD DIC_GENERAL_PURPOSE_B = 14;
const WORD DIC_GENERAL_PURPOSE_A = 15;
//Digital output configuration
const WORD DOC_READY_FAULT = 0;
const WORD DOC_POSITION_COMPARE = 1;
const WORD DOC_GENERAL_PURPOSE_H = 8;
const WORD DOC_GENERAL_PURPOSE_G = 9;
const WORD DOC_GENERAL_PURPOSE_F = 10;
const WORD DOC_GENERAL_PURPOSE_E = 11;
const WORD DOC_GENERAL_PURPOSE_D = 12;
const WORD DOC_GENERAL_PURPOSE_C = 13;
const WORD DOC_GENERAL_PURPOSE_B = 14;
const WORD DOC_GENERAL_PURPOSE_A = 15;
//Analog input configuration
const WORD AIC_ANALOG_CURRENT_SETPOINT = 0;
const WORD AIC_ANALOG_VELOCITY_SETPOINT = 1;
const WORD AIC_ANALOG_POSITION_SETPOINT = 2;
//Units
//VelocityDimension
const BYTE VD_RPM = 0xA4;
//VelocityNotation
const char VN_STANDARD = 0;
const char VN_DECI = -1;
const char VN_CENTI = -2;
const char VN_MILLI = -3;
//Operational mode
const __int8 OMD_PROFILE_POSITION_MODE = 1;
const __int8 OMD_PROFILE_VELOCITY_MODE = 3;
const __int8 OMD_HOMING_MODE = 6;
const __int8 OMD_INTERPOLATED_POSITION_MODE = 7;
const __int8 OMD_POSITION_MODE = -1;
const __int8 OMD_VELOCITY_MODE = -2;
const __int8 OMD_CURRENT_MODE = -3;
const __int8 OMD_MASTER_ENCODER_MODE = -5;
const __int8 OMD_STEP_DIRECTION_MODE = -6;
//States
const WORD ST_DISABLED = 0;
const WORD ST_ENABLED = 1;
const WORD ST_QUICKSTOP = 2;
const WORD ST_FAULT = 3;
//Homing mode
//Homing method
const __int8 HM_ACTUAL_POSITION = 35;
const __int8 HM_NEGATIVE_LIMIT_SWITCH = 17;
const __int8 HM_NEGATIVE_LIMIT_SWITCH_AND_INDEX = 1;
const __int8 HM_POSITIVE_LIMIT_SWITCH = 18;
const __int8 HM_POSITIVE_LIMIT_SWITCH_AND_INDEX = 2;
const __int8 HM_HOME_SWITCH_POSITIVE_SPEED = 23;
const __int8 HM_HOME_SWITCH_POSITIVE_SPEED_AND_INDEX = 7;
const __int8 HM_HOME_SWITCH_NEGATIVE_SPEED = 27;
const __int8 HM_HOME_SWITCH_NEGATIVE_SPEED_AND_INDEX = 11;
const __int8 HM_CURRENT_THRESHOLD_POSITIVE_SPEED = -3;
const __int8 HM_CURRENT_THRESHOLD_POSITIVE_SPEED_AND_INDEX = -1;
const __int8 HM_CURRENT_THRESHOLD_NEGATIVE_SPEED = -4;
const __int8 HM_CURRENT_THRESHOLD_NEGATIVE_SPEED_AND_INDEX = -2;
const __int8 HM_INDEX_POSITIVE_SPEED = 34;
const __int8 HM_INDEX_NEGATIVE_SPEED = 33;
//Input Output PositionMarker
//PositionMarkerEdgeType
const BYTE PET_BOTH_EDGES = 0;
const BYTE PET_RISING_EDGE = 1;
const BYTE PET_FALLING_EDGE = 2;
//PositionMarkerMode
const BYTE PM_CONTINUOUS = 0;
const BYTE PM_SINGLE = 1;
const BYTE PM_MULTIPLE = 2;
//Input Output PositionCompare
//PositionCompareOperationalMode
const BYTE PCO_SINGLE_POSITION_MODE = 0;
const BYTE PCO_POSITION_SEQUENCE_MODE = 1;
//PositionCompareIntervalMode
const BYTE PCI_NEGATIVE_DIR_TO_REFPOS = 0;
const BYTE PCI_POSITIVE_DIR_TO_REFPOS = 1;
const BYTE PCI_BOTH_DIR_TO_REFPOS = 2;
//PositionCompareDirectionDependency
const BYTE PCD_MOTOR_DIRECTION_NEGATIVE = 0;
const BYTE PCD_MOTOR_DIRECTION_POSITIVE = 1;
const BYTE PCD_MOTOR_DIRECTION_BOTH = 2;
//Data recorder
//Trigger type
const BYTE DR_MOVEMENT_START_TRIGGER = 1;
const BYTE DR_ERROR_TRIGGER = 2;
const BYTE DR_DIGITAL_INPUT_TRIGGER = 4;
const BYTE DR_MOVEMENT_END_TRIGGER = 8;
//CanLayer Functions
const WORD NCS_START_REMOTE_NODE = 1;
const WORD NCS_STOP_REMOTE_NODE = 2;
const WORD NCS_ENTER_PRE_OPERATIONAL = 128;
const WORD NCS_RESET_NODE = 129;
const WORD NCS_RESET_COMMUNICATION = 130;
#endif //EposCommandLibraryDefinitions
| 47,620 | C | 87.187037 | 357 | 0.669845 |
adegirmenci/HBL-ICEbot/epiphan/frmgrab/include/frmgrab.h | /****************************************************************************
*
* $Id: frmgrab.h 21236 2013-03-16 12:32:41Z monich $
*
* Copyright (C) 2008-2013 Epiphan Systems Inc. All rights reserved.
*
* Header file for the Epiphan frame grabber library
*
****************************************************************************/
#ifndef _EPIPHAN_FRMGRAB_H_
#define _EPIPHAN_FRMGRAB_H_ 1
#include "v2u_defs.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
typedef struct _FrmGrabber FrmGrabber;
struct sockaddr;
struct sockaddr_in;
/**
* Initialize/deinitialize frmgrab library. Both functions may be invoked
* several times, but there must be FrmGrab_Deinit call per each FrmGrab_Init.
*/
void FrmGrab_Init(void);
void FrmGrab_Deinit(void);
void FrmGrabNet_Init(void);
void FrmGrabNet_Deinit(void);
/**
* Functions specific to local frame grabbers.
*/
FrmGrabber* FrmGrabLocal_Open(void);
FrmGrabber* FrmGrabLocal_OpenSN(const char* sn);
FrmGrabber* FrmGrabLocal_OpenIndex(int i);
int FrmGrabLocal_Count(void);
int FrmGrabLocal_OpenAll(FrmGrabber* grabbers[], int maxcount);
/**
* VGA2Ethernet authentication callback. Username buffer pointer is NULL
* if username is not required. Maximum sizes of username and password
* are defined below. Non-ASCII username and passwords must be UTF-8
* encoded. Note that FG_USERNAME_SIZE and FG_PASSWORD_SIZE define
* maximum number of bytes (including NULL terminator), not characters.
* In case of UTF-8 encoding it's not the same thing.
*/
typedef V2U_BOOL (*FrmGrabAuthProc)(char* user, char* pass, void* param);
#define FG_USERNAME_SIZE 32
#define FG_PASSWORD_SIZE 64
/**
* Connection status returned by FrmGrabNet_OpenAddress2
*/
typedef enum _FrmGrabConnectStatus {
FrmGrabConnectOK, /* Connection OK, authentication not needed */
FrmGrabConnectAuthOK, /* Connection OK, authentication successful */
FrmGrabConnectError, /* Connection failed */
FrmGrabConnectAuthFail, /* Authentication failure */
FrmGrabConnectAuthCancel /* Authentication was cancelled */
} FrmGrabConnectStatus;
/**
* VGA2Ethernet specific functions. IP address is in the host byte order.
*/
FrmGrabber* FrmGrabNet_Open(void);
FrmGrabber* FrmGrabNet_OpenSN(const char* sn);
FrmGrabber* FrmGrabNet_OpenLocation(const char* location);
FrmGrabber* FrmGrabNet_OpenAddress(V2U_UINT32 ipaddr, V2U_UINT16 port);
FrmGrabber* FrmGrabNet_OpenAddress2(V2U_UINT32 ipaddr, V2U_UINT16 port,
FrmGrabAuthProc authproc, void* param, FrmGrabConnectStatus* status);
/**
* IPv6 friendly version of FrmGrabNet_OpenAddress.
*
* Available since version 3.27.7.1
*/
FrmGrabber* FrmGrabNet_OpenAddress3(const struct sockaddr* sa, V2U_UINT32 len);
/**
* FrmGrabNet_Find finds network grabbers on the subnet. Callback is
* invoked on each grabber found. Callback function is responsible for
* calling FrmGrab_Close() on each FrmGrabber that was passed in. Search
* terminates when either timeout expires or callback returns V2U_FALSE.
* FrmGrabNet_Find returns number of times is has invoked the callback.
* Timeout is measured in milliseconds. Zero timeout means that the library
* should use the default timeout. Negative timeout means to search forever.
*
* Available since version 3.27.7.1
*/
typedef V2U_BOOL (*FrmGrabFindProc)(FrmGrabber* fg, void* param);
int FrmGrabNet_Find(FrmGrabFindProc proc, void* param, int timeout);
/**
* VGA2Ethernet authentication. These functions fail (but don't crash) on
* local frame grabbers.
*/
V2U_BOOL FrmGrabNet_IsProtected(FrmGrabber* fg);
FrmGrabConnectStatus FrmGrabNet_Auth(FrmGrabber* fg, FrmGrabAuthProc authproc,
void* param);
/**
* Simple non-interactive username/password authentication. VGA2Ethernet
* grabbers normally don't use usernames for viewer authentication, you
* should pass NULL as the second parameter.
*
* Available since version 3.26.0.15
*/
FrmGrabConnectStatus FrmGrabNet_Auth2(FrmGrabber* fg, const char* user,
const char* pass);
/**
* Network statistics for a network frame grabber. These functions return
* V2U_FALSE if invoked on a local frame grabber.
*/
typedef struct _FrmGrabNetStat {
V2U_UINT64 bytesSent; /* Total bytes sent over the network */
V2U_UINT64 bytesReceived; /* Total bytes received from the network */
} FrmGrabNetStat;
V2U_BOOL FrmGrabNet_GetStat(FrmGrabber* fg, FrmGrabNetStat* netstat);
V2U_BOOL FrmGrabNet_GetRemoteAddr(FrmGrabber* fg, struct sockaddr_in* addr);
/**
* IPv6 friendly version of FrmGrabNet_GetRemoteAddr.
*
* Available since version 3.27.7.1
*/
V2U_UINT32 FrmGrabNet_GetRemoteAddr2(FrmGrabber* fg, struct sockaddr* addr,
V2U_UINT32 len);
/* Other network-specific functions */
V2U_BOOL FrmGrabNet_IsAlive(FrmGrabber* fg);
V2U_BOOL FrmGrabNet_SetAutoReconnect(FrmGrabber* fg, V2U_BOOL enable);
/** Generic functions that work with all Frame Grabbers */
/**
* Open frame grabber. The URL-like location parameter can be one of the
* following:
*
* local:[SERIAL]
*
* Opens a local frame grabber. Optionally, the serial number can be
* specified.
*
* net:[ADDRESS[:PORT]]
*
* Opens a network frame grabber at the specified address/port. If no
* address is specified, opens a random network frame grabber.
*
* sn:SERIAL
*
* Opens a local or network frame grabber with the specified serial number.
* Checks the local frame grabbers first then goes to the network.
*
* id:INDEX
*
* Opens a local frame grabber with the specified index.
*/
FrmGrabber* FrmGrab_Open(const char* location);
/**
* Duplicates handle to the frame grabber. Returns a new independent
* FrmGrabber instance pointing to the same piece of hardware.
*/
FrmGrabber* FrmGrab_Dup(FrmGrabber* fg);
/**
* Checks whether two FrmGrabber instances point to the same physical grabber.
*/
V2U_BOOL FrmGrab_Equal(FrmGrabber* fg1, FrmGrabber* fg2);
/**
* Returns a hash code value for this FrmGrabber.
* If two grabbers are equal according to FrmGrab_Equal() function (i.e.
* they point to the same physical grabber), then calling FrmGrab_Hash()
* function on each of the two grabbers is guaranteed to produce the same
* integer result. Note that opposite is not true - two unequal grabbers
* may have the same hash, although it's a fairly rare case.
*/
V2U_UINT32 FrmGrab_Hash(FrmGrabber* fg);
/**
* Returns frame grabber's serial number.
*/
const char* FrmGrab_GetSN(FrmGrabber* fg);
/**
* Grabber's id uniquely identifies the grabber. For those boards that have
* one on-board grabber it's the same as the board's serial number. For those
* boards that have more than one grabber (e.g. DVI2PCIe) it's different
* for each grabber and looks like SSSSSSSS.X where SSSSSSSS is the board's
* serial number and X is a string identifying the particular grabber.
*/
const char* FrmGrab_GetId(FrmGrabber* fg);
/**
* Returns the unique product id. Includes product type bits OR'ed with
* type-specific product id.
*/
int FrmGrab_GetProductId(FrmGrabber* fg);
#define PRODUCT_ID_MASK 0x0000ffff
#define PRODUCT_TYPE_MASK 0x00ff0000
#define PRODUCT_TYPE_USB 0x00010000 /* Local USB grabber */
#define PRODUCT_TYPE_NET 0x00020000 /* Network grabber */
#define PRODUCT_TYPE_NETAPP 0x00030000 /* Network appliance, not a grabber */
#define PRODUCT_TYPE_FILE 0x00040000 /* Reserved */
#define PRODUCT_TYPE_PCI 0x00050000 /* Local PCI grabber */
#define PRODUCT_TYPE_VPFE 0x00060000 /* TI davinci video input bus */
#define FrmGrab_IsNetGrabberId(id) \
(((id) & PRODUCT_TYPE_MASK) == PRODUCT_TYPE_NET)
#define FrmGrab_IsUsbGrabberId(id) \
(((id) & PRODUCT_TYPE_MASK) == PRODUCT_TYPE_USB)
#define FrmGrab_IsPciGrabberId(id) \
(((id) & PRODUCT_TYPE_MASK) == PRODUCT_TYPE_PCI)
#define FrmGrab_IsLocalGrabberId(id) \
(FrmGrab_IsUsbGrabberId(id) || \
FrmGrab_IsPciGrabberId(id) || \
((id) & PRODUCT_TYPE_MASK) == PRODUCT_TYPE_FILE || \
((id) & PRODUCT_TYPE_MASK) == PRODUCT_TYPE_VPFE)
#define FrmGrab_IsNetworkDeviceId(id) \
(((id) & PRODUCT_TYPE_MASK) == PRODUCT_TYPE_NET || \
((id) & PRODUCT_TYPE_MASK) == PRODUCT_TYPE_NETAPP)
#define FrmGrab_IsNetGrabber(fg) \
FrmGrab_IsNetGrabberId(FrmGrab_GetProductId(fg))
#define FrmGrab_IsUsbGrabber(fg) \
FrmGrab_IsUsbGrabberId(FrmGrab_GetProductId(fg))
#define FrmGrab_IsPciGrabber(fg) \
FrmGrab_IsPciGrabberId(FrmGrab_GetProductId(fg))
#define FrmGrab_IsLocalGrabber(fg) \
FrmGrab_IsLocalGrabberId(FrmGrab_GetProductId(fg))
#define FrmGrab_IsNetworkDevice(fg) \
FrmGrab_IsNetworkDeviceId(FrmGrab_GetProductId(fg))
/**
* Returns the product description ("VGA2USB", "VGA2Ethernet", etc)
*/
const char* FrmGrab_GetProductName(FrmGrabber* fg);
/**
* Returns a string that describes the location of the grabber ("USB,
* "192.168.0.122", etc)
*/
const char* FrmGrab_GetLocation(FrmGrabber* fg);
/**
* Returns device capabilities (V2U_CAPS_* flags defined in v2u_defs.h).
* Returns zero if an error occurs.
*/
V2U_UINT32 FrmGrab_GetCaps(FrmGrabber* fg);
/**
* Returns the last known video mode, detecting is if necessary.
* Unlike FrmGrab_DetectVideoMode, this function doesn't force the
* video mode detection, but most of the time it's accurate enough.
* Note that video mode detection is a relatively expensive operation.
*/
void FrmGrab_GetVideoMode(FrmGrabber* fg, V2U_VideoMode* vm);
/**
* Detects current video mode. If no signal is detected, the output
* V2U_VideoMode structure is zeroed.
*/
V2U_BOOL FrmGrab_DetectVideoMode(FrmGrabber* fg, V2U_VideoMode* vm);
/**
* Queries current VGA capture parameters.
*/
V2U_BOOL FrmGrab_GetGrabParams(FrmGrabber* fg, V2U_GrabParameters* gp);
/**
* Queries current VGA capture parameters and adjustment ranges in one shot.
* More efficient for network grabbers. FrmGrab_GetGrabParams2(fg,gp,NULL)
* is equivalent to FrmGrab_GetGrabParams(fg,gp)
*/
V2U_BOOL FrmGrab_GetGrabParams2(FrmGrabber* fg, V2U_GrabParameters* gp,
V2UAdjRange* range);
/**
* Sets VGA capture parameters.
*/
V2U_BOOL FrmGrab_SetGrabParams(FrmGrabber* fg, const V2U_GrabParameters* gp);
/**
* Queries the device property.
*/
V2U_BOOL FrmGrab_GetProperty(FrmGrabber* fg, V2U_Property* prop);
/**
* Sets the device property.
*/
V2U_BOOL FrmGrab_SetProperty(FrmGrabber* fg, const V2U_Property* prop);
/**
* VGA mode table can be queried or modified with a bunch of GetProperty
* or SetProperty calls, but getting and settinng the entire VGA mode table
* with one call is more efficient, especially for network frame grabbers.
* Number of custom modes doesn't exceed V2U_CUSTOM_VIDEOMODE_COUNT. The
* whole FrmGrabVgaModes structure returned by FrmGrab_GetVGAModes is
* allocated as a single memory block. The caller is responsible for
* deallocating it with with a single FrmGrab_Free call.
*/
typedef struct _FrmGrabVgaModes {
V2UVideoModeDescr* customModes; /* Custom modes */
V2UVideoModeDescr* stdModes; /* Standard modes */
int numCustomModes; /* Number of custom modes */
int numStdModes; /* Number of standard modes */
} FrmGrabVgaModes;
/**
* Gets VGA mode table. The returned pointer must be deallocated
* with FrmGrab_Free()
*/
FrmGrabVgaModes* FrmGrab_GetVGAModes(FrmGrabber* fg);
/**
* Sets VGA mode table. Custom modes can be modified, standard modes can only
* enabled or disabled (VIDEOMODE_TYPE_ENABLED flag).
*/
V2U_BOOL FrmGrab_SetVGAModes(FrmGrabber* fg, const FrmGrabVgaModes* vgaModes);
/**
* Sends PS/2 events to the frame grabber (KVM capable products only).
*/
V2U_BOOL FrmGrab_SendPS2(FrmGrabber* fg, const V2U_SendPS2* ps2);
/**
* Sets intended frame rate limit (average number of FrmGrab_Frame calls per
* second). The frame grabber may use this hint to reduce resource usage,
* especially in low fps case.
*/
V2U_BOOL FrmGrab_SetMaxFps(FrmGrabber* fg, double maxFps);
/**
* Signals the grabber to prepare for capturing frames with maximum
* frame rate. While it currently doesn't matter for local grabbers, it's
* really important for network grabbers (it turns streaming on, otherwise
* FrmGrab_Frame will have to work on request/response basis, which is
* much slower). Returns V2U_TRUE if streaming is supported, or V2U_FALSE
* if this call has no effect.
*/
V2U_BOOL FrmGrab_Start(FrmGrabber* fg);
/**
* Signals the grabber to stop capturing frames with maximum frame rate.
*/
void FrmGrab_Stop(FrmGrabber* fg);
/**
* Grabs one frame. The caller doesn't have to call FrmGrab_Start first,
* but it's recommended in order to get maximum frame rate.
*
* The second parameter is the capture format, i.e. one of
* V2U_GRABFRAME_FORMAT_* constants defined in v2u_defs.h
*
* The last parameter is a pointer to the requested crop rectangle. Pass
* NULL if you need the whole frame.
*
* All frames returned by this function must be eventually released with
* FrmGrab_Release which makes them eligible for deallocation or recycling.
* All frames captured via particular FrmGrabber handle must be released
* before you close the handle with FrmGrab_Close. If FrmGrab_Release is
* called after closing FrmGrabber handle, the behavior of frmgrab library
* is undefined. Most likely, it would result in either crash or memory leak.
*/
V2U_GrabFrame2* FrmGrab_Frame(FrmGrabber* fg, V2U_UINT32 format,
const V2URect* crop);
/**
* Deallocates or recycles the frame previously returned by FrmGrab_Frame.
* FrmGrabber handle must match the one passed to FrmGrab_Frame.
*
* All frames captured via particular FrmGrabber handle must be released
* before you close the handle with FrmGrab_Close.
*/
void FrmGrab_Release(FrmGrabber* fg, V2U_GrabFrame2* frame);
/**
* Closes the frame grabber and invalidates the handle.
*
* All frames captured via particular FrmGrabber handle must be released
* before you close the handle with FrmGrab_Close.
*/
void FrmGrab_Close(FrmGrabber* fg);
/**
* Deallocates memory allocated by frmgrab.
*/
void FrmGrab_Free(void* ptr);
/** Memory allocation callbacks */
typedef void* (*FrmGrabMemAlloc)(void* param, V2U_UINT32 len);
typedef void (*FrmGrabMemFree)(void* param, void* ptr);
typedef struct _FrmGrabMemCB {
FrmGrabMemAlloc alloc;
FrmGrabMemFree free;
} FrmGrabMemCB;
/**
* Sets functions for allocating and deallocating memory for the frame
* buffers. NOTE that these callbacks are ONLY invoked to allocate memory
* for the frame buffer. For all other allocations, frmgrab library uses
* its own allocator. The allocator and deallocator callbacks may be invoked
* in arbitrary thread context, not necessarily the thread that invokes
* FrmGrab_Frame. The contents of FrmGrabMemCB is copied to internal storage.
*/
void FrmGrab_SetAlloc(FrmGrabber* fg, const FrmGrabMemCB* memcb, void* param);
#ifdef __cplusplus
} /* end of extern "C" */
#endif /* __cplusplus */
#endif /* _EPIPHAN_FRMGRAB_H_ */
/*
* Local Variables:
* c-basic-offset: 4
* indent-tabs-mode: nil
* End:
*/
| 15,048 | C | 33.437071 | 79 | 0.730728 |
adegirmenci/HBL-ICEbot/epiphan/codec/avi_writer/avi_writer.c | /****************************************************************************
*
* $Id: avi_writer.c 10003 2010-06-10 11:28:31Z monich $
*
* Copyright (C) 2007-2010 Epiphan Systems Inc. All rights reserved.
*
* Platform-independent library for creating AVI files.
*
****************************************************************************/
#include "avi_writer.h"
#include <stdlib.h>
#include <memory.h>
#include <assert.h>
#define AVIF_HASINDEX 0x00000010
#define AVIF_MUSTUSEINDEX 0x00000020
#define AVIF_ISINTERLEAVED 0x00000100
#define AVIF_TRUSTCKTYPE 0x00000800
#define AVIF_WASCAPTUREFILE 0x00010000 /* AW will set this flag by default */
#define AVIF_COPYRIGHTED 0x00020000
#define AVIH_CHUNK_OFFSET 32
#define AVIH_CHUNK_SIZE 56
#define AVIH_CHUNK_STREAM_COUNT_OFFSET 24
#define STRH_CHUNK_SIZE 56
#define STRF_VIDEO_CHUNK_SIZE 40
#define AW_FALSE 0
#define AW_TRUE 1
typedef int AW_BOOL;
typedef unsigned char AW_BYTE;
typedef unsigned int AW_UINT32;
/* rgb121 */
static const AW_BYTE aw_palette_4bpp[16*4] = {
0x00,0x00,0x00,0, 0x00,0x00,0xff,0,
0x00,0x55,0x00,0, 0x00,0x55,0xff,0,
0x00,0xaa,0x00,0, 0x00,0xaa,0xff,0,
0x00,0xff,0x00,0, 0x00,0xff,0xff,0,
0xff,0x00,0x00,0, 0xff,0x00,0xff,0,
0xff,0x55,0x00,0, 0xff,0x55,0xff,0,
0xff,0xaa,0x00,0, 0xff,0xaa,0xff,0,
0xff,0xff,0x00,0, 0xff,0xff,0xff,0,
};
/* rgb233 */
static const AW_BYTE aw_palette_8bpp[256*4] = {
0x00,0x00,0x00,0, 0x24,0x00,0x00,0, 0x49,0x00,0x00,0, 0x6D,0x00,0x00,0,
0x92,0x00,0x00,0, 0xB6,0x00,0x00,0, 0xDB,0x00,0x00,0, 0xFF,0x00,0x00,0,
0x00,0x24,0x00,0, 0x24,0x24,0x00,0, 0x49,0x24,0x00,0, 0x6D,0x24,0x00,0,
0x92,0x24,0x00,0, 0xB6,0x24,0x00,0, 0xDB,0x24,0x00,0, 0xFF,0x24,0x00,0,
0x00,0x49,0x00,0, 0x24,0x49,0x00,0, 0x49,0x49,0x00,0, 0x6D,0x49,0x00,0,
0x92,0x49,0x00,0, 0xB6,0x49,0x00,0, 0xDB,0x49,0x00,0, 0xFF,0x49,0x00,0,
0x00,0x6D,0x00,0, 0x24,0x6D,0x00,0, 0x49,0x6D,0x00,0, 0x6D,0x6D,0x00,0,
0x92,0x6D,0x00,0, 0xB6,0x6D,0x00,0, 0xDB,0x6D,0x00,0, 0xFF,0x6D,0x00,0,
0x00,0x92,0x00,0, 0x24,0x92,0x00,0, 0x49,0x92,0x00,0, 0x6D,0x92,0x00,0,
0x92,0x92,0x00,0, 0xB6,0x92,0x00,0, 0xDB,0x92,0x00,0, 0xFF,0x92,0x00,0,
0x00,0xB6,0x00,0, 0x24,0xB6,0x00,0, 0x49,0xB6,0x00,0, 0x6D,0xB6,0x00,0,
0x92,0xB6,0x00,0, 0xB6,0xB6,0x00,0, 0xDB,0xB6,0x00,0, 0xFF,0xB6,0x00,0,
0x00,0xDB,0x00,0, 0x24,0xDB,0x00,0, 0x49,0xDB,0x00,0, 0x6D,0xDB,0x00,0,
0x92,0xDB,0x00,0, 0xB6,0xDB,0x00,0, 0xDB,0xDB,0x00,0, 0xFF,0xDB,0x00,0,
0x00,0xFF,0x00,0, 0x24,0xFF,0x00,0, 0x49,0xFF,0x00,0, 0x6D,0xFF,0x00,0,
0x92,0xFF,0x00,0, 0xB6,0xFF,0x00,0, 0xDB,0xFF,0x00,0, 0xFF,0xFF,0x00,0,
0x00,0x00,0x55,0, 0x24,0x00,0x55,0, 0x49,0x00,0x55,0, 0x6D,0x00,0x55,0,
0x92,0x00,0x55,0, 0xB6,0x00,0x55,0, 0xDB,0x00,0x55,0, 0xFF,0x00,0x55,0,
0x00,0x24,0x55,0, 0x24,0x24,0x55,0, 0x49,0x24,0x55,0, 0x6D,0x24,0x55,0,
0x92,0x24,0x55,0, 0xB6,0x24,0x55,0, 0xDB,0x24,0x55,0, 0xFF,0x24,0x55,0,
0x00,0x49,0x55,0, 0x24,0x49,0x55,0, 0x49,0x49,0x55,0, 0x6D,0x49,0x55,0,
0x92,0x49,0x55,0, 0xB6,0x49,0x55,0, 0xDB,0x49,0x55,0, 0xFF,0x49,0x55,0,
0x00,0x6D,0x55,0, 0x24,0x6D,0x55,0, 0x49,0x6D,0x55,0, 0x6D,0x6D,0x55,0,
0x92,0x6D,0x55,0, 0xB6,0x6D,0x55,0, 0xDB,0x6D,0x55,0, 0xFF,0x6D,0x55,0,
0x00,0x92,0x55,0, 0x24,0x92,0x55,0, 0x49,0x92,0x55,0, 0x6D,0x92,0x55,0,
0x92,0x92,0x55,0, 0xB6,0x92,0x55,0, 0xDB,0x92,0x55,0, 0xFF,0x92,0x55,0,
0x00,0xB6,0x55,0, 0x24,0xB6,0x55,0, 0x49,0xB6,0x55,0, 0x6D,0xB6,0x55,0,
0x92,0xB6,0x55,0, 0xB6,0xB6,0x55,0, 0xDB,0xB6,0x55,0, 0xFF,0xB6,0x55,0,
0x00,0xDB,0x55,0, 0x24,0xDB,0x55,0, 0x49,0xDB,0x55,0, 0x6D,0xDB,0x55,0,
0x92,0xDB,0x55,0, 0xB6,0xDB,0x55,0, 0xDB,0xDB,0x55,0, 0xFF,0xDB,0x55,0,
0x00,0xFF,0x55,0, 0x24,0xFF,0x55,0, 0x49,0xFF,0x55,0, 0x6D,0xFF,0x55,0,
0x92,0xFF,0x55,0, 0xB6,0xFF,0x55,0, 0xDB,0xFF,0x55,0, 0xFF,0xFF,0x55,0,
0x00,0x00,0xAA,0, 0x24,0x00,0xAA,0, 0x49,0x00,0xAA,0, 0x6D,0x00,0xAA,0,
0x92,0x00,0xAA,0, 0xB6,0x00,0xAA,0, 0xDB,0x00,0xAA,0, 0xFF,0x00,0xAA,0,
0x00,0x24,0xAA,0, 0x24,0x24,0xAA,0, 0x49,0x24,0xAA,0, 0x6D,0x24,0xAA,0,
0x92,0x24,0xAA,0, 0xB6,0x24,0xAA,0, 0xDB,0x24,0xAA,0, 0xFF,0x24,0xAA,0,
0x00,0x49,0xAA,0, 0x24,0x49,0xAA,0, 0x49,0x49,0xAA,0, 0x6D,0x49,0xAA,0,
0x92,0x49,0xAA,0, 0xB6,0x49,0xAA,0, 0xDB,0x49,0xAA,0, 0xFF,0x49,0xAA,0,
0x00,0x6D,0xAA,0, 0x24,0x6D,0xAA,0, 0x49,0x6D,0xAA,0, 0x6D,0x6D,0xAA,0,
0x92,0x6D,0xAA,0, 0xB6,0x6D,0xAA,0, 0xDB,0x6D,0xAA,0, 0xFF,0x6D,0xAA,0,
0x00,0x92,0xAA,0, 0x24,0x92,0xAA,0, 0x49,0x92,0xAA,0, 0x6D,0x92,0xAA,0,
0x92,0x92,0xAA,0, 0xB6,0x92,0xAA,0, 0xDB,0x92,0xAA,0, 0xFF,0x92,0xAA,0,
0x00,0xB6,0xAA,0, 0x24,0xB6,0xAA,0, 0x49,0xB6,0xAA,0, 0x6D,0xB6,0xAA,0,
0x92,0xB6,0xAA,0, 0xB6,0xB6,0xAA,0, 0xDB,0xB6,0xAA,0, 0xFF,0xB6,0xAA,0,
0x00,0xDB,0xAA,0, 0x24,0xDB,0xAA,0, 0x49,0xDB,0xAA,0, 0x6D,0xDB,0xAA,0,
0x92,0xDB,0xAA,0, 0xB6,0xDB,0xAA,0, 0xDB,0xDB,0xAA,0, 0xFF,0xDB,0xAA,0,
0x00,0xFF,0xAA,0, 0x24,0xFF,0xAA,0, 0x49,0xFF,0xAA,0, 0x6D,0xFF,0xAA,0,
0x92,0xFF,0xAA,0, 0xB6,0xFF,0xAA,0, 0xDB,0xFF,0xAA,0, 0xFF,0xFF,0xAA,0,
0x00,0x00,0xFF,0, 0x24,0x00,0xFF,0, 0x49,0x00,0xFF,0, 0x6D,0x00,0xFF,0,
0x92,0x00,0xFF,0, 0xB6,0x00,0xFF,0, 0xDB,0x00,0xFF,0, 0xFF,0x00,0xFF,0,
0x00,0x24,0xFF,0, 0x24,0x24,0xFF,0, 0x49,0x24,0xFF,0, 0x6D,0x24,0xFF,0,
0x92,0x24,0xFF,0, 0xB6,0x24,0xFF,0, 0xDB,0x24,0xFF,0, 0xFF,0x24,0xFF,0,
0x00,0x49,0xFF,0, 0x24,0x49,0xFF,0, 0x49,0x49,0xFF,0, 0x6D,0x49,0xFF,0,
0x92,0x49,0xFF,0, 0xB6,0x49,0xFF,0, 0xDB,0x49,0xFF,0, 0xFF,0x49,0xFF,0,
0x00,0x6D,0xFF,0, 0x24,0x6D,0xFF,0, 0x49,0x6D,0xFF,0, 0x6D,0x6D,0xFF,0,
0x92,0x6D,0xFF,0, 0xB6,0x6D,0xFF,0, 0xDB,0x6D,0xFF,0, 0xFF,0x6D,0xFF,0,
0x00,0x92,0xFF,0, 0x24,0x92,0xFF,0, 0x49,0x92,0xFF,0, 0x6D,0x92,0xFF,0,
0x92,0x92,0xFF,0, 0xB6,0x92,0xFF,0, 0xDB,0x92,0xFF,0, 0xFF,0x92,0xFF,0,
0x00,0xB6,0xFF,0, 0x24,0xB6,0xFF,0, 0x49,0xB6,0xFF,0, 0x6D,0xB6,0xFF,0,
0x92,0xB6,0xFF,0, 0xB6,0xB6,0xFF,0, 0xDB,0xB6,0xFF,0, 0xFF,0xB6,0xFF,0,
0x00,0xDB,0xFF,0, 0x24,0xDB,0xFF,0, 0x49,0xDB,0xFF,0, 0x6D,0xDB,0xFF,0,
0x92,0xDB,0xFF,0, 0xB6,0xDB,0xFF,0, 0xDB,0xDB,0xFF,0, 0xFF,0xDB,0xFF,0,
0x00,0xFF,0xFF,0, 0x24,0xFF,0xFF,0, 0x49,0xFF,0xFF,0, 0x6D,0xFF,0xFF,0,
0x92,0xFF,0xFF,0, 0xB6,0xFF,0xFF,0, 0xDB,0xFF,0xFF,0, 0xFF,0xFF,0xFF,0
};
static const AW_UINT32 aw_mask_bgr16[3] = {0x001F, 0x07E0, 0xF800};
static const AW_UINT32 aw_mask_rgb16[3] = {0xF800, 0x07E0, 0x001F};
static const AW_BYTE aw_mask_rgb32[3*4] = {
0,0xFF,0x00,0x00, 0,0x00,0xFF,0x00, 0,0x00,0x00,0xFF
};
#define AW_FSEEK( f,pos ) (fseek( (f),(pos),SEEK_SET ) == 0)
static AW_BOOL AW_FWRITE( AW_FHANDLE f,const void *buf,unsigned long count,unsigned long *fpos )
{
if (count) {
if( fwrite( buf,1,count,f ) == count ) {
if( fpos ) *fpos += count;
return AW_TRUE;
}
return AW_FALSE;
}
return AW_TRUE;
}
typedef enum {
AW_ST_Video,
AW_ST_Audio
} AW_StreamTypes_e;
typedef struct _STREAM_CTX {
AW_StreamTypes_e stype;
unsigned long frame_count;
unsigned long streamh_start;
unsigned char fourcc[4];
unsigned long rate;
unsigned long scale;
} STREAM_CTX;
typedef enum {
AW_StreamError,
AW_StreamsConfig,
AW_FramesAdd,
} AW_States_e;
typedef struct _AW_Idx_s {
unsigned char fourcc[4];
unsigned long flags;
unsigned long offs;
unsigned long size;
} AW_Idx_s;
/* Numbers should be power of 8 to speed up calculations */
#define AW_Idx_Plane_Size 2048
#define AW_Idx_Plane_Count 1024
typedef AW_Idx_s AW_Idx_Plane[AW_Idx_Plane_Size];
typedef AW_Idx_Plane *pAW_Idx_Plane;
const int AW_CTX_magic = 0x501E1E55;
struct __AW_CTX {
unsigned long magic;
unsigned long write_pos;
int stream_count;
STREAM_CTX streams[AW_MAX_STREAMS];
AW_FHANDLE f;
unsigned long movi_ch_start;
AW_States_e state;
unsigned long width;
unsigned long height;
pAW_Idx_Plane idx[AW_Idx_Plane_Count];
unsigned long idx_count;
};
static const unsigned char riff4cc[4] = "RIFF";
static const unsigned char AVI4cc[4] = "AVI ";
static const unsigned char LIST4cc[4] = "LIST";
static const unsigned char hdrl4cc[4] = "hdrl";
static const unsigned char avih4cc[4] = "avih";
static const unsigned char strl4cc[4] = "strl";
static const unsigned char strh4cc[4] = "strh";
static const unsigned char vids4cc[4] = "vids";
static const unsigned char auds4cc[4] = "auds";
static const unsigned char strf4cc[4] = "strf";
static const unsigned char movi4cc[4] = "movi";
static const unsigned char idx14cc[4] = "idx1";
static const unsigned char JUNK4cc[4] = "JUNK";
static const unsigned char DIB4cc[4] = "DIB ";
/* Platform indepent conversions */
static AW_BOOL AW_WriteULONG( AW_CTX *ctx,unsigned long l )
{
unsigned char c[4];
c[0] = (unsigned char)l;
c[1] = (unsigned char)((l >> 8));
c[2] = (unsigned char)((l >> 16));
c[3] = (unsigned char)((l >> 24));
return AW_FWRITE( ctx->f,&c[0],4,&ctx->write_pos );
}
static AW_BOOL AW_WriteUSHORT( AW_CTX *ctx,unsigned long s )
{
unsigned char c[2];
c[0] = (unsigned char)s;
c[1] = (unsigned char)(s >> 8);
return AW_FWRITE( ctx->f,&c[0],2,&ctx->write_pos );
}
static AW_BOOL AW_WriteFourCC( AW_CTX *ctx,const unsigned char* fourcc )
{
return AW_FWRITE( ctx->f,fourcc,4,&ctx->write_pos );
}
static AW_BOOL AW_Seek( AW_CTX *ctx,unsigned long pos )
{
if (AW_FSEEK(ctx->f, pos)) {
ctx->write_pos = pos;
return AW_TRUE;
}
return AW_FALSE;
}
static AW_RET AW_AddIdx( AW_CTX *ctx,const unsigned char *fourcc,
unsigned long flags,unsigned long offs,unsigned long size )
{
unsigned long il = ctx->idx_count % AW_Idx_Plane_Size;
unsigned long ih = ctx->idx_count / AW_Idx_Plane_Size;
AW_Idx_Plane *pl;
if( ih >= AW_Idx_Plane_Count )
return AW_ERR_INTERNAL_LIMIT;
if( !ctx->idx[ih] ) ctx->idx[ih] = malloc( sizeof( AW_Idx_Plane ));
if( !ctx->idx[ih] ) return AW_ERR_MEMORY;
pl = ctx->idx[ih];
memcpy( (*pl)[il].fourcc,fourcc,4 );
(*pl)[il].flags = flags;
(*pl)[il].offs = offs;
(*pl)[il].size = size;
ctx->idx_count++;
return AW_OK;
}
static AW_BOOL AW_Align( AW_CTX *ctx,unsigned long align_amount )
{
unsigned long write_amount = align_amount - ( ctx->write_pos % align_amount );
#define empty_buf_size 2048
static char empty_buf[empty_buf_size] = "q";
if( empty_buf[0] ) memset( empty_buf,0,empty_buf_size );
while( write_amount <= 8 ) write_amount += align_amount;
if( !AW_WriteFourCC( ctx,JUNK4cc ) ||
!AW_WriteULONG( ctx,write_amount ) ) goto err_io;
while( write_amount ) {
if( write_amount > empty_buf_size ) {
if( !AW_FWRITE( ctx->f,empty_buf,empty_buf_size,&ctx->write_pos ) ) goto err_io;
write_amount -= empty_buf_size;
} else {
if( !AW_FWRITE( ctx->f,empty_buf,write_amount,&ctx->write_pos ) ) goto err_io;
write_amount = 0;
}
}
return AW_TRUE;
err_io:
return AW_FALSE;
}
AW_RET AW_FInit( AW_CTX **ctx,AW_FHANDLE f,unsigned long width,unsigned long height )
{
AW_CTX *lctx;
if( !ctx ) return AW_ERR_PARAM;
lctx = (AW_CTX *)malloc( sizeof( AW_CTX ));
if( !lctx ) return AW_ERR_MEMORY;
memset( lctx,0,sizeof( AW_CTX ));
lctx->magic = AW_CTX_magic;
lctx->f = f;
lctx->height = height;
lctx->width = width;
if( AW_Seek( lctx,0 ) /* Just to be sure */ &&
AW_WriteFourCC( lctx,riff4cc ) &&
/* Size of full file, offset 4, fill later */
AW_WriteULONG( lctx,0 ) &&
AW_WriteFourCC( lctx,AVI4cc ) &&
AW_WriteFourCC( lctx,LIST4cc ) &&
/* Size of AVI LIST chunk, offset 16, fill later */
AW_WriteULONG( lctx,0 ) &&
AW_WriteFourCC( lctx,hdrl4cc ) &&
AW_WriteFourCC( lctx,avih4cc ) &&
/* avih chunk is always 56 bytes */
AW_WriteULONG( lctx,AVIH_CHUNK_SIZE ) ) {
#ifdef _DEBUG
unsigned long d1 = lctx->write_pos;
#endif /* _DEBUG */
/*
* typedef struct{
* DWORD dwMicroSecPerFrame;
* DWORD dwMaxBytesPerSec;
* DWORD dwPaddingGranularity;
* DWORD dwFlags;
* DWORD dwTotalFrames;
* DWORD dwInitialFrames;
* DWORD dwStreams;
* DWORD dwSuggestedBufferSize;
* DWORD dwWidth;
* DWORD dwHeight;
* DWORD dwReserved[4];
* } MainAVIHeader;
*/
/* dwMicroSecPerFrame - do not know now, let's write NTSC value */
if( AW_WriteULONG( lctx,33367 ) &&
/* dwMaxBytesPerSec - by default width * height * 3 * 30fps for NTSC */
AW_WriteULONG( lctx,width * height * 3 * 30 ) &&
/* dwPaddingGranularity */
AW_WriteULONG( lctx,0 ) &&
/* dwFlags */
AW_WriteULONG( lctx,AVIF_WASCAPTUREFILE | AVIF_HASINDEX ) &&
/* dwTotalFrames - have to be set later */
AW_WriteULONG( lctx,0 ) &&
/* dwInitialFrames */
AW_WriteULONG( lctx,0 ) &&
/* dwStreams - let's write 1 stream by default */
AW_WriteULONG( lctx,1 ) &&
/* dwSuggestedBufferSize - max unpacked frame by default */
AW_WriteULONG( lctx,width * height * 3 ) &&
/* dwWidth */
AW_WriteULONG( lctx,width ) &&
/* dwHeight */
AW_WriteULONG( lctx,height ) &&
/* dwReserved */
AW_WriteULONG( lctx,0 ) &&
AW_WriteULONG( lctx,0 ) &&
AW_WriteULONG( lctx,0 ) &&
AW_WriteULONG( lctx,0 ) ) {
#ifdef _DEBUG
assert( d1 + AVIH_CHUNK_SIZE == lctx->write_pos );
#endif /* _DEBUG */
lctx->state = AW_StreamsConfig;
*ctx = lctx;
return AW_OK;
}
}
/* I/O error */
free( lctx );
*ctx = NULL;
return AW_ERR_FILE_IO;
}
AW_RET AW_FDone( AW_CTX *ctx )
{
unsigned long q;
if( !ctx ) return AW_ERR_PARAM;
/* Let's do full AVI close if the stream is in right state
Call in other state mean that we have to do emergency clean up */
if( ctx->state == AW_FramesAdd ) {
unsigned long tmppos = 0;
unsigned long movich_size = 0;
unsigned long RIFF_size = 0;
int i = 0;
STREAM_CTX *s = NULL;
if( !AW_Align( ctx,2048 ) ) goto err_io; /* Align to CD sector size */
movich_size = ctx->write_pos - ( ctx->movi_ch_start + 8 ); /* LIST and size are not counted */
/* write idx1 chunk */
if( !AW_WriteFourCC( ctx,idx14cc ) ||
!AW_WriteULONG( ctx,16 * ctx->idx_count ) ) goto err_io;
for( q = 0; q < ctx->idx_count; q++ )
{
unsigned long il = q % AW_Idx_Plane_Size;
unsigned long ih = q / AW_Idx_Plane_Size;
AW_Idx_Plane *pl = ctx->idx[ih];
if( !pl )
goto err_io;
if( !AW_WriteFourCC( ctx,(*pl)[il].fourcc ) ||
!AW_WriteULONG( ctx,(*pl)[il].flags ) ||
!AW_WriteULONG( ctx,(*pl)[il].offs ) ||
!AW_WriteULONG( ctx,(*pl)[il].size ) ) goto err_io;
}
/* ------------------------------------------------------------*/
tmppos = ctx->write_pos;
RIFF_size = tmppos - 8;
/* RIFF size */
if( !AW_Seek( ctx,4 ) ||
!AW_WriteULONG( ctx,RIFF_size ) ||
/* movi list chunk size */
!AW_Seek( ctx,ctx->movi_ch_start + 4 ) ||
!AW_WriteULONG( ctx,movich_size ) ) goto err_io;
/* Calculated from 1st video stream */
for( i = 0; i < ctx->stream_count; i++ ) {
if( ctx->streams[i].stype == AW_ST_Video ) {
s = &ctx->streams[i];
break;
}
}
if( s ) {
/* should avoid overflow here */
unsigned long ms_per_frame = (unsigned long)( 1000000.0 * (double)s->scale / s->rate );
/* dwMicroSecPerFrame */
if( !AW_Seek( ctx,32 ) ||
!AW_WriteULONG( ctx,ms_per_frame ) ||
/* dwTotalFrames */
!AW_Seek( ctx,48 ) ||
!AW_WriteULONG( ctx,s->frame_count ) ) goto err_io;
}
for( i = 0; i < ctx->stream_count; i++ ) {
s = &ctx->streams[i];
switch( s->stype ) {
case AW_ST_Video:
case AW_ST_Audio:
/* dwTotalLength */
if( !AW_Seek( ctx,s->streamh_start + 20 + 32 ) ||
!AW_WriteULONG( ctx,s->frame_count ) ) goto err_io;
break;
default:
assert( 0 );
break;
}
}
/* Let's return file pointer to the end of file just in case */
AW_Seek( ctx,tmppos );
}
for( q = 0; q < AW_Idx_Plane_Count; q++ ) {
free( ctx->idx[q] );
}
ctx->magic = 0;
free( ctx );
return AW_OK;
err_io:
for( q = 0; q < AW_Idx_Plane_Count; q++ ) {
free( ctx->idx[q] );
}
ctx->magic = 0;
free( ctx );
return AW_ERR_FILE_IO;
}
AW_RET AW_UpdateAVIHeaderField( AW_CTX *ctx,AW_HDR_Fields fld,unsigned long value )
{
if( !ctx ) return AW_ERR_PARAM;
return AW_OK;
}
/*
* typedef struct {
* FOURCC fccType;
* FOURCC fccHandler;
* DWORD dwFlags;
* WORD wPriority;
* WORD wLanguage;
* DWORD dwInitialFrames;
* DWORD dwScale;
* DWORD dwRate; // dwRate / dwScale == samples/second
* DWORD dwStart;
* DWORD dwLength; // In units above...
* DWORD dwSuggestedBufferSize;
* DWORD dwQuality;
* DWORD dwSampleSize;
* RECT rcFrame;
* } AVIStreamHeader;
*/
static AW_BOOL AW_WriteAVIStreamHeader( AW_CTX *ctx,
const unsigned char *fccType, const unsigned char *fccHandler,
unsigned long scale, unsigned long rate,
unsigned long width, unsigned long height)
{
return
AW_WriteFourCC( ctx,LIST4cc ) &&
/* Size of strl LIST chunk, offset 4, fill later */
AW_WriteULONG( ctx,0 ) &&
AW_WriteFourCC( ctx,strl4cc ) &&
AW_WriteFourCC( ctx,strh4cc ) &&
/* strh chunk is always 56 bytes */
AW_WriteULONG( ctx,STRH_CHUNK_SIZE ) &&
/* fccType */
AW_WriteFourCC( ctx,fccType ) &&
/* fccHandler */
AW_WriteFourCC( ctx,fccHandler ) &&
/* dwFlags */
AW_WriteULONG( ctx,0 ) &&
/* wPriority */
AW_WriteUSHORT( ctx,0 ) &&
/* wLanguage */
AW_WriteUSHORT( ctx,0 ) &&
/* dwInitialFrames */
AW_WriteULONG( ctx,0 ) &&
/* dwScale */
AW_WriteULONG( ctx,scale ) &&
/* dwRate */
AW_WriteULONG( ctx,rate ) &&
/* dwStart */
AW_WriteULONG( ctx,0 ) &&
/* dwLength - have to be set later */
AW_WriteULONG( ctx,0 ) &&
/* dwSuggestedBufferSize */
AW_WriteULONG( ctx,width*height*3 ) &&
/* dwQuality */
AW_WriteULONG( ctx,0 ) &&
/* dwSampleSize */
AW_WriteULONG( ctx,0 ) &&
/* rcFrame */
AW_WriteUSHORT( ctx,0 ) &&
AW_WriteUSHORT( ctx,0 ) &&
AW_WriteUSHORT( ctx,width ) &&
AW_WriteUSHORT( ctx,height );
}
static AW_BOOL AW_FinalizeStreamHeader( AW_CTX *ctx,const STREAM_CTX *cstream )
{
unsigned long tmppos = ctx->write_pos;
unsigned long strllen = tmppos - ( cstream->streamh_start + 8 );
if( AW_Seek( ctx,cstream->streamh_start + 4 ) &&
AW_WriteULONG( ctx,strllen ) &&
AW_Seek( ctx,tmppos ) ) {
ctx->write_pos = tmppos;
ctx->stream_count++;
return AW_TRUE;
}
return AW_FALSE;
}
AW_RET AW_AddVideoStream( AW_CTX *ctx,const char *fourcc,int bitcount )
{
STREAM_CTX *cstream;
AW_UINT32 biCompression = 0;
AW_UINT32 biClrUsed = 0;
AW_UINT32 bmiColorsSize = 0;
const void *bmiColors = NULL;
if( !ctx ) return AW_ERR_PARAM;
cstream = ctx->streams + ctx->stream_count;
if( ctx->state != AW_StreamsConfig ) return AW_ERR_WRONG_STATE;
if( ctx->stream_count >= AW_MAX_STREAMS ) return AW_ERR_STREAMS_LIMIT;
memset( cstream,0,sizeof( STREAM_CTX ));
cstream->streamh_start = ctx->write_pos;
cstream->stype = AW_ST_Video;
cstream->scale = 100;
cstream->rate = 2997; /* 2997 / scale( 100 ) for NTSC 29.97 */
if (fourcc) {
memcpy(&biCompression, fourcc, 4);
memcpy( cstream->fourcc,fourcc,4 );
}
if (!biCompression) {
memcpy( cstream->fourcc,DIB4cc,4 );
switch (bitcount) {
case 4:
/* This one is not played by most players */
bmiColors = aw_palette_4bpp;
bmiColorsSize = sizeof(aw_palette_4bpp);
biClrUsed = 1 << bitcount;
break;
case 8:
bmiColors = aw_palette_8bpp;
bmiColorsSize = sizeof(aw_palette_8bpp);
biClrUsed = 1 << bitcount;
break;
case 16:
biCompression = 3 /* BI_BITFIELDS */;
bmiColors = aw_mask_rgb16;
bmiColorsSize = sizeof(aw_mask_rgb16);
break;
case 32:
/* This one is not played by most players */
biCompression = 3 /* BI_BITFIELDS */;
bmiColors = aw_mask_rgb32;
bmiColorsSize = sizeof(aw_mask_rgb32);
break;
}
}
if( AW_WriteAVIStreamHeader(ctx, vids4cc, cstream->fourcc,
cstream->scale, cstream->rate,
ctx->width, ctx->height) &&
/* "strf" start" */
AW_WriteFourCC( ctx,strf4cc ) &&
/* Size of strf chunk */
AW_WriteULONG( ctx,STRF_VIDEO_CHUNK_SIZE + bmiColorsSize ) &&
/*
* typedef struct {
* DWORD biSize;
* LONG biWidth;
* LONG biHeight;
* WORD biPlanes;
* WORD biBitCount;
* DWORD biCompression;
* DWORD biSizeImage;
* LONG biXPelsPerMeter;
* LONG biYPelsPerMeter;
* DWORD biClrUsed;
* DWORD biClrImportant;
* } BITMAPINFOHEADER;
*/
/* biSize */
AW_WriteULONG( ctx,STRF_VIDEO_CHUNK_SIZE ) &&
/* biWidth */
AW_WriteULONG( ctx,ctx->width ) &&
/* biHeight */
AW_WriteULONG( ctx,ctx->height ) &&
/* biPlanes */
AW_WriteUSHORT( ctx,1 ) &&
/* biBitCount */
AW_WriteUSHORT( ctx,bitcount ) &&
/* biCompression */
AW_WriteULONG( ctx,biCompression ) &&
/* biSizeImage */
AW_WriteULONG( ctx,ctx->width * ctx->height * bitcount / 8 ) &&
/* biXPelsPerMeter */
AW_WriteULONG( ctx,0 ) &&
/* biYPelsPerMeter */
AW_WriteULONG( ctx,0 ) &&
/* biClrUsed */
AW_WriteULONG( ctx,biClrUsed ) &&
/* biClrImportant */
AW_WriteULONG( ctx,0 ) &&
/* bmiColors */
AW_FWRITE( ctx->f,bmiColors,bmiColorsSize,&ctx->write_pos ) &&
/* Finalize stream list */
AW_FinalizeStreamHeader( ctx,cstream ) ) {
return AW_OK;
}
ctx->state = AW_StreamError;
return AW_ERR_FILE_IO;
}
AW_RET AW_AddAudioStreamPCM( AW_CTX *ctx,int freq,int bits,int channels )
{
STREAM_CTX *cstream = ctx->streams + ctx->stream_count;
if( !ctx ) return AW_ERR_PARAM;
if( ctx->state != AW_StreamsConfig ) return AW_ERR_WRONG_STATE;
if( ctx->stream_count >= AW_MAX_STREAMS ) return AW_ERR_STREAMS_LIMIT;
memset( cstream,0,sizeof( STREAM_CTX ));
cstream->streamh_start = ctx->write_pos;
cstream->stype = AW_ST_Audio;
cstream->scale = 1;
cstream->rate = freq;
if( AW_WriteAVIStreamHeader(ctx, auds4cc, cstream->fourcc,
cstream->scale, cstream->rate, 0, 0) &&
/* "strf" start" */
AW_WriteFourCC( ctx,strf4cc ) &&
/* Size of strf chunk, 18 for PCM audio */
AW_WriteULONG( ctx,18 ) &&
/*
* typedef struct {
* WORD wFormatTag;
* WORD nChannels;
* DWORD nSamplesPerSec;
* DWORD nAvgBytesPerSec;
* WORD nBlockAlign;
* WORD wBitsPerSample;
* WORD cbSize;
* } WAVEFORMATEX;
*/
/* wFormatTag */
AW_WriteUSHORT( ctx, 1 /* WAVE_FORMAT_PCM */ ) &&
/* nChannels */
AW_WriteUSHORT( ctx,channels ) &&
/* nSamplesPerSec */
AW_WriteULONG( ctx,freq ) &&
/* nAvgBytesPerSec */
AW_WriteULONG( ctx,freq*channels*bits/8 ) &&
/* nBlockAlign */
AW_WriteUSHORT( ctx,channels*bits/8 ) &&
/* wBitsPerSample */
AW_WriteUSHORT( ctx,bits ) &&
/* cbSize */
AW_WriteUSHORT( ctx,0 ) &&
/* Finalize stream list */
AW_FinalizeStreamHeader( ctx,cstream ) ) {
return AW_OK;
}
ctx->state = AW_StreamError;
return AW_ERR_FILE_IO;
}
AW_RET AW_UpdateStreamHeaderField( AW_CTX *ctx,int stream,AW_SHDR_Fields fld,unsigned long value )
{
STREAM_CTX *s = NULL;
int hdr_offs = 0;
if( !ctx ) return AW_ERR_PARAM;
if( stream >= ctx->stream_count ) return AW_ERR_PARAM;
s = ctx->streams + stream;
switch( fld ) {
case AW_SHDR_Scale:
s->scale = value;
hdr_offs = 20;
break;
case AW_SHDR_Rate:
s->rate = value;
hdr_offs = 24;
break;
default:
assert( 0 );
break;
}
if (hdr_offs) {
const unsigned long tmppos = ctx->write_pos;
if( AW_Seek( ctx,s->streamh_start + 20 + hdr_offs ) &&
AW_WriteULONG( ctx,value ) &&
/* Reposition back to the file end */
AW_Seek( ctx,tmppos ) ) {
return AW_OK;
}
}
ctx->state = AW_StreamError;
return AW_ERR_FILE_IO;
}
AW_RET AW_StartStreamsData( AW_CTX *ctx )
{
if( !ctx ) return AW_ERR_PARAM;
if( ctx->state != AW_StreamsConfig ) return AW_ERR_WRONG_STATE;
/* Align to CD sector size */
if( AW_Align( ctx,2048 ) ) {
/* Finalize header list */
const unsigned long tmppos = ctx->write_pos;
const unsigned long hdrllen = tmppos - 20;
if( AW_Seek( ctx,16 ) &&
AW_WriteULONG( ctx,hdrllen ) &&
/* update dwStreams, offset hdrl + 24 = 56 */
AW_Seek( ctx,AVIH_CHUNK_OFFSET + AVIH_CHUNK_STREAM_COUNT_OFFSET ) &&
AW_WriteULONG( ctx,ctx->stream_count ) &&
/* Reposition back to the file end */
AW_Seek( ctx,tmppos ) &&
AW_WriteFourCC( ctx,LIST4cc ) &&
/* Size of movi LIST chunk, offset 4 from movi list start, fill later */
AW_WriteULONG( ctx,0 ) &&
AW_WriteFourCC( ctx,movi4cc ) ) {
ctx->movi_ch_start = tmppos;
ctx->state = AW_FramesAdd;
return AW_OK;
}
}
ctx->state = AW_StreamError;
return AW_ERR_FILE_IO;
}
#define AW_KEYFRAME_FLAG 0x00000010
AW_RET AW_AddFrame( AW_CTX *ctx,int stream,unsigned char *frame,unsigned long frame_len,int keyframe )
{
unsigned char chunkId[4] = "00dc";
if( !ctx ) return AW_ERR_PARAM;
if( ctx->state != AW_FramesAdd ) return AW_ERR_WRONG_STATE;
if( stream > ctx->stream_count ) return AW_ERR_PARAM;
if( ctx->streams[stream].stype != AW_ST_Video ) return AW_ERR_PARAM;
assert( ctx->stream_count < 100 );
chunkId[0] = '0' + (char)( stream / 10 );
chunkId[1] = '0' + (char)( stream % 10 );
if( AW_AddIdx( ctx,chunkId,keyframe ? AW_KEYFRAME_FLAG : 0,
ctx->write_pos - ( ctx->movi_ch_start + 8 ),
frame_len ) != AW_OK ) {
ctx->state = AW_StreamError;
return AW_ERR_INTERNAL_LIMIT;
}
if( AW_WriteFourCC( ctx,chunkId ) &&
AW_WriteULONG( ctx,frame_len ) &&
AW_FWRITE( ctx->f,frame,frame_len,&ctx->write_pos ) ) {
ctx->streams[stream].frame_count++;
return AW_OK;
}
ctx->state = AW_StreamError;
return AW_ERR_FILE_IO;
}
AW_RET AW_AddAudioChunk( AW_CTX *ctx,int stream,unsigned char *data,unsigned long len)
{
unsigned char chunkId[4] = "00wb";
if( !ctx ) return AW_ERR_PARAM;
if( ctx->state != AW_FramesAdd ) return AW_ERR_WRONG_STATE;
if( stream > ctx->stream_count ) return AW_ERR_PARAM;
if( ctx->streams[stream].stype != AW_ST_Audio ) return AW_ERR_PARAM;
assert( ctx->stream_count < 100 );
chunkId[0] = '0' + (char)( stream / 10 );
chunkId[1] = '0' + (char)( stream % 10 );
if( AW_AddIdx( ctx,chunkId, AW_KEYFRAME_FLAG,
ctx->write_pos - ( ctx->movi_ch_start + 8 ),
len ) != AW_OK ) {
ctx->state = AW_StreamError;
return AW_ERR_INTERNAL_LIMIT;
}
if( AW_WriteFourCC( ctx,chunkId ) &&
AW_WriteULONG( ctx,len ) &&
AW_FWRITE( ctx->f,data,len,&ctx->write_pos ) ) {
ctx->streams[stream].frame_count++;
return AW_OK;
}
ctx->state = AW_StreamError;
return AW_ERR_FILE_IO;
}
/*
* Local Variables:
* c-basic-offset: 4
* indent-tabs-mode: nil
* End:
*/
| 29,662 | C | 31.740618 | 102 | 0.564662 |
adegirmenci/HBL-ICEbot/epiphan/codec/avi_writer/avi_writer.h | /****************************************************************************
*
* $Id: avi_writer.h 15560 2012-02-01 16:27:42Z pzeldin $
*
* Copyright (C) 2007-2009 Epiphan Systems Inc. All rights reserved.
*
* Platform-independent library for creating AVI files.
*
****************************************************************************/
#ifndef __AVI_WRITER_H__
#define __AVI_WRITER_H__
#include <stdio.h>
#define AW_MAX_STREAMS 2
typedef enum {
AW_OK,
AW_ERR_MEMORY,
AW_ERR_PARAM,
AW_ERR_FILE_IO,
AW_ERR_WRONG_STATE,
AW_ERR_STREAMS_LIMIT,
AW_ERR_INTERNAL_LIMIT
} AW_RET;
typedef enum {
AW_HDR_MicroSecPerFrame,
AW_HDR_MaxBytesPerSec,
AW_HDR_TotalFrames,
AW_HDR_Flags,
AW_HDR_Streams,
AW_HDR_SuggestedBufferSize,
AW_HDR_Length
} AW_HDR_Fields;
typedef enum {
AW_SHDR_Scale,
AW_SHDR_Rate
} AW_SHDR_Fields;
typedef FILE * AW_FHANDLE;
typedef struct __AW_CTX AW_CTX;
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
AW_RET AW_FInit( AW_CTX **ctx,AW_FHANDLE f,unsigned long width,unsigned long height );
AW_RET AW_FDone( AW_CTX *ctx );
AW_RET AW_UpdateAVIHeaderField( AW_CTX *ctx,AW_HDR_Fields fld,unsigned long value );
AW_RET AW_AddVideoStream( AW_CTX *ctx,const char *fourcc,int bitcount );
AW_RET AW_AddAudioStreamPCM( AW_CTX *ctx,int freq,int bits,int channels );
/* Scale and rate stream fields will be used for calculation of stream playback length in stream header and
average frame duration in avi header on close in AW_FDone */
AW_RET AW_UpdateStreamHeaderField( AW_CTX *ctx,int stream,AW_SHDR_Fields fld,unsigned long value );
AW_RET AW_StartStreamsData( AW_CTX *ctx ); /* Starts movi chunk */
AW_RET AW_AddFrame( AW_CTX *ctx,int stream,unsigned char *frame,unsigned long frame_len,int keyframe );
AW_RET AW_AddAudioChunk( AW_CTX *ctx,int stream,unsigned char *data,unsigned long len);
#ifdef __cplusplus
} /* end of extern "C" */
#endif /* __cplusplus */
#endif /* __AVI_WRITER_H__ */
| 2,006 | C | 27.267605 | 108 | 0.64008 |
adegirmenci/HBL-ICEbot/epiphan/include/v2u_version.h | /****************************************************************************
*
* $Id: v2u_version.h 22900 2013-07-04 18:43:09Z monich $
*
* Copyright (C) 2004-2013 Epiphan Systems Inc. All rights reserved.
*
* Version information
*
****************************************************************************/
#ifndef _VGA2USB_VERSION_H_
#define _VGA2USB_VERSION_H_ 1
#ifndef V2U_COMPANY_NAME
#define V2U_COMPANY_NAME "Epiphan Systems Inc."
#endif /* V2U_COMPANY_NAME */
#ifndef V2U_COMPANY_URL
#define V2U_COMPANY_URL "http://www.epiphan.com"
#endif /* V2U_COMPANY_URL */
#ifndef V2U_REGISTRATION_URL
#define V2U_REGISTRATION_URL V2U_COMPANY_URL "/register/"
#endif /* V2U_REGISTRATION_URL */
#ifndef V2U_COPYRIGHT_YEARS
#define V2U_COPYRIGHT_YEARS "2004-2013"
#endif /* V2U_COPYRIGHT_YEARS */
#ifndef V2U_PRODUCT_COPYRIGHT
#define V2U_PRODUCT_COPYRIGHT V2U_COPYRIGHT_YEARS " " V2U_COMPANY_NAME
#endif /* V2U_PRODUCT_COPYRIGHT */
#ifndef V2U_PRODUCT_NAME
#define V2U_PRODUCT_NAME "Epiphan Capture"
#endif /* V2U_PRODUCT_NAME */
#define V2U_VERSION_MAJOR 3
#define V2U_VERSION_MINOR 28
#define V2U_VERSION_MICRO 0
#define V2U_VERSION_NANO 9
#endif /* _VGA2USB_VERSION_H_*/
| 1,247 | C | 27.363636 | 78 | 0.605453 |
adegirmenci/HBL-ICEbot/epiphan/include/v2u_dshow.h | /****************************************************************************
*
* $Id: v2u_dshow.h 22128 2013-05-12 06:46:41Z monich $
*
* Copyright (C) 2009-2013 Epiphan Systems Inc. All rights reserved.
*
* VGA2USB driver for Windows.
* Declaration of VGA2USB proprietary property set
*
****************************************************************************/
#ifndef _VGA2USB_V2U_DSHOW_H_
#define _VGA2USB_V2U_DSHOW_H_ 1
/* {9B2C649F-CAE6-4745-8D09-413DF0562C4B} */
#define STATIC_PROPSETID_V2U_PROPSET \
0x9b2c649fL, 0xcae6, 0x4745, 0x8d, 0x09, 0x41, 0x3d, 0xf0, 0x56, 0x2c, 0x4b
/*
* Map between DirectShow PROP_GET properties and V2U properties.
* This map is full.
*/
#define V2U_DSHOW_PROP_MAP(m) \
m( V2U_DSHOW_PROP_GET_DSFLAGS, V2UKey_DirectShowFlags ) \
m( V2U_DSHOW_PROP_GET_DSFIXRES, V2UKey_DirectShowFixRes ) \
m( V2U_DSHOW_PROP_GET_DSBITMAP, V2UKey_DirectShowDefaultBmp ) \
m( V2U_DSHOW_PROP_GET_DSSCALEMODE, V2UKey_DirectShowScaleMode ) \
m( V2U_DSHOW_PROP_GET_DSMAXRATE, V2UKey_DirectShowMaxFps ) \
m( V2U_DSHOW_PROP_GET_USERDATA, V2UKey_UserData ) \
m( V2U_DSHOW_PROP_GET_PROD_ID, V2UKey_UsbProductID ) \
m( V2U_DSHOW_PROP_GET_PROD_TYPE, V2UKey_ProductType ) \
m( V2U_DSHOW_PROP_GET_PROD_NAME, V2UKey_ProductName ) \
m( V2U_DSHOW_PROP_GET_VGAMODE_INFO, V2UKey_ModeMeasurmentsDump ) \
m( V2U_DSHOW_PROP_GET_HW_COMPRESSION, V2UKey_HardwareCompression ) \
m( V2U_DSHOW_PROP_GET_ADJ_RANGE, V2UKey_AdjustmentsRange ) \
m( V2U_DSHOW_PROP_GET_VERSION, V2UKey_Version ) \
m( V2U_DSHOW_PROP_GET_EDID, V2UKey_EDID ) \
m( V2U_DSHOW_PROP_GET_KVM_SUPPORT, V2UKey_KVMCapable ) \
m( V2U_DSHOW_PROP_GET_VGAMODE_ENTRY, V2UKey_VGAMode ) \
m( V2U_DSHOW_PROP_GET_VGAMODE, V2UKey_CurrentVGAMode ) \
m( V2U_DSHOW_PROP_GET_MEASURE_INTERVAL, V2UKey_ModeMeasureInterval ) \
m( V2U_DSHOW_PROP_GET_EDID_SUPPORT, V2UKey_EDIDSupport ) \
m( V2U_DSHOW_PROP_GET_TUNE_INTERVAL, V2UKey_TuneInterval ) \
m( V2U_DSHOW_PROP_GET_SN, V2UKey_SerialNumber ) \
m( V2U_DSHOW_PROP_GET_SIGNAL_TYPE, V2UKey_InputSignalType ) \
m( V2U_DSHOW_PROP_GET_DVIMODE_DETECT, V2UKey_DigitalModeDetect ) \
m( V2U_DSHOW_PROP_GET_NOISE_FILTER, V2UKey_NoiseFilter ) \
m( V2U_DSHOW_PROP_GET_HSYNC_THRESHOLD, V2UKey_HSyncThreshold ) \
m( V2U_DSHOW_PROP_GET_VSYNC_THRESHOLD, V2UKey_VSyncThreshold ) \
m( V2U_DSHOW_PROP_GET_DEVICE_CAPS, V2UKey_DeviceCaps ) \
m( V2U_DSHOW_PROP_GET_DSBITMAP2, V2UKey_DirectShowDefaultBmp2) \
m( V2U_DSHOW_PROP_GET_BUS_TYPE, V2UKey_BusType ) \
m( V2U_DSHOW_PROP_GET_GRABBER_ID, V2UKey_GrabberId ) \
m( V2U_DSHOW_PROP_GET_VIDEO_FORMAT, V2UKey_VideoFormat )
/*
* Second range of properties (add new ones to the end)
*/
#define V2U_DSHOW_PROP_MAP2(m) \
m( V2U_DSHOW_PROP_GET_DSHOW_COMPAT_MODE, V2UKey_DShowCompatMode ) \
m( V2U_DSHOW_PROP_GET_EEDID, V2UKey_EEDID )
/* We have run out of these */
#define V2U_DSHOW_PROP_RESERVE(r)
/* More reserved slots before V2U_DSHOW_PROP_GET_DSHOW_COMPAT_MODE */
#define V2U_DSHOW_PROP_RESERVE2(r) \
r( V2U_DSHOW_PROP_RESERVED_1, -1 ) \
r( V2U_DSHOW_PROP_RESERVED_2, -1 ) \
r( V2U_DSHOW_PROP_RESERVED_3, -1 ) \
r( V2U_DSHOW_PROP_RESERVED_4, -1 ) \
r( V2U_DSHOW_PROP_RESERVED_5, -1 ) \
r( V2U_DSHOW_PROP_RESERVED_6, -1 ) \
r( V2U_DSHOW_PROP_RESERVED_7, -1 ) \
r( V2U_DSHOW_PROP_RESERVED_8, -1 ) \
r( V2U_DSHOW_PROP_RESERVED_9, -1 ) \
r( V2U_DSHOW_PROP_RESERVED_10, -1 ) \
r( V2U_DSHOW_PROP_RESERVED_11, -1 ) \
r( V2U_DSHOW_PROP_RESERVED_12, -1 ) \
r( V2U_DSHOW_PROP_RESERVED_13, -1 ) \
r( V2U_DSHOW_PROP_RESERVED_14, -1 ) \
r( V2U_DSHOW_PROP_RESERVED_15, -1 ) \
r( V2U_DSHOW_PROP_RESERVED_16, -1 ) \
r( V2U_DSHOW_PROP_RESERVED_17, -1 ) \
r( V2U_DSHOW_PROP_RESERVED_18, -1 ) \
r( V2U_DSHOW_PROP_RESERVED_19, -1 ) \
r( V2U_DSHOW_PROP_RESERVED_20, -1 )
/**
* Property IDs
*/
#undef V2U_DSHOW_PROP_DEFINE_ID
#define V2U_DSHOW_PROP_DEFINE_ID(id,key) id,
typedef enum _V2U_DSHOW_PROP {
V2U_DSHOW_PROP_DETECT_VIDEO_MODE, /* V2U_VideoMode */
V2U_DSHOW_PROP_SET_PROPERTY, /* Any property */
V2U_DSHOW_PROP_MAP(V2U_DSHOW_PROP_DEFINE_ID)
V2U_DSHOW_PROP_RESERVE(V2U_DSHOW_PROP_DEFINE_ID)
V2U_DSHOW_PROP_GRAB_PARAMETERS, /* V2U_GrabParameters */
V2U_DSHOW_PROP_DSHOW_ACTIVE_COMPAT_MODE,/* V2UKey_DShowActiveCompatMode */
V2U_DSHOW_PROP_RESERVE2(V2U_DSHOW_PROP_DEFINE_ID)
V2U_DSHOW_PROP_MAP2(V2U_DSHOW_PROP_DEFINE_ID)
V2U_DSHOW_PROP_COUNT /* Not a valid value! */
} V2U_DSHOW_PROP;
#undef V2U_DSHOW_PROP_DEFINE_ID
#endif /* _VGA2USB_V2U_DSHOW_H_ */
| 5,164 | C | 44.307017 | 79 | 0.588304 |
adegirmenci/HBL-ICEbot/epiphan/include/v2u_ioctl.h | /****************************************************************************
*
* $Id: v2u_ioctl.h 19092 2012-10-31 02:04:10Z monich $
*
* Copyright (C) 2003-2012 Epiphan Systems Inc. All rights reserved.
*
* Defines IOCTL interface to the VGA2USB driver. Included by the driver
* and by the user level code.
*
****************************************************************************/
#ifndef _VGA2USB_IOCTL_H_
#define _VGA2USB_IOCTL_H_ 1
#include "v2u_defs.h"
/* Platform specific magic */
#ifdef _WIN32
# define FILE_DEVICE_VGA2USB FILE_DEVICE_UNKNOWN
# define _IOCTL_VGA2USB(x,a) CTL_CODE(FILE_DEVICE_VGA2USB,x,METHOD_NEITHER,a)
# define IOCTL_VGA2USB(x) _IOCTL_VGA2USB(x,FILE_ANY_ACCESS)
# define IOCTL_VGA2USB_R(x,type) _IOCTL_VGA2USB(x,FILE_READ_ACCESS)
# define IOCTL_VGA2USB_W(x,type) _IOCTL_VGA2USB(x,FILE_WRITE_ACCESS)
# define IOCTL_VGA2USB_WR(x,type) _IOCTL_VGA2USB(x,FILE_ANY_ACCESS)
#else /* Unix */
# define IOCTL_VGA2USB(x) _IO('V',x)
# define IOCTL_VGA2USB_R(x,type) _IOR('V',x,type)
# define IOCTL_VGA2USB_W(x,type) _IOW('V',x,type)
# define IOCTL_VGA2USB_WR(x,type) _IOWR('V',x,type)
#endif /* Unix */
/* IOCTL definitions */
/*
* IOCTL_VGA2USB_VIDEOMODE
*
* Detects video mode. If cable is disconnected, width and height are zero.
* Note that the vertical refresh rate is measured in milliHertz.
* That is, the number 59900 represents 59.9 Hz.
*
* Support: Linux, Windows, MacOS X
*/
#define IOCTL_VGA2USB_VIDEOMODE IOCTL_VGA2USB_R(9,V2U_VideoMode)
/*
* IOCTL_VGA2USB_GETPARAMS
* IOCTL_VGA2USB_SETPARAMS
*
* Support: Linux, Windows, MacOS X
*/
/* Legacy flags names */
#define GRAB_BMP_BOTTOM_UP V2U_GRAB_BMP_BOTTOM_UP
#define GRAB_PREFER_WIDE_MODE V2U_GRAB_PREFER_WIDE_MODE
#define GRAB_YCRCB V2U_GRAB_YCRCB
#define IOCTL_VGA2USB_GETPARAMS IOCTL_VGA2USB_R(6,V2U_GrabParameters)
#define IOCTL_VGA2USB_SETPARAMS IOCTL_VGA2USB_W(8,V2U_GrabParameters)
/*
* IOCTL_VGA2USB_GRABFRAME
*
* For pixel format check V2U_GRABFRAME_FORMAT_XXX constants in v2u_defs.h
*
* Support: Linux, Windows, MacOS X
*/
#define IOCTL_VGA2USB_GRABFRAME IOCTL_VGA2USB_WR(10,V2U_GrabFrame)
#define IOCTL_VGA2USB_GRABFRAME2 IOCTL_VGA2USB_WR(20,V2U_GrabFrame2)
/*
* IOCTL_VGA2USB_GETSN
*
* Support: Windows, Linux, MacOS X
*/
typedef struct ioctl_getsn {
char sn[V2U_SN_BUFSIZ]; /* OUT serial number string */
} V2U_PACKED V2U_GetSN;
#define IOCTL_VGA2USB_GETSN IOCTL_VGA2USB_R(7,V2U_GetSN)
/*
* IOCTL_VGA2USB_SENDPS2 (KVM2USB capable products only)
*
* Support: Windows, Linux, MacOS X
*/
#define IOCTL_VGA2USB_SENDPS2 IOCTL_VGA2USB_W(16,V2U_SendPS2)
/*
* IOCTL_VGA2USB_GET_PROPERTY
* IOCTL_VGA2USB_SET_PROPERTY
*
* Get or set the value of the specified property.
*
* Support: Windows, Linux, MacOS X
* Required driver version: 3.6.22 or later.
*/
#define IOCTL_VGA2USB_GET_PROPERTY IOCTL_VGA2USB_WR(18,V2U_Property)
#define IOCTL_VGA2USB_SET_PROPERTY IOCTL_VGA2USB_W(19,V2U_Property)
#endif /* _VGA2USB_IOCTL_H_ */
| 3,098 | C | 28.235849 | 84 | 0.656553 |
adegirmenci/HBL-ICEbot/epiphan/include/v2u_defs.h | /****************************************************************************
*
* $Id: v2u_defs.h 22124 2013-05-11 19:36:54Z monich $
*
* Copyright (C) 2003-2013 Epiphan Systems Inc. All rights reserved.
*
* VGA2USB common defines and types
*
****************************************************************************/
#ifndef _VGA2USB_DEFS_H_
#define _VGA2USB_DEFS_H_ 1
/* Required system headers */
#if !defined(__KERNEL__) && !defined(__C51__) && !defined(__FX3__)
# ifdef _WIN32
# include <windows.h>
# include <winioctl.h>
# else /* Unix */
# include <stdint.h>
# include <sys/ioctl.h>
# endif /* Unix */
#endif /* __KERNEL__ */
/* Structure packing */
#ifdef _WIN32
# include <pshpack1.h>
#endif
#ifndef V2U_PACKED
# if defined(_WIN32) || defined(__C51__)
# define V2U_PACKED
# else
# define V2U_PACKED __attribute__((packed))
# endif
#endif
/* Basic data types */
#ifdef _WIN32
typedef __int8 V2U_INT8;
typedef unsigned __int8 V2U_UINT8;
typedef __int16 V2U_INT16;
typedef unsigned __int16 V2U_UINT16;
typedef __int32 V2U_INT32;
typedef unsigned __int32 V2U_UINT32;
typedef __int64 V2U_INT64;
typedef unsigned __int64 V2U_UINT64;
#elif defined(__C51__)
typedef char V2U_INT8;
typedef unsigned char V2U_UINT8;
typedef short V2U_INT16;
typedef unsigned short V2U_UINT16;
typedef long V2U_INT32;
typedef unsigned long V2U_UINT32;
/* V2U_INT64 and V2U_UINT64 should not be used on FX2 microcontroller */
typedef BYTE V2U_INT64[8];
typedef BYTE V2U_UINT64[8];
#else
typedef int8_t V2U_INT8;
typedef uint8_t V2U_UINT8;
typedef int16_t V2U_INT16;
typedef uint16_t V2U_UINT16;
typedef int32_t V2U_INT32;
typedef uint32_t V2U_UINT32;
typedef int64_t V2U_INT64;
typedef uint64_t V2U_UINT64;
#endif
typedef const char* V2U_STR;
typedef V2U_UINT8 V2U_BYTE;
typedef V2U_UINT16 V2U_UCS2;
typedef V2U_INT32 V2U_BOOL;
#if !defined(__C51__)
typedef V2U_INT64 V2U_TIME;
#endif
#define V2U_TRUE 1
#define V2U_FALSE 0
typedef struct v2u_size {
V2U_INT32 width;
V2U_INT32 height;
} V2U_PACKED V2USize;
typedef struct v2u_rect {
V2U_INT32 x;
V2U_INT32 y;
V2U_INT32 width;
V2U_INT32 height;
} V2U_PACKED V2URect;
typedef struct v2u_str_ucs2 {
V2U_UCS2* buffer; /* not necessarily NULL-terminated */
V2U_UINT32 len; /* string length, in characters */
V2U_UINT32 maxlen; /* buffer size, in characters */
} V2U_PACKED V2UStrUcs2;
/*
* V2U_VideoMode
*
* Video mode descriptor.
*
* Note that the vertical refresh rate is measured in milliHertz.
* That is, the number 59900 represents 59.9 Hz.
*/
typedef struct ioctl_videomode {
V2U_INT32 width; /* screen width, pixels */
V2U_INT32 height; /* screen height, pixels */
V2U_INT32 vfreq; /* vertical refresh rate, mHz */
} V2U_PACKED V2U_VideoMode, V2UVideoMode;
/*
* V2U_GrabParameters
*
* VGA capture parameters.
*
* Gain = Contrast
* Offset = Brightness
*/
typedef struct ioctl_setparams {
V2U_UINT32 flags; /* Validity flags for fields below */
/* When any of the fields below is used, */
/* corresponding V2U_FLAG_VALID_* flag is set */
/* otherwise the field is ignored */
V2U_INT32 hshift; /* Shifts image left (<0) or right(>0). */
/* Valid range depends on the video mode. */
/* Invalid values are rounded to the nearest */
/* valid value */
V2U_UINT8 phase; /* Pixel sampling phase, [0,31] */
V2U_UINT8 gain_r; /* Gain for the red channel, [0,255] */
V2U_UINT8 gain_g; /* Gain for the green channel, [0,255] */
V2U_UINT8 gain_b; /* Gain for the blue channel, [0,255] */
V2U_UINT8 offset_r; /* Offset for the red channel, [0,63] */
V2U_UINT8 offset_g; /* Offset for the green channel, [0,63] */
V2U_UINT8 offset_b; /* Offset for the blue channel, [0,63] */
V2U_UINT8 reserved; /* added for alignment, don't use */
V2U_INT32 vshift; /* Shifts image up or down */
/* Valid range depends on the video mode. */
/* Invalid values are rounded to the nearest */
/* valid value */
V2U_INT32 pllshift; /* Adjusts the PLL value */
V2U_UINT32 grab_flags; /* Sets grab_flags V2U_GRAB_* */
V2U_UINT32 grab_flags_mask; /* Marks which bits from grab_flags are used */
} V2U_PACKED V2U_GrabParameters, V2UGrabParameters;
/* Indicates that hshift field is used */
#define V2U_FLAG_VALID_HSHIFT 0x0001
/* Indicates that phase field is used */
#define V2U_FLAG_VALID_PHASE 0x0002
/* Indicates that all gain_{rgb} and offset_{rgb} fields are used */
#define V2U_FLAG_VALID_OFFSETGAIN 0x0004
/* Indicates that vshift field is used */
#define V2U_FLAG_VALID_VSHIFT 0x0008
/* Indicates that pllshift field is used */
#define V2U_FLAG_VALID_PLLSHIFT 0x0010
/* Indicates that grab_flags and grab_flags_mask are used */
#define V2U_FLAG_VALID_GRABFLAGS 0x0020
/* Flags allowed in grab_flags and grab_flags_mask fields */
/* Grab image upside-down */
#define V2U_GRAB_BMP_BOTTOM_UP 0x10000
/* Sometimes 4:3 and wide modes with the same height are indistinguishable,
* so this flag can force choosing wide mode */
#define V2U_GRAB_PREFER_WIDE_MODE 0x20000
/* We have no way to distinguish Component Video (YCrCb) from RGB+Sync-on-Green,
* so this flag can force YCrCb->RGB conversion on input */
#define V2U_GRAB_YCRCB 0x40000
/*
* The ranges below are obsolete. They depend on the frame grabber model
* as well as the video mode. Use V2UKey_AdjustmentsRange property to get
* the ranges that are valid for the parcular frame grabber and current
* video mode.
*/
#define V2U_MIN_PHASE 0
#define V2U_MAX_PHASE 31
#define V2U_MIN_GAIN 0
#define V2U_MAX_GAIN 255
#define V2U_MIN_OFFSET 0
#define V2U_MAX_OFFSET 63
/*
* V2U_SendPS2
*
* PS/2 packet descriptor.
*/
typedef struct ioctl_sendps2 {
V2U_INT16 addr;
V2U_INT16 len;
V2U_BYTE buf[64];
} V2U_PACKED V2U_SendPS2, V2USendPS2;
#define V2U_PS2ADDR_KEYBOARD 0x01
#define V2U_PS2ADDR_MOUSE 0x02
/*
* Serial number length.
*/
#define V2U_SN_BUFSIZ 32
/*
* Product type.
*/
typedef enum v2u_product_type {
V2UProductOther,
V2UProductVGA2USB,
V2UProductKVM2USB,
V2UProductDVI2USB,
V2UProductVGA2USBPro,
V2UProductVGA2USBLR,
V2UProductDVI2USBSolo,
V2UProductDVI2USBDuo,
V2UProductKVM2USBPro,
V2UProductKVM2USBLR,
V2UProductDVI2USBRespin,
V2UProductVGA2USBHR,
V2UProductVGA2USBLRRespin,
V2UProductVGA2USBHRRespin,
V2UProductVGA2USBProRespin,
V2UProductVGA2FIFO,
V2UProductKVM2FIFO,
V2UProductDVI2FIFO,
V2UProductDVI2Davinci1,
V2UProductVGA2PCI,
V2UProductGioconda,
V2UProductDVI2PCI,
V2UProductKVM2USBLRRespin,
V2UProductHDMI2PCI,
V2UProductDVI2PCIStd,
V2UProductDVI2USB3,
V2UProductDVI2PCIGen2,
V2UProductCount /* Number of known product types */
} V2UProductType;
/*
* Resize algorithms.
*/
typedef enum v2u_scale_mode {
V2UScaleNone, /* No scaling */
V2UScaleModeNearestNeighbor, /* Nearest neighbor algorithm */
V2UScaleModeWeightedAverage, /* Weighted average algorithm */
V2UScaleModeFastBilinear, /* Fast bilinear */
V2UScaleModeBilinear, /* Bilinear */
V2UScaleModeBicubic, /* Bicubic */
V2UScaleModeExperimental, /* Experimental */
V2UScaleModePoint, /* Nearest neighbour# 2 */
V2UScaleModeArea, /* Weighted average */
V2UScaleModeBicubLin, /* Luma bicubic, chroma bilinear */
V2UScaleModeSinc, /* Sinc */
V2UScaleModeLanczos, /* Lanczos */
V2UScaleModeSpline, /* Natural bicubic spline */
V2UScaleModeHardware, /* Scale in hardware, if supported */
V2UScaleModeCount /* Number of valid modes */
} V2UScaleMode;
/* Macros to translate V2UScaleMode to capture flags and back */
#define V2U_SCALE_MODE_TO_FLAGS(_m) \
(((_m) << 16) & V2U_GRABFRAME_SCALE_MASK)
#define V2U_SCALE_FLAGS_TO_MODE(_f) \
((V2UScaleMode)(((_f) & V2U_GRABFRAME_SCALE_MASK) >> 16))
typedef enum v2u_rotation_mode {
V2URotationNone, /* V2U_GRABFRAME_ROTATION_NONE */
V2URotationLeft90, /* V2U_GRABFRAME_ROTATION_LEFT90 */
V2URotationRight90, /* V2U_GRABFRAME_ROTATION_RIGHT90 */
V2URotation180, /* V2U_GRABFRAME_ROTATION_180 */
V2URotationCount /* Number of valid rotation types */
} V2URotationMode;
/* Macros to translate V2URotationMode to capture flags and back */
#define V2U_ROTATION_MODE_TO_FLAGS(_m) \
(((_m) << 20) & V2U_GRABFRAME_ROTATION_MASK)
#define V2U_ROTATION_FLAGS_TO_MODE(_f) \
((V2URotationMode)(((_f) & V2U_GRABFRAME_ROTATION_MASK) >> 20))
typedef struct v2u_adjustment_range {
V2U_UINT32 flags;
V2U_UINT32 valid_flags;
V2U_INT16 hshift_min;
V2U_INT16 hshift_max;
V2U_INT16 phase_min;
V2U_INT16 phase_max;
V2U_INT16 offset_min;
V2U_INT16 offset_max;
V2U_INT16 gain_min;
V2U_INT16 gain_max;
V2U_INT16 vshift_min;
V2U_INT16 vshift_max;
V2U_INT16 pll_min;
V2U_INT16 pll_max;
} V2U_PACKED V2UAdjRange;
/* Video mode descriptor */
typedef struct vesa_videomode {
V2U_UINT32 VerFrequency; /* mHz */
V2U_UINT16 HorAddrTime; /* pixels */
V2U_UINT16 HorFrontPorch; /* pixels */
V2U_UINT16 HorSyncTime; /* pixels */
V2U_UINT16 HorBackPorch; /* pixels */
V2U_UINT16 VerAddrTime; /* lines */
V2U_UINT16 VerFrontPorch; /* lines */
V2U_UINT16 VerSyncTime; /* lines */
V2U_UINT16 VerBackPorch; /* lines */
V2U_UINT32 Type; /* flags, see below */
#define VIDEOMODE_TYPE_VALID 0x01
#define VIDEOMODE_TYPE_ENABLED 0x02
#define VIDEOMODE_TYPE_SUPPORTED 0x04
#define VIDEOMODE_TYPE_DUALLINK 0x08
#define VIDEOMODE_TYPE_DIGITAL 0x10
#define VIDEOMODE_TYPE_INTERLACED 0x20
#define VIDEOMODE_TYPE_HSYNCPOSITIVE 0x40
#define VIDEOMODE_TYPE_VSYNCPOSITIVE 0x80
#define VIDEOMODE_TYPE_TOPFIELDFIRST 0x100
} V2U_PACKED V2UVideoModeDescr;
typedef const V2UVideoModeDescr* V2UVideoModeDescrCPtr;
/* Maximum number of custom videomodes */
#define V2U_CUSTOM_VIDEOMODE_COUNT 8
/*
* The first 8 (V2U_CUSTOM_VIDEOMODE_COUNT) entries in the video mode table
* are reserved for custom video modes. The remaining entries are standard
* video modes.
*/
typedef struct custom_videomode {
V2U_INT32 idx;
V2UVideoModeDescr vesa_mode;
} V2U_PACKED V2UVGAMode;
typedef struct v2u_version {
V2U_INT32 major;
V2U_INT32 minor;
V2U_INT32 micro;
V2U_INT32 nano;
} V2U_PACKED V2UVersion;
/*
* Property keys and types
*/
/* V2UKey_DirectShowFlags */
#define V2U_DSHOW_LIMIT_FPS 0x200
#define V2U_DSHOW_FLIP_VERTICALLY 0x400
#define V2U_DSHOW_FIX_FPS 0x800
/* V2UKey_DShowCompatMode */
/* V2UKey_DShowActiveCompatMode */
typedef enum v2u_dshow_compat_mode {
V2UDShowCompatMode_Invalid = -1, /* Invalid value */
V2UDShowCompatMode_Auto, /* Automatic action (default) */
V2UDShowCompatMode_None, /* No tweaks */
V2UDShowCompatMode_Skype, /* Skype compatiblity */
V2UDShowCompatMode_WebEx, /* WebEx compatibility */
V2UDShowCompatMode_Count /* Number of valid values */
} V2UDShowCompatMode;
/* Type of video input (V2UKey_InputSignalType) */
#define V2U_INPUT_NONE 0x00
#define V2U_INPUT_ANALOG 0x01
#define V2U_INPUT_DIGITAL 0x02
#define V2U_INPUT_SOG 0x04
#define V2U_INPUT_COMPOSITE 0x08
/* V2UKey_DigitalModeDetect */
typedef enum v2u_digital_mode_detect {
V2UDigitalMode_AutoDetect, /* Automatic detection (default) */
V2UDigitalMode_SingleLink, /* Force single link */
V2UDigitalMode_DualLink, /* Force dual link */
V2UDigitalMode_Count /* Not a valid value */
} V2UDigitalModeDetect;
/* V2UKey_NoiseFilter */
typedef enum v2u_noise_filter {
V2UNoiseFilter_Auto, /* Automatic configuration (default) */
V2UNoiseFilter_None, /* Disable noise filter */
V2UNoiseFilter_Low, /* Good for Apple */
V2UNoiseFilter_Moderate,
V2UNoiseFilter_High,
V2UNoiseFilter_Extreme, /* Good for black and white */
V2UNoiseFilter_Count /* Not a valid value */
} V2UNoiseFilter;
/* V2UKey_BusType */
typedef enum v2u_bus_type {
V2UBusType_Other, /* Doesn't fall into any known category */
V2UBusType_USB, /* USB bus */
V2UBusType_PCI, /* PCI (Express) bus */
V2UBusType_VPFE, /* Davinci platform bus */
V2UBusType_Count /* Not a valid value */
} V2UBusType;
/* H/VSync threshold values */
#define V2U_MIN_SYNC_THRESHOLD 0
#define V2U_MAX_SYNC_THRESHOLD 255
#define V2U_DEFAULT_SYNC_THRESHOLD 128
/* ResetADC options */
#define ResetADC_Reset 0x01
#define ResetADC_PowerDown 0x02
#define ResetADC_PowerUp 0x03
/* Divide the value of V2UKey_DirectShowMaxFps by 100 to get the fps value */
#define V2U_FPS_DENOMINATOR 100
/* Device capabilities for V2UKey_DeviceCaps */
#define V2U_CAPS_VGA_CAPTURE 0x0001 /* Captures VGA signal */
#define V2U_CAPS_DVI_CAPTURE 0x0002 /* Captures DVI single-link */
#define V2U_CAPS_DVI_DUAL_LINK 0x0004 /* Captures DVI dual-link */
#define V2U_CAPS_KVM 0x0008 /* KVM functionality */
#define V2U_CAPS_EDID 0x0010 /* Programmable EDID */
#define V2U_CAPS_HW_COMPRESSION 0x0020 /* On-board compression */
#define V2U_CAPS_SYNC_THRESHOLD 0x0040 /* Adjustable sync thresholds */
#define V2U_CAPS_HW_SCALE 0x0080 /* Hardware scale */
#define V2U_CAPS_SIGNATURE 0x0100 /* Signed hardware */
#define V2U_CAPS_SD_VIDEO 0x0200 /* Captures SD video */
#define V2U_CAPS_MULTIGRAB 0x0400 /* Several grabbers on board */
#define V2U_CAPS_AUDIO_CAPTURE 0x0800 /* Captures audio */
/* V2UKey_VideoFormat. For grabbers with V2U_CAPS_SD_VIDEO capability */
typedef enum {
V2UVideoFormat_Unknown = -1,
V2UVideoFormat_SVideo,
V2UVideoFormat_Composite,
V2UVideoFormat_Count
} V2UVideoFormat;
typedef enum v2u_property_access {
V2UPropAccess_NO, /* unaccesible */
V2UPropAccess_RO, /* Read only */
V2UPropAccess_RW, /* Read/Write */
V2UPropAccess_WO, /* Write only */
} V2UPropertyAccess;
typedef enum v2u_property_type {
V2UPropType_Invalid = -1, /* Not a valid type */
V2UPropType_Int8, /* int8 - First valid type (zero) */
V2UPropType_Int16, /* int16 */
V2UPropType_Int32, /* int32 - Also used for enums */
V2UPropType_Boolean, /* boolean */
V2UPropType_Size, /* size */
V2UPropType_Rect, /* rect */
V2UPropType_Version, /* version */
V2UPropType_Binary, /* blob */
V2UPropType_EDID, /* edid */
V2UPropType_AdjustRange, /* adj_range */
V2UPropType_VGAMode, /* vgamode */
V2UPropType_String, /* str */
V2UPropType_StrUcs2, /* wstr */
V2UPropType_Uint8, /* uint8 */
V2UPropType_Uint16, /* uint16 */
V2UPropType_Uint32, /* uint32 */
V2UPropType_Reserved, /* not being used */
V2UPropType_UserData, /* userdata */
V2UPropType_Int64, /* int64 */
V2UPropType_Uint64, /* uint64 */
V2UPropType_VESAMode, /* vesa_mode */
V2UPropType_String2, /* str2 */
V2UPropType_Count /* Number of valid types */
} V2UPropertyType;
#define V2UPropType_Enum V2UPropType_Int32
#define V2UKey_UsbProductID V2UKey_ProductID
#define V2U_PROPERTY_LIST(property) \
property( V2UKey_ProductID, \
"Product id", \
V2UPropType_Int16, \
V2UPropAccess_RO) \
property( V2UKey_ProductType, \
"Product type", \
V2UPropType_Enum, \
V2UPropAccess_RO) \
property( V2UKey_DirectShowFixRes, /* Windows only */\
"DS Fix Resolution", \
V2UPropType_Size, \
V2UPropAccess_RW) \
property( V2UKey_DirectShowFlags, /* Windows only */\
"DS Flags", \
V2UPropType_Int32, \
V2UPropAccess_RW) \
property( V2UKey_DirectShowDefaultBmp, /* Windows only */\
"DS Default BMP", \
V2UPropType_StrUcs2, \
V2UPropAccess_RW) \
property( V2UKey_ModeMeasurmentsDump, \
"Mode Measurments dump", \
V2UPropType_Binary, \
V2UPropAccess_RO) \
property( V2UKey_ResetADC, /* Not really a property */\
"Reset ADC", \
V2UPropType_Int32, \
V2UPropAccess_WO) \
property( V2UKey_DirectShowScaleMode, /* Windows only */\
"DirectShow Scale Mode", \
V2UPropType_Enum, \
V2UPropAccess_RW) \
property( V2UKey_HardwareCompression, \
"Hardware Compression", \
V2UPropType_Boolean, \
V2UPropAccess_RO) \
property( V2UKey_AdjustmentsRange, \
"Adjustments Range", \
V2UPropType_AdjustRange, \
V2UPropAccess_RO) \
property( V2UKey_Version, \
"Version", \
V2UPropType_Version, \
V2UPropAccess_RO) \
property( V2UKey_EDID, \
"EDID", \
V2UPropType_EDID, \
V2UPropAccess_RW) \
property( V2UKey_DirectShowMaxFps, /* Windows only */\
"DS Max fps", \
V2UPropType_Int32, \
V2UPropAccess_RW) \
property( V2UKey_KVMCapable, \
"KVM capable", \
V2UPropType_Boolean, \
V2UPropAccess_RO) \
property( V2UKey_VGAMode, \
"VGA mode", \
V2UPropType_VGAMode, \
V2UPropAccess_RW) \
property( V2UKey_CurrentVGAMode, /* Since 3.24.6 */\
"Current VGA mode", \
V2UPropType_VESAMode, \
V2UPropAccess_RO) \
property( V2UKey_ModeMeasureInterval, \
"Mode Measure interval", \
V2UPropType_Int32, \
V2UPropAccess_RW) \
property( V2UKey_EDIDSupport, \
"EDID support", \
V2UPropType_Boolean, \
V2UPropAccess_RO) \
property( V2UKey_ProductName, \
"Product name", \
V2UPropType_String, \
V2UPropAccess_RO) \
property( V2UKey_TuneInterval, /* ms */\
"Tune interval", \
V2UPropType_Uint32, \
V2UPropAccess_RW) \
property( V2UKey_UserData, \
"User data", \
V2UPropType_UserData, \
V2UPropAccess_RW) \
property( V2UKey_SerialNumber, \
"Serial number", \
V2UPropType_String, \
V2UPropAccess_RO) \
property( V2UKey_InputSignalType, /* Since 3.23.7.3 */\
"Input signal type", \
V2UPropType_Uint32, \
V2UPropAccess_RO) \
property( V2UKey_DigitalModeDetect, /* Since 3.24.5 */\
"Digital mode detection", \
V2UPropType_Enum, \
V2UPropAccess_RW) \
property( V2UKey_NoiseFilter, /* Since 3.24.6 */\
"Noise filter", \
V2UPropType_Enum, \
V2UPropAccess_RW) \
property( V2UKey_HSyncThreshold, /* Since 3.24.6 */\
"Hsync threshold", \
V2UPropType_Uint8, \
V2UPropAccess_RW) \
property( V2UKey_VSyncThreshold, /* Since 3.24.6 */\
"Vsync threshold", \
V2UPropType_Uint8, \
V2UPropAccess_RW) \
property( V2UKey_DeviceCaps, /* Since 3.24.6 */\
"Device capabilities", \
V2UPropType_Uint32, \
V2UPropAccess_RO) \
property( V2UKey_DirectShowDefaultBmp2, /* Since 3.24.9.4, Windows */\
"DS Default BMP", \
V2UPropType_String2, \
V2UPropAccess_RW) \
property( V2UKey_BusType, /* Since 3.24.9.5 */\
"Grabber bus type", \
V2UPropType_Enum, \
V2UPropAccess_RO) \
property( V2UKey_GrabberId, /* Since 3.27.4 */\
"Grabber ID", \
V2UPropType_String, \
V2UPropAccess_RO) \
property( V2UKey_VideoFormat, /* Since 3.27.4 */\
"Video input format", \
V2UPropType_Enum, \
V2UPropAccess_RW) \
property( V2UKey_DShowCompatMode, /* Since 3.27.10, Windows */\
"DShow compatiblity mode", \
V2UPropType_Enum, \
V2UPropAccess_RW) \
property( V2UKey_DShowActiveCompatMode, /* Since 3.27.10, Windows */\
"Active compatiblity mode", \
V2UPropType_Enum, \
V2UPropAccess_RO) \
property( V2UKey_EEDID, /* Since 3.27.14.6 */\
"E-EDID", \
V2UPropType_Binary, \
V2UPropAccess_RW)
/* Define V2UPropertyKey enum */
typedef enum v2u_property_key {
#define V2U_PROPERTY_KEY_ENUM(key,name,type,access) key,
V2U_PROPERTY_LIST(V2U_PROPERTY_KEY_ENUM)
#undef V2U_PROPERTY_KEY_ENUM
V2UKey_Count /* Number of known properties */
} V2UPropertyKey;
#define V2U_USERDATA_LEN 8
typedef union v2u_property_value {
V2U_INT8 int8;
V2U_UINT8 uint8;
V2U_INT16 int16;
V2U_UINT16 uint16;
V2U_INT32 int32;
V2U_UINT32 uint32;
V2U_INT64 int64;
V2U_UINT64 uint64;
V2U_BOOL boolean;
V2UProductType product_type;
V2USize size;
V2URect rect;
V2UStrUcs2 wstr;
V2UAdjRange adj_range;
V2UVersion version;
V2UVGAMode vgamode;
V2UVideoModeDescr vesa_mode;
char str[256];
V2U_UCS2 str2[128];
V2U_UINT8 edid[128];
V2U_UINT8 blob[256];
V2U_UINT8 userdata[V2U_USERDATA_LEN];
} V2UPropertyValue;
typedef struct v2u_ioctl_property {
V2UPropertyKey key; /* IN property key */
V2UPropertyValue value; /* IN/OUT property value */
} V2U_PACKED V2U_Property, V2UProperty;
/*
* V2U_GrabFrame
*
* Frame buffer.
*/
typedef struct ioctl_grabframe {
#define V2U_GrabFrame_Fields(pointer) \
pointer pixbuf; /* IN should be filled by user process */\
V2U_UINT32 pixbuflen; /* IN should be filled by user process */\
V2U_INT32 width; /* OUT width in pixels */\
V2U_INT32 height; /* OUT height in pixels */\
V2U_UINT32 bpp; /* IN pixel format */
V2U_GrabFrame_Fields(void*)
} V2U_PACKED V2U_GrabFrame, V2UGrabFrame;
typedef struct ioctl_grabframe2 {
#define V2U_GrabFrame2_Fields(pointer) \
pointer pixbuf; /* IN should be filled by user process */\
V2U_UINT32 pixbuflen; /* IN should be filled by user process */\
V2U_UINT32 palette; /* IN pixel format */\
V2URect crop; /* IN/OUT cropping area; all zeros = full frame */\
V2U_VideoMode mode; /* OUT VGA mode */\
V2U_UINT32 imagelen; /* OUT size of the image stored in pixbuf */\
V2U_INT32 retcode; /* OUT return/error code */
V2U_GrabFrame2_Fields(void*)
} V2U_PACKED V2U_GrabFrame2, V2UGrabFrame2;
/*
* Error codes
*/
#define V2UERROR_OK 0 /* Success */
#define V2UERROR_FAULT 1 /* Unspecified error */
#define V2UERROR_INVALARG 2 /* Invalid argument */
#define V2UERROR_SMALLBUF 3 /* Insufficient buffer size */
#define V2UERROR_OUTOFMEMORY 4 /* Out of memory */
#define V2UERROR_NOSIGNAL 5 /* No signal detected */
#define V2UERROR_UNSUPPORTED 6 /* Unsupported video mode */
#define V2UERROR_TIMEOUT 7 /* grab timeout */
/*
* The following flags can be OR'ed with V2U_GrabFrame::bpp or
* V2U_GrabFrame2::palette field. The flags are preserved on return.
*
* V2U_GRABFRAME_BOTTOM_UP_FLAG
* This flag requests the bitmap data to be sent in bottom-up format.
* By default, the bitmap data are stored in the top-down order.
*
* V2U_GRABFRAME_KEYFRAME_FLAG
* This flag only makes sense when the data are requested in compressed
* format (V2U_GRABFRAME_FORMAT_CRGB24 and such). If this flag is set, the
* driver updates and returns a full frame (i.e. keyframe).
*/
#define V2U_GRABFRAME_RESERVED 0x0f000000 /* These are ignored */
#define V2U_GRABFRAME_FLAGS_MASK 0xf0000000 /* Bits reserved for flags */
#define V2U_GRABFRAME_BOTTOM_UP_FLAG 0x80000000 /* Invert order of lines */
#define V2U_GRABFRAME_KEYFRAME_FLAG 0x40000000 /* Full frame is requested */
#define V2U_GRABFRAME_ADDR_IS_PHYS 0x20000000 /* Buffer addr is physical */
#define V2U_GRABFRAME_DEINTERLACE 0x10000000 /* De-interlace image, if it is interlaced */
/*
* Image rotation mode
*
* V2U_GRABFRAME_ROTATION_NONE
* No rotation, image is grabbed in its original orientation.
*
* V2U_GRABFRAME_ROTATION_LEFT90
* Grab the image rotated 90 degrees to the left with respect
* to its original orientation.
*
* V2U_GRABFRAME_ROTATION_RIGHT90
* Grab the image rotated 90 degrees to the right with respect
* to its original orientation.
*
* V2U_GRABFRAME_ROTATION_180
* Grab the image rotated 180 degrees with respect to its
* original orientation.
*/
#define V2U_GRABFRAME_ROTATION_MASK 0x00300000 /* Bits reserved for mode */
#define V2U_GRABFRAME_ROTATION_NONE 0x00000000 /* No rotation */
#define V2U_GRABFRAME_ROTATION_LEFT90 0x00100000 /* 90 degrees to the left */
#define V2U_GRABFRAME_ROTATION_RIGHT90 0x00200000 /* 90 degrees to the right */
#define V2U_GRABFRAME_ROTATION_180 0x00300000 /* Rotation 180 degrees */
/* If a valid algoruthm code is set, the image will be scaled image to
* width/height in V2U_GrabFrame or crop.width/crop.height in V2U_GrabFrame2.
* If no bits in V2U_GRABFRAME_SCALE_MASK are set, no scaling is performed.
* If an unknown algorithm code is specified, a default one will be used.
* Scaling works for the following capture formats:
*
* V2U_GRABFRAME_FORMAT_Y8
* V2U_GRABFRAME_FORMAT_RGB4
* V2U_GRABFRAME_FORMAT_RGB8
* V2U_GRABFRAME_FORMAT_RGB16
* V2U_GRABFRAME_FORMAT_BGR16
* V2U_GRABFRAME_FORMAT_RGB24
* V2U_GRABFRAME_FORMAT_ARGB32
* V2U_GRABFRAME_FORMAT_BGR24
* V2U_GRABFRAME_FORMAT_YUY2
* V2U_GRABFRAME_FORMAT_2VUY
* V2U_GRABFRAME_FORMAT_YV12
* V2U_GRABFRAME_FORMAT_I420
* V2U_GRABFRAME_FORMAT_NV12
*
* Scaling is available since version 3.10.9
*
* Note that V2U_GRABFRAME_SCALE_AVERAGE scale mode is EXPERIMENTAL and
* currently only works for RGB24 and BGR24 images.
*/
#define V2U_GRABFRAME_SCALE_MASK 0x000F0000 /* Scale algorithm mask */
#define V2U_GRABFRAME_SCALE_NEAREST 0x00010000 /* Nearest neighbour */
#define V2U_GRABFRAME_SCALE_AVERAGE 0x00020000 /* Weighted average */
#define V2U_GRABFRAME_SCALE_FAST_BILINEAR 0x00030000 /* Fast bilinear */
#define V2U_GRABFRAME_SCALE_BILINEAR 0x00040000 /* Bilinear */
#define V2U_GRABFRAME_SCALE_BICUBIC 0x00050000 /* Bicubic */
#define V2U_GRABFRAME_SCALE_EXPERIMENTAL 0x00060000 /* Experimental */
#define V2U_GRABFRAME_SCALE_POINT 0x00070000 /* Nearest neighbour */
#define V2U_GRABFRAME_SCALE_AREA 0x00080000 /* Weighted average */
#define V2U_GRABFRAME_SCALE_BICUBLIN 0x00090000 /* Lum bicub,Chr bilinear*/
#define V2U_GRABFRAME_SCALE_SINC 0x000A0000 /* Sinc */
#define V2U_GRABFRAME_SCALE_LANCZOS 0x000B0000 /* Lanczos */
#define V2U_GRABFRAME_SCALE_SPLINE 0x000C0000 /* Natural bicubic spline*/
#define V2U_GRABFRAME_SCALE_HW 0x000D0000 /* Hardware provided */
#define V2U_GRABFRAME_SCALE_MAX_MODE 0x000D0000 /* Maximum valid mode */
/* Bits that define image format */
#define V2U_GRABFRAME_FORMAT_MASK 0x0000ffff /* Image format mask */
#define V2U_GRABFRAME_FORMAT_RGB_MASK 0x0000001f /* Mask for RGB formats */
#define V2U_GRABFRAME_FORMAT_RGB4 0x00000004
#define V2U_GRABFRAME_FORMAT_RGB8 0x00000008 /* R2:G3:B3 */
#define V2U_GRABFRAME_FORMAT_RGB16 0x00000010
#define V2U_GRABFRAME_FORMAT_RGB24 0x00000018
#define V2U_GRABFRAME_FORMAT_YUY2 0x00000100 /* Same as YUV422 */
#define V2U_GRABFRAME_FORMAT_YV12 0x00000200
#define V2U_GRABFRAME_FORMAT_2VUY 0x00000300
#define V2U_GRABFRAME_FORMAT_BGR16 0x00000400
#define V2U_GRABFRAME_FORMAT_Y8 0x00000500
#define V2U_GRABFRAME_FORMAT_CRGB24 0x00000600 /* Compressed RGB24 */
#define V2U_GRABFRAME_FORMAT_CYUY2 0x00000700 /* Compressed YUY2 */
#define V2U_GRABFRAME_FORMAT_BGR24 0x00000800
#define V2U_GRABFRAME_FORMAT_CBGR24 0x00000900 /* Compressed BGR24 */
#define V2U_GRABFRAME_FORMAT_I420 0x00000A00 /* Same as YUV420P */
#define V2U_GRABFRAME_FORMAT_ARGB32 0x00000B00
#define V2U_GRABFRAME_FORMAT_NV12 0x00000C00
#define V2U_GRABFRAME_FORMAT_C2VUY 0x00000D00 /* Compressed 2VUY */
/* Old flag names, defined here for backward compatibility */
#define V2U_GRABFRAME_PALETTE_MASK V2U_GRABFRAME_FORMAT_MASK
#define V2U_GRABFRAME_PALETTE_RGB_MASK V2U_GRABFRAME_FORMAT_RGB_MASK
#define V2U_GRABFRAME_PALETTE_RGB4 V2U_GRABFRAME_FORMAT_RGB4
#define V2U_GRABFRAME_PALETTE_RGB8 V2U_GRABFRAME_FORMAT_RGB8
#define V2U_GRABFRAME_PALETTE_RGB16 V2U_GRABFRAME_FORMAT_RGB16
#define V2U_GRABFRAME_PALETTE_RGB24 V2U_GRABFRAME_FORMAT_RGB24
#define V2U_GRABFRAME_PALETTE_ARGB32 V2U_GRABFRAME_FORMAT_ARGB32
#define V2U_GRABFRAME_PALETTE_YUY2 V2U_GRABFRAME_FORMAT_YUY2
#define V2U_GRABFRAME_PALETTE_YV12 V2U_GRABFRAME_FORMAT_YV12
#define V2U_GRABFRAME_PALETTE_I420 V2U_GRABFRAME_FORMAT_I420
#define V2U_GRABFRAME_PALETTE_2VUY V2U_GRABFRAME_FORMAT_2VUY
#define V2U_GRABFRAME_PALETTE_BGR16 V2U_GRABFRAME_FORMAT_BGR16
#define V2U_GRABFRAME_PALETTE_Y8 V2U_GRABFRAME_FORMAT_Y8
#define V2U_GRABFRAME_PALETTE_BGR24 V2U_GRABFRAME_FORMAT_BGR24
#define V2U_GRABFRAME_PALETTE_NV12 V2U_GRABFRAME_FORMAT_NV12
#define V2U_GRABFRAME_FORMAT(p) ((p) & V2U_GRABFRAME_FORMAT_MASK)
/* Macro to determine bpp (bits per pixel) for particular grab format */
#define V2UPALETTE_2_BPP(p) \
(((p) & V2U_GRABFRAME_FORMAT_RGB_MASK) ? \
((V2U_UINT8)((p) & V2U_GRABFRAME_FORMAT_RGB_MASK)) : \
(((V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_BGR16) || \
(V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_YUY2) || \
(V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_2VUY) || \
(V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_CYUY2) || \
(V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_C2VUY)) ? 16 :\
(((V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_YV12) || \
(V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_NV12) || \
(V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_I420)) ? 12 : \
(((V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_Y8) || \
(V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_RGB8)) ? 8 : \
(((V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_CRGB24) || \
(V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_CBGR24) || \
(V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_BGR24)) ? 24 : \
((V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_ARGB32) ? 32 : 0))))))
/* Macro to determine whether frame data is compressed */
#define V2UPALETTE_COMPRESSED(p) \
((V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_CRGB24) || \
(V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_CBGR24) || \
(V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_CYUY2) || \
(V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_C2VUY))
/*
* Restore previous packing
*/
#ifdef _WIN32
# include <poppack.h>
#endif
#endif /* _VGA2USB_DEFS_H_ */
| 34,431 | C | 39.603774 | 96 | 0.596178 |
adegirmenci/HBL-ICEbot/epiphan/include/v2u_compression.h | /****************************************************************************
*
* $Id: v2u_compression.h 8063 2009-11-19 23:11:46Z rekjanov $
*
* Copyright (C) 2007-2009 Epiphan Systems Inc. All rights reserved.
*
* Defines and implements decompression library for EPIPHAN VGA2USB compression
*
****************************************************************************/
#ifndef _VGA2USB_COMPRESSION_H_
#define _VGA2USB_COMPRESSION_H_ 1
#include "v2u_defs.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#ifndef V2UDEC_API
#ifdef _WIN32
#ifdef V2UDEC_EXPORTS
#define V2UDEC_API __declspec(dllexport)
#else
#define V2UDEC_API __declspec(dllimport)
#endif
#else
#define V2UDEC_API
#endif
#endif
/**
* Error codes used as a part of compression SDK
*/
#ifndef EPROTO
# define EPROTO 105
#endif
#ifndef ENOSR
# define ENOSR 106
#endif
#ifndef EOK
# define EOK 0
#endif
/****************************************************************************
*
*
* Public interface to the decompression engine
*
*
****************************************************************************/
/**
* Version of the library and files generatated by the compression algorithm
*/
#define V2U_COMPRESSION_LIB_VERSION 0x00000100
/**
* Context of the files sequence
* Compression algorithm internaly keeps key frame. Therefore to decode
* sequence of frames common context must be created and used during decoding
* of consiquently captured frames
*/
typedef struct v2udec_ctx* V2U_DECOMPRESSION_LIB_CONTEXT;
V2UDEC_API V2U_DECOMPRESSION_LIB_CONTEXT v2udec_init_context( void );
V2UDEC_API void v2udec_deinit_context( V2U_DECOMPRESSION_LIB_CONTEXT uctx );
/**
* Functions to obtain information about the compressed frame
*/
/**
* Minimum header size.
* Useful when reading in bytestream. After receiving this number of bytes
* additional information about the frame can be obtained from
* v2udec_get_framelen() et al.
* This value can be different for different versions of V2U libraries.
*/
V2UDEC_API V2U_UINT32
v2udec_get_minheaderlen(V2U_DECOMPRESSION_LIB_CONTEXT uctx);
/**
* Actual header size.
* Add this to v2udec_get_framelen() to obtain required buffer size to
* hold one compressed frame.
* @return 0 on error.
*/
V2UDEC_API V2U_UINT32
v2udec_get_headerlen(
V2U_DECOMPRESSION_LIB_CONTEXT uctx,
const unsigned char * framebuf,
int framebuflen);
/** Timestamp (in milliseconds) of the frame in the framebuf */
V2UDEC_API V2U_TIME
v2udec_get_timestamp(
V2U_DECOMPRESSION_LIB_CONTEXT uctx,
const unsigned char * framebuf,
int framebuflen);
// Length of the single compressed frame in the framebuf (excluding compression
// header)
V2UDEC_API V2U_UINT32
v2udec_get_framelen(
V2U_DECOMPRESSION_LIB_CONTEXT uctx,
const unsigned char * framebuf,
int framebuflen);
// Size of the buffer required to decompress the frame in the framebuf
// (function of frame resolution and palette)
V2UDEC_API int
v2udec_get_decompressed_framelen(
V2U_DECOMPRESSION_LIB_CONTEXT uctx,
const unsigned char * framebuf,
int framebuflen);
// Palette of the frame in the framebuf (currently RGB24 or YUY2)
V2UDEC_API V2U_UINT32
v2udec_get_palette(
V2U_DECOMPRESSION_LIB_CONTEXT uctx,
const unsigned char * framebuf,
int framebuflen);
// Palette of the frame in the framebuf before decompression
V2UDEC_API V2U_UINT32
v2udec_get_cpalette(
V2U_DECOMPRESSION_LIB_CONTEXT uctx,
const unsigned char * framebuf,
int framebuflen);
// Set desired palette for the frame in the framebuf
V2UDEC_API V2U_BOOL
v2udec_set_palette(
V2U_DECOMPRESSION_LIB_CONTEXT uctx,
const unsigned char * framebuf,
int framebuflen,
V2U_UINT32 palette);
// Resolution of the frame in the framebuf
V2UDEC_API void
v2udec_get_frameres(
V2U_DECOMPRESSION_LIB_CONTEXT uctx,
const unsigned char * framebuf,
int framebuflen,
V2URect * rect);
// Video mode of the frame in the framebuf,
// that is width and height before cropping
// and vertical refresh rate.
V2UDEC_API void
v2udec_get_videomode(
V2U_DECOMPRESSION_LIB_CONTEXT uctx,
const unsigned char * framebuf,
int framebuflen,
V2U_VideoMode * vmode);
// Keyframe if not 0
V2UDEC_API int
v2udec_is_keyframe(
V2U_DECOMPRESSION_LIB_CONTEXT uctx,
const unsigned char * framebuf,
int framebuflen);
// Ordered if not 0
V2UDEC_API int
v2udec_is_ordered(
V2U_DECOMPRESSION_LIB_CONTEXT uctx,
const unsigned char * framebuf,
int framebuflen);
/**
* Decompression functions
*/
V2UDEC_API int
v2udec_decompress_frame(
V2U_DECOMPRESSION_LIB_CONTEXT uctx,
const unsigned char * framebuf,
int framebuflen,
unsigned char * bufout, // user-allocated buffer for decompressed frame
int bufoutlen);
V2UDEC_API int
v2udec_decompress_frame2(
V2U_DECOMPRESSION_LIB_CONTEXT uctx,
const unsigned char * framebuf,
int framebuflen,
unsigned char * bufout,
int bufoutlen,
const unsigned char *prev_frame,
int prev_frame_len,
int just_key_data);
#ifdef __cplusplus
} /* end of extern "C" */
#endif /* __cplusplus */
#endif //_VGA2USB_COMPRESSION_H_
| 5,192 | C | 24.455882 | 79 | 0.684707 |
adegirmenci/HBL-ICEbot/epiphan/include/v2u_id.h | /****************************************************************************
*
* $Id: v2u_id.h 21957 2013-04-29 19:18:29Z monich $
*
* Copyright (C) 2003-2013 Epiphan Systems Inc. All rights reserved.
*
* Defines vendor and product ids of VGA2USB hardware. Included by the
* driver and by the user level code.
*
****************************************************************************/
#ifndef _VGA2USB_ID_H_
#define _VGA2USB_ID_H_ 1
/**
* Vendor and product ids.
*
* NOTE: if you are adding a new product ID, don't forget to update
* V2U_PRODUCT_MAP macro below.
*/
#define EPIPHAN_VENDORID 0x5555
#define VGA2USB_VENDORID EPIPHAN_VENDORID
#define VGA2USB_PRODID_VGA2USB 0x1110
#define VGA2USB_PRODID_KVM2USB 0x1120
#define VGA2USB_PRODID_DVI2USB 0x2222
#define VGA2USB_PRODID_VGA2USB_LR 0x3340
#define VGA2USB_PRODID_VGA2USB_HR 0x3332
#define VGA2USB_PRODID_VGA2USB_PRO 0x3333
#define VGA2USB_PRODID_VGA2USB_LR_RESPIN 0x3382
#define VGA2USB_PRODID_KVM2USB_LR_RESPIN 0x3383
#define VGA2USB_PRODID_VGA2USB_HR_RESPIN 0x3392
#define VGA2USB_PRODID_VGA2USB_PRO_RESPIN 0x33A2
#define VGA2USB_PRODID_DVI2USB_RESPIN 0x3380
#define VGA2USB_PRODID_KVM2USB_LR 0x3344
#define VGA2USB_PRODID_KVM2USB_PRO 0x3337
#define VGA2USB_PRODID_DVI2USB_SOLO 0x3411
#define VGA2USB_PRODID_DVI2USB_DUO 0x3422
#define VGA2USB_PRODID_DVI2USB3 0x3500
#define VGA2USB_PRODID_VGA2FIFO 0x4000
#define VGA2USB_PRODID_KVM2FIFO 0x4004
#define VGA2USB_PRODID_DVI2FIFO 0x4080
#define VGA2USB_PRODID_DAVINCI1 0x5000
#define VGA2USB_PRODID_VGA2PCI 0x3A00
#define VGA2USB_PRODID_DVI2PCI 0x3B00
#define VGA2USB_PRODID_DVI2PCI_STD 0x3B10
#define VGA2USB_PRODID_HDMI2PCI 0x3C00
#define VGA2USB_PRODID_DVI2PCI2 0x3D00
#define VGA2USB_PRODID_GIOCONDA 0x5100
#define VGA2USB_PRODID_ORNITHOPTER 0x5200
/**
* Macros for detecting VGA2USB hardware
*/
#define VGA2USB_IS_VGA2USB(idVendor,idProduct,iProduct,iMfg) \
((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_VGA2USB && \
((iProduct)>0 || (iMfg)>0))
#define VGA2USB_IS_KVM2USB(idVendor,idProduct,iProduct,iMfg) \
((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_KVM2USB && \
((iProduct)>0 || (iMfg)>0))
#define VGA2USB_IS_DVI2USB(idVendor,idProduct,iProduct,iMfg) \
((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_DVI2USB && \
((iProduct)>0 || (iMfg)>0))
#define VGA2USB_IS_VGA2USB_PRO(idVendor,idProduct,iProduct,iMfg) \
((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_VGA2USB_PRO && \
((iProduct)>0 || (iMfg)>0))
#define VGA2USB_IS_VGA2USB_HR(idVendor,idProduct,iProduct,iMfg) \
((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_VGA2USB_HR && \
((iProduct)>0 || (iMfg)>0))
#define VGA2USB_IS_VGA2USB_LR(idVendor,idProduct,iProduct,iMfg) \
((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_VGA2USB_LR && \
((iProduct)>0 || (iMfg)>0))
#define VGA2USB_IS_VGA2USB_LR_RESPIN(idVendor,idProduct,iProduct,iMfg) \
((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_VGA2USB_LR_RESPIN && \
((iProduct)>0 || (iMfg)>0))
#define VGA2USB_IS_VGA2USB_HR_RESPIN(idVendor,idProduct,iProduct,iMfg) \
((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_VGA2USB_HR_RESPIN && \
((iProduct)>0 || (iMfg)>0))
#define VGA2USB_IS_VGA2USB_PRO_RESPIN(idVendor,idProduct,iProduct,iMfg) \
((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_VGA2USB_PRO_RESPIN && \
((iProduct)>0 || (iMfg)>0))
#define VGA2USB_IS_KVM2USB_LR(idVendor,idProduct,iProduct,iMfg) \
((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_KVM2USB_LR && \
((iProduct)>0 || (iMfg)>0))
#define VGA2USB_IS_KVM2USB_PRO(idVendor,idProduct,iProduct,iMfg) \
((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_KVM2USB_PRO && \
((iProduct)>0 || (iMfg)>0))
#define VGA2USB_IS_DVI2USB_SOLO(idVendor,idProduct,iProduct,iMfg) \
((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_DVI2USB_SOLO && \
((iProduct)>0 || (iMfg)>0))
#define VGA2USB_IS_DVI2USB_DUO(idVendor,idProduct,iProduct,iMfg) \
((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_DVI2USB_DUO && \
((iProduct)>0 || (iMfg)>0))
#define VGA2USB_IS_DVI2USB_RESPIN(idVendor,idProduct,iProduct,iMfg) \
((idVendor)==VGA2USB_VENDORID &&(idProduct)==VGA2USB_PRODID_DVI2USB_RESPIN &&\
((iProduct)>0 || (iMfg)>0))
#define VGA2USB_IS_KVM2USB_LR_RESPIN(idVendor,idProduct,iProduct,iMfg) \
((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_KVM2USB_LR_RESPIN && \
((iProduct)>0 || (iMfg)>0))
#define VGA2USB_IS_DVI2USB3(idVendor,idProduct,iProduct,iMfg) \
((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_DVI2USB3 && \
((iProduct)>0 || (iMfg)>0))
#define VGA2USB_IS_ANY(idVendor,idProduct,iProduct,iMfg) \
(VGA2USB_IS_VGA2USB(idVendor,idProduct,iProduct,iMfg) || \
VGA2USB_IS_KVM2USB(idVendor,idProduct,iProduct,iMfg) || \
VGA2USB_IS_DVI2USB(idVendor,idProduct,iProduct,iMfg) || \
VGA2USB_IS_DVI2USB_SOLO(idVendor,idProduct,iProduct,iMfg) || \
VGA2USB_IS_DVI2USB_DUO(idVendor,idProduct,iProduct,iMfg) || \
VGA2USB_IS_DVI2USB_RESPIN(idVendor,idProduct,iProduct,iMfg) || \
VGA2USB_IS_VGA2USB_PRO(idVendor,idProduct,iProduct,iMfg) || \
VGA2USB_IS_VGA2USB_HR(idVendor,idProduct,iProduct,iMfg) || \
VGA2USB_IS_VGA2USB_LR(idVendor,idProduct,iProduct,iMfg) || \
VGA2USB_IS_VGA2USB_LR_RESPIN(idVendor,idProduct,iProduct,iMfg) || \
VGA2USB_IS_VGA2USB_HR_RESPIN(idVendor,idProduct,iProduct,iMfg) || \
VGA2USB_IS_VGA2USB_PRO_RESPIN(idVendor,idProduct,iProduct,iMfg) || \
VGA2USB_IS_KVM2USB_PRO(idVendor,idProduct,iProduct,iMfg) || \
VGA2USB_IS_KVM2USB_LR(idVendor,idProduct,iProduct,iMfg) || \
VGA2USB_IS_KVM2USB_LR_RESPIN(idVendor,idProduct,iProduct,iMfg) || \
VGA2USB_IS_DVI2USB3(idVendor,idProduct,iProduct,iMfg))
/**
* Windows device name format. Used by user level code on Windows to open
* a handle to the VGA2USB driver.
*/
#define VGA2USB_WIN_DEVICE_FORMAT "EpiphanVga2usb%lu"
/**
* This macro helps to map VGA2USB product ids into product names
*/
#define V2U_PRODUCT_MAP(map) \
map( VGA2USB_PRODID_VGA2USB, V2UProductVGA2USB, "VGA2USB" )\
map( VGA2USB_PRODID_KVM2USB, V2UProductKVM2USB, "KVM2USB" )\
map( VGA2USB_PRODID_DVI2USB, V2UProductDVI2USB, "DVI2USB" )\
map( VGA2USB_PRODID_VGA2USB_LR, V2UProductVGA2USBLR, "VGA2USB LR" )\
map( VGA2USB_PRODID_VGA2USB_HR, V2UProductVGA2USBHR, "VGA2USB HR" )\
map( VGA2USB_PRODID_VGA2USB_PRO, V2UProductVGA2USBPro, "VGA2USB Pro" )\
map( VGA2USB_PRODID_VGA2USB_LR_RESPIN,V2UProductVGA2USBLRRespin,"VGA2USB LR")\
map( VGA2USB_PRODID_VGA2USB_HR_RESPIN,V2UProductVGA2USBHRRespin,"VGA2USB HR")\
map( VGA2USB_PRODID_VGA2USB_PRO_RESPIN,V2UProductVGA2USBProRespin,"VGA2USB Pro")\
map( VGA2USB_PRODID_DVI2USB_RESPIN,V2UProductDVI2USBRespin,"DVI2USB" )\
map( VGA2USB_PRODID_KVM2USB_LR, V2UProductKVM2USBLR, "KVM2USB LR" )\
map( VGA2USB_PRODID_KVM2USB_LR_RESPIN, V2UProductKVM2USBLRRespin, "KVM2USB LR")\
map( VGA2USB_PRODID_KVM2USB_PRO, V2UProductKVM2USBPro, "KVM2USB Pro" )\
map( VGA2USB_PRODID_DVI2USB_SOLO, V2UProductDVI2USBSolo, "DVI2USB Solo")\
map( VGA2USB_PRODID_DVI2USB_DUO, V2UProductDVI2USBDuo, "DVI2USB Duo" )\
map( VGA2USB_PRODID_DVI2USB3, V2UProductDVI2USB3, "DVI2USB 3.0" )\
map( VGA2USB_PRODID_VGA2FIFO, V2UProductVGA2FIFO, "VGA2FIFO" )\
map( VGA2USB_PRODID_KVM2FIFO, V2UProductKVM2FIFO, "KVMFIFO" )\
map( VGA2USB_PRODID_DVI2FIFO, V2UProductDVI2FIFO, "DVI2FIFO" )\
map( VGA2USB_PRODID_DAVINCI1, V2UProductDVI2Davinci1, "DVI2Davinci" )\
map( VGA2USB_PRODID_VGA2PCI, V2UProductVGA2PCI, "VGA2PCI" )\
map( VGA2USB_PRODID_GIOCONDA, V2UProductGioconda, "Gioconda" )\
map( VGA2USB_PRODID_DVI2PCI, V2UProductDVI2PCI, "DVI2PCI" )\
map( VGA2USB_PRODID_DVI2PCI_STD, V2UProductDVI2PCIStd, "DVI2PCI Std" )\
map( VGA2USB_PRODID_DVI2PCI2, V2UProductDVI2PCIGen2, "DVI2PCI Gen2")\
map( VGA2USB_PRODID_HDMI2PCI, V2UProductHDMI2PCI, "HDMI2PCI" )
#endif /* _VGA2USB_ID_H_ */
| 8,369 | C | 46.288135 | 86 | 0.68933 |
adegirmenci/HBL-ICEbot/DataLoggerWidget/dataloggerwidget.cpp | #include "dataloggerwidget.h"
#include "ui_dataloggerwidget.h"
DataLoggerWidget::DataLoggerWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::DataLoggerWidget)
{
ui->setupUi(this);
m_worker = new DataLoggerThread;
m_worker->moveToThread(&m_thread);
connect(&m_thread, &QThread::finished, m_worker, &QObject::deleteLater);
m_thread.start();
// connect widget signals to worker slots
connect(this, SIGNAL(initializeDataLogger(std::vector<int>,std::vector<QString>)),
m_worker, SLOT(initializeDataLogger(std::vector<int>,std::vector<QString>)));
connect(this, SIGNAL(setRootDir(QString)), m_worker, SLOT(setRootDirectory(QString)));
connect(this, SIGNAL(closeLogFiles()), m_worker, SLOT(closeLogFiles()));
connect(this, SIGNAL(startLogging()), m_worker, SLOT(startLogging()));
connect(this, SIGNAL(stopLogging()), m_worker, SLOT(stopLogging()));
connect(this, SIGNAL(logNote(QTime,QString)), m_worker, SLOT(logNote(QTime,QString)));
// connect worker signals to widget slots
connect(m_worker, SIGNAL(statusChanged(int)), this, SLOT(workerStatusChanged(int)));
connect(m_worker, SIGNAL(fileStatusChanged(unsigned short,int)),
this, SLOT(workerFileStatusChanged(unsigned short,int)));
m_statusList.push_back(ui->EMstatusLabel);
m_statusList.push_back(ui->ECGstatusLabel);
m_statusList.push_back(ui->EPOSstatusLabel);
m_statusList.push_back(ui->FrmGrabStatusLabel);
m_statusList.push_back(ui->LogStatusLabel);
m_statusList.push_back(ui->ErrorStatusLabel);
m_statusList.push_back(ui->NotesStatusLabel);
m_statusList.push_back(ui->ControlStatusLabel);
m_fileNameList.push_back(ui->EMpathLineEdit);
m_fileNameList.push_back(ui->ECGpathLineEdit);
m_fileNameList.push_back(ui->EPOSpathLineEdit);
m_fileNameList.push_back(ui->FrmGrabPathLineEdit);
m_fileNameList.push_back(ui->LogPathLineEdit);
m_fileNameList.push_back(ui->ErrorPathLineEdit);
m_fileNameList.push_back(ui->NotesPathLineEdit);
m_fileNameList.push_back(ui->ControlPathLineEdit);
m_checkBoxList.push_back(ui->EMcheckBox);
m_checkBoxList.push_back(ui->ECGcheckBox);
m_checkBoxList.push_back(ui->EPOScheckBox);
m_checkBoxList.push_back(ui->FrmGrabCheckBox);
m_checkBoxList.push_back(ui->LogCheckBox);
m_checkBoxList.push_back(ui->ErrorCheckBox);
m_checkBoxList.push_back(ui->NotesCheckBox);
m_checkBoxList.push_back(ui->ControlCheckBox);
m_writeCount.resize(DATALOG_NUM_FILES, 0);
}
DataLoggerWidget::~DataLoggerWidget()
{
m_thread.quit();
m_thread.wait();
qDebug() << "DataLogger thread quit.";
delete ui;
}
void DataLoggerWidget::workerStatusChanged(int status)
{
switch(status)
{
case DATALOG_INITIALIZE_BEGIN:
ui->widgetStatusLineEdit->setText("Initializing");
ui->initFilesButton->setEnabled(false);
ui->dataDirLineEdit->setReadOnly(true);
ui->dataDirPushButton->setEnabled(false);
ui->startLoggingButton->setEnabled(true);
ui->stopLoggingButton->setEnabled(false);
ui->closeFilesButton->setEnabled(false);
ui->logNoteButton->setEnabled(false);
for(size_t i = 0; i < m_checkBoxList.size(); i++)
{
m_fileNameList[i]->setReadOnly(true);
m_checkBoxList[i]->setEnabled(false);
}
break;
case DATALOG_INITIALIZE_FAILED:
ui->widgetStatusLineEdit->setText("Failed!");
ui->initFilesButton->setEnabled(true);
ui->dataDirLineEdit->setReadOnly(false);
ui->dataDirPushButton->setEnabled(true);
ui->startLoggingButton->setEnabled(false);
ui->stopLoggingButton->setEnabled(false);
ui->closeFilesButton->setEnabled(false);
ui->logNoteButton->setEnabled(false);
for(size_t i = 0; i < m_checkBoxList.size(); i++)
{
m_fileNameList[i]->setReadOnly(false);
m_checkBoxList[i]->setEnabled(true);
}
break;
case DATALOG_INITIALIZED:
ui->widgetStatusLineEdit->setText("Initialized");
ui->initFilesButton->setEnabled(false);
ui->dataDirLineEdit->setReadOnly(true);
ui->dataDirPushButton->setEnabled(false);
ui->startLoggingButton->setEnabled(true);
ui->stopLoggingButton->setEnabled(false);
ui->closeFilesButton->setEnabled(true);
ui->logNoteButton->setEnabled(true);
for(size_t i = 0; i < m_checkBoxList.size(); i++)
{
m_fileNameList[i]->setReadOnly(true);
m_checkBoxList[i]->setEnabled(false);
}
break;
case DATALOG_LOGGING_STARTED:
ui->widgetStatusLineEdit->setText("Logging");
ui->initFilesButton->setEnabled(false);
ui->dataDirLineEdit->setReadOnly(true);
ui->dataDirPushButton->setEnabled(false);
ui->startLoggingButton->setEnabled(false);
ui->stopLoggingButton->setEnabled(true);
ui->closeFilesButton->setEnabled(false);
ui->logNoteButton->setEnabled(true);
break;
case DATALOG_LOGGING_STOPPED:
ui->widgetStatusLineEdit->setText("Stopped");
ui->initFilesButton->setEnabled(false);
ui->dataDirLineEdit->setReadOnly(true);
ui->dataDirPushButton->setEnabled(false);
ui->startLoggingButton->setEnabled(true);
ui->stopLoggingButton->setEnabled(false);
ui->closeFilesButton->setEnabled(true);
ui->logNoteButton->setEnabled(true);
break;
case DATALOG_CLOSED:
ui->widgetStatusLineEdit->setText("Closed");
ui->initFilesButton->setEnabled(true);
ui->dataDirLineEdit->setReadOnly(false);
ui->dataDirPushButton->setEnabled(true);
ui->startLoggingButton->setEnabled(false);
ui->stopLoggingButton->setEnabled(false);
ui->closeFilesButton->setEnabled(false);
ui->logNoteButton->setEnabled(false);
for(size_t i = 0; i < m_checkBoxList.size(); i++)
{
m_fileNameList[i]->setReadOnly(false);
m_checkBoxList[i]->setEnabled(true);
}
break;
default:
qDebug() << "Unrecognized status.";
break;
}
}
void DataLoggerWidget::workerFileStatusChanged(const unsigned short fileID, int status)
{
switch(status)
{
case DATALOG_FILE_OPENED:
m_statusList[fileID]->setText("Opened");
m_statusList[fileID]->setStyleSheet("QLabel { background-color : green;}");
break;
case DATALOG_FILE_CLOSED:
m_statusList[fileID]->setText("Closed");
m_statusList[fileID]->setStyleSheet("QLabel { background-color : yellow;}");
break;
case DATALOG_FILE_ERROR:
m_statusList[fileID]->setText("ERROR!");
m_statusList[fileID]->setStyleSheet("QLabel { background-color : red;}");
break;
case DATALOG_FILE_DATA_LOGGED:
m_writeCount[fileID] += 1; // data written
break;
default:
qDebug() << "Worker status not recognized!";
break;
}
}
void DataLoggerWidget::on_dataDirPushButton_clicked()
{
QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"),
"../ICEbot_QT_v1/LoggedData",
QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks);
ui->dataDirLineEdit->setText(dir);
ui->initFilesButton->setEnabled(true); // enable initialize button
}
void DataLoggerWidget::on_initFilesButton_clicked()
{
std::vector<int> enableMask;
std::vector<QString> fileNames;
QString rootDir = ui->dataDirLineEdit->text();
QString datetime = QDateTime::currentDateTime().toString("yyyyMMdd_hhmmsszzz");
rootDir.append("/");
rootDir.append(datetime);
ui->subdirLineEdit->setText(tr("/")+datetime);
emit setRootDir(rootDir);
for(int i = 0; i < DATALOG_NUM_FILES; i++)
{
enableMask.push_back(m_checkBoxList[i]->isChecked());
QString fname = rootDir;
fname.append("/");
fname.append(datetime);
fname.append("_");
fname.append(m_fileNameList[i]->text());
fileNames.push_back(fname);
}
emit initializeDataLogger(enableMask, fileNames);
}
void DataLoggerWidget::on_closeFilesButton_clicked()
{
for(size_t i = 0; i < DATALOG_NUM_FILES; i++)
qDebug() << m_writeCount[i] << "records written to" << m_fileNameList[i]->text();
// reset counts
m_writeCount.clear();
m_writeCount.resize(DATALOG_NUM_FILES, 0);
emit closeLogFiles();
}
void DataLoggerWidget::on_startLoggingButton_clicked()
{
emit startLogging();
}
void DataLoggerWidget::on_stopLoggingButton_clicked()
{
emit stopLogging();
}
void DataLoggerWidget::on_logNoteButton_clicked()
{
emit logNote(QTime::currentTime(), ui->noteTextEdit->toPlainText());
ui->noteTextEdit->clear();
}
| 8,985 | C++ | 34.377953 | 90 | 0.650751 |
adegirmenci/HBL-ICEbot/DataLoggerWidget/dataloggerthread.cpp | #include "dataloggerthread.h"
DataLoggerThread::DataLoggerThread(QObject *parent) : QObject(parent)
{
qRegisterMetaType< std::vector<int> >("std::vector<int>");
qRegisterMetaType< std::vector<QString> >("std::vector<QString>");
m_isEpochSet = false;
m_isReady = false;
m_keepLogging = false;
m_mutex = new QMutex(QMutex::Recursive);
// for (int i = 0; i < DATALOG_NUM_FILES; i++)
// {
// m_files.push_back(std::shared_ptr<QFile>(new QFile()) );
// m_TextStreams.push_back(std::shared_ptr<QTextStream>(new QTextStream()));
// m_DataStreams.push_back(std::shared_ptr<QTextStream>(new QTextStream()));
// }
m_files.resize(DATALOG_NUM_FILES);
m_TextStreams.resize(DATALOG_NUM_FILES);
m_DataStreams.resize(DATALOG_NUM_FILES);
//qRegisterMetaType<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD>("DOUBLE_POSITION_MATRIX_TIME_Q_RECORD");
}
DataLoggerThread::~DataLoggerThread()
{
closeLogFiles();
qDebug() << "Ending DataLoggerThread - ID: " << reinterpret_cast<int>(QThread::currentThreadId()) << ".";
delete m_mutex;
emit finished();
}
// ------------------------------
// SLOTS IMPLEMENTATION
// ------------------------------
void DataLoggerThread::setEpoch(const QDateTime &epoch)
{
QMutexLocker locker(m_mutex);
if(!m_keepLogging)
{
m_epoch = epoch;
m_isEpochSet = true;
// TODO: Implement generic logEventWithMessage slot
//emit logEventWithMessage(SRC_DATALOGGER, LOG_INFO, QTime::currentTime(), DATALOG_EPOCH_SET,
// m_epoch.toString("dd/MM/yyyy - hh:mm:ss.zzz"));
}
else
emit logEvent(SRC_DATALOGGER, LOG_INFO, QTime::currentTime(), DATALOG_EPOCH_SET_FAILED);
}
void DataLoggerThread::setRootDirectory(QString rootDir)
{
QMutexLocker locker(m_mutex);
// check if the directory exists, if not, create it
QDir dir;
if( ! dir.exists(rootDir) )
{
if( dir.mkpath(rootDir) )
{
qDebug() << "Folder created: " << rootDir;
QDir imgDir;
if( imgDir.mkpath(rootDir + QString("/images")) )
qDebug() << "Folder created: " << "/images";
}
else
{
qDebug() << "Folder creation failed: " << rootDir;
emit statusChanged(DATALOG_FOLDER_ERROR);
}
}
else
{
QDir imgDir;
if(! dir.exists(rootDir+ QString("/images")) )
{
if( imgDir.mkpath(rootDir + QString("/images")) )
qDebug() << "Folder created: " << "/images";
}
}
qDebug() << "Root dir: " << rootDir;
m_rootDirectory = rootDir;
}
void DataLoggerThread::initializeDataLogger(std::vector<int> enableMask, std::vector<QString> fileNames)
{
QMutexLocker locker(m_mutex);
emit statusChanged(DATALOG_INITIALIZE_BEGIN);
if(enableMask.size() == DATALOG_NUM_FILES) // within bounds
{
for (size_t i = 0; i < enableMask.size(); i++) // iterate through items
{
if(enableMask[i]) // user wants to log this
{
bool status = true;
m_files[i].reset(new QFile());
m_files[i]->setFileName(fileNames[i]); // set filename of QFile
if(m_files[i]->open(QIODevice::WriteOnly | QIODevice::Append)) // opened successfuly
{
if( DATALOG_EM_ID == i)
{
m_DataStreams[i].reset(new QDataStream());
m_DataStreams[i]->setDevice(&(*m_files[i]));
(*m_DataStreams[i]) << QDateTime::currentMSecsSinceEpoch();
}
else
{
m_TextStreams[i].reset(new QTextStream());
m_TextStreams[i]->setDevice(&(*m_files[i]));
(*m_TextStreams[i]) << "File opened at: " << getCurrDateTimeStr() << '\n';
}
emit fileStatusChanged(i, DATALOG_FILE_OPENED);
}
else // can't open
{
qDebug() << "File could not be opened: " << m_files[i]->fileName();
status = false;
emit fileStatusChanged(i, DATALOG_FILE_ERROR);
}
}
else // user doesn't want
{
emit fileStatusChanged(i, DATALOG_FILE_CLOSED);
}
}
emit statusChanged(DATALOG_INITIALIZED);
m_isReady = true;
}
else
emit statusChanged(DATALOG_INITIALIZE_FAILED); //error!
}
// This is for writing to EM file as text
//void DataLoggerThread::logEMdata(QTime timeStamp,
// int sensorID,
// DOUBLE_POSITION_MATRIX_TIME_STAMP_RECORD data)
//{
// QDateTime ts;
// ts.setMSecsSinceEpoch(data.time*1000);
// // Data Format
// // | Sensor ID | Time Stamp | x | y | z | r11 | r12 | ... | r33 |
// QString output;
// output.append(QString("%1\t%2\t%3\t%4\t%5\t%6\t%7\t%8\t%9\t%10\t%11\t%12\t%13\t%14\n")
// .arg(sensorID)
// .arg(QString::number(data.x,'f',m_prec))
// .arg(QString::number(data.y,'f',m_prec))
// .arg(QString::number(data.z,'f',m_prec))
// .arg(QString::number(data.s[0][0],'f',m_prec))
// .arg(QString::number(data.s[0][1],'f',m_prec))
// .arg(QString::number(data.s[0][2],'f',m_prec))
// .arg(QString::number(data.s[1][0],'f',m_prec))
// .arg(QString::number(data.s[1][1],'f',m_prec))
// .arg(QString::number(data.s[1][2],'f',m_prec))
// .arg(QString::number(data.s[2][0],'f',m_prec))
// .arg(QString::number(data.s[2][1],'f',m_prec))
// .arg(QString::number(data.s[2][2],'f',m_prec))
// .arg(QString::number(data.time*1000,'f',m_prec)));
// //.arg(ts.toString("hh:mm:ss:zzz")));
// QMutexLocker locker(m_mutex);
// if(m_files[DATALOG_EM_ID]->isOpen())
// {
// (*m_TextStreams[DATALOG_EM_ID]) << output;
//
// // emit fileStatusChanged(DATALOG_EM_ID, DATALOG_FILE_DATA_LOGGED);
// }
// else
// qDebug() << "File is closed.";
//}
void DataLoggerThread::logEMdata(QTime timeStamp,
int sensorID,
DOUBLE_POSITION_MATRIX_TIME_Q_RECORD data)
{
// Data Format
// | Sensor ID | Time Stamp | x | y | z | q1 | q2 | q3 | q4 | quality |
// | int | double | ... double ... |
QMutexLocker locker(m_mutex);
if(m_isReady && m_files[DATALOG_EM_ID]->isOpen())
{
(*m_DataStreams[DATALOG_EM_ID]) << sensorID
<< data.time*1000
<< data.x
<< data.y
<< data.z
<< data.s[0][0]
<< data.s[0][1]
<< data.s[0][2]
<< data.s[1][0]
<< data.s[1][1]
<< data.s[1][2]
<< data.s[2][0]
<< data.s[2][1]
<< data.s[2][2]
<< data.quality;
// << data.q[0]
// << data.q[1]
// << data.q[2]
// << data.q[3]
// emit fileStatusChanged(DATALOG_EM_ID, DATALOG_FILE_DATA_LOGGED);
}
else
qDebug() << "File is closed.";
}
// save image and write details to text file
void DataLoggerThread::logFrmGrabImage(std::shared_ptr<Frame> frm)
{
QDateTime imgTime;
imgTime.setMSecsSinceEpoch(frm->timestamp_);
// file name of frame
QString m_imgFname = imgTime.toString("ddMMyyyy_hhmmsszzz");
// populate m_imgFname with index
m_imgFname.append( QString("_%1.jpg").arg(frm->index_) );
QString m_DirImgFname = m_rootDirectory;
m_DirImgFname.append("/images/");
m_DirImgFname.append(m_imgFname);
// save frame
//state = frame->image_.save(m_imgFname, "JPG", 100);
std::vector<int> compression_params;
compression_params.push_back(CV_IMWRITE_JPEG_QUALITY);
compression_params.push_back(100);
cv::imwrite(m_DirImgFname.toStdString().c_str(), frm->image_, compression_params); // write frame
QMutexLocker locker(m_mutex);
// output to text
if(m_isReady && m_files[DATALOG_FrmGrab_ID]->isOpen())
{
(*m_TextStreams[DATALOG_FrmGrab_ID]) << m_imgFname << "\t"
<< QString::number(frm->timestamp_, 'f', 1) << '\n';
// emit fileStatusChanged(DATALOG_FrmGrab_ID, DATALOG_FILE_DATA_LOGGED);
}
else
qDebug() << "FrmGrab text file closed.";
}
void DataLoggerThread::logLabJackData(qint64 timeStamp, std::vector<double> data)
{
QString output = QString("%1").arg(timeStamp);
for(const double &d : data)
{
output.append("\t");
output.append(QString::number(d, 'f', 6));
}
QMutexLocker locker(m_mutex);
if(m_isReady && m_files[DATALOG_ECG_ID]->isOpen())
{
// (*m_TextStreams[DATALOG_ECG_ID]) << timeStamp.toString("HH:mm:ss.zzz") << "\t" << QString::number(data, 'f', 6) << '\n';
(*m_TextStreams[DATALOG_ECG_ID]) << output << '\n';
// emit fileStatusChanged(DATALOG_ECG_ID, DATALOG_FILE_DATA_LOGGED);
}
else
;//qDebug() << "File is closed.";
}
void DataLoggerThread::logEPOSdata(QTime timeStamp, int dataType, const int motID, long data)
{
QString output = QString("%1\t").arg(timeStamp.msecsSinceStartOfDay());
switch(dataType)
{
case EPOS_COMMANDED:
output.append("CMND\t");
break;
case EPOS_READ:
output.append("READ\t");
break;
}
output.append(QString("%1\t%2\n").arg(motID).arg(data));
QMutexLocker locker(m_mutex);
if(m_isReady && m_files[DATALOG_EPOS_ID]->isOpen())
{
(*m_TextStreams[DATALOG_EPOS_ID]) << output;
// emit fileStatusChanged(DATALOG_EPOS_ID, DATALOG_FILE_DATA_LOGGED);
}
else
;//qDebug() << "File is closed.";
}
void DataLoggerThread::logEPOSdata(QTime timeStamp, int dataType, std::vector<long> data)
{
QString output;
for(size_t i = 0; i < data.size(); i++)
{
output.append(QString("%1\t").arg(timeStamp.msecsSinceStartOfDay()));
switch(dataType)
{
case EPOS_COMMANDED:
output.append("CMND\t");
break;
case EPOS_READ:
output.append("READ\t");
break;
}
output.append(QString("%1\t%2\n").arg(i).arg(data[i]));
}
QMutexLocker locker(m_mutex);
if(m_isReady && m_files[DATALOG_EPOS_ID]->isOpen())
{
(*m_TextStreams[DATALOG_EPOS_ID]) << output << '\n';
// emit fileStatusChanged(DATALOG_EPOS_ID, DATALOG_FILE_DATA_LOGGED);
}
else
;//qDebug() << "File is closed.";
}
void DataLoggerThread::logControllerData(QTime timeStamp, int loopIdx, int dataType, std::vector<double> data)
{
// CONTROLLER_DXYZPSI = 0, // 4 values
// CONTROLLER_USER_XYZDXYZPSI, // 7 values
// CONTROLLER_CURR_PSY_GAMMA, // 2 values
// CONTROLLER_T_BB_CT_curTipPos, // 16 values
// CONTROLLER_CURR_TASK, // 4 values
// CONTROLLER_PERIOD, // 1 value
// CONTROLLER_BIRD4_MODEL_PARAMS, // 19 = 10 polar + 9 rect
// CONTROLLER_RESETBB, // 16 values
// CONTROLLER_MODES, // 6 values
// CONTROLLER_USANGLE // 1 value
QString output;
output.append(QString("%1\t%2\t").arg(loopIdx).arg(timeStamp.msecsSinceStartOfDay()));
switch(dataType)
{
case CONTROLLER_DXYZPSI: // 4 values
output.append(QString("DXYZPSI\t%1\t%2\t%3\t%4")
.arg(QString::number(data[0],'f',m_prec2))
.arg(QString::number(data[1],'f',m_prec2))
.arg(QString::number(data[2],'f',m_prec2))
.arg(QString::number(data[3],'f',m_prec2)));
break;
case CONTROLLER_USER_XYZDXYZPSI: // 7 values
output.append(QString("USERXYZDXYZPSI\t%1\t%2\t%3\t%4\t%5\t%6\t%7")
.arg(QString::number(data[0],'f',2))
.arg(QString::number(data[1],'f',2))
.arg(QString::number(data[2],'f',2))
.arg(QString::number(data[3],'f',2))
.arg(QString::number(data[4],'f',2))
.arg(QString::number(data[5],'f',2))
.arg(QString::number(data[6],'f',2)));
break;
case CONTROLLER_CURR_PSY_GAMMA: // 2 values
output.append(QString("CURRPSYGAMMA\t%1\t%2")
.arg(QString::number(data[0],'f',m_prec2))
.arg(QString::number(data[1],'f',m_prec2)));
break;
case CONTROLLER_T_BB_CT_curTipPos: // 16 values
output.append(QString("T_BB_CT\t%1\t%2\t%3\t%4\t%5\t%6\t%7\t%8\t%9\t%10\t%11\t%12\t%13\t%14\t%15\t%16")
.arg(QString::number(data[0],'f',m_prec2))
.arg(QString::number(data[1],'f',m_prec2))
.arg(QString::number(data[2],'f',m_prec2))
.arg(QString::number(data[3],'f',m_prec2))
.arg(QString::number(data[4],'f',m_prec2))
.arg(QString::number(data[5],'f',m_prec2))
.arg(QString::number(data[6],'f',m_prec2))
.arg(QString::number(data[7],'f',m_prec2))
.arg(QString::number(data[8],'f',m_prec2))
.arg(QString::number(data[9],'f',m_prec2))
.arg(QString::number(data[10],'f',m_prec2))
.arg(QString::number(data[11],'f',m_prec2))
.arg(QString::number(data[12],'f',m_prec2))
.arg(QString::number(data[13],'f',m_prec2))
.arg(QString::number(data[14],'f',m_prec2))
.arg(QString::number(data[15],'f',m_prec2)));
break;
case CONTROLLER_CURR_TASK: // 4 values
output.append(QString("CURRTASK\t%1\t%2\t%3\t%4")
.arg(QString::number(data[0],'f',m_prec2))
.arg(QString::number(data[1],'f',m_prec2))
.arg(QString::number(data[2],'f',m_prec2))
.arg(QString::number(data[3],'f',m_prec2)));
break;
case CONTROLLER_PERIOD: // 1 value
output.append(QString("PERIOD\t%1")
.arg(QString::number(data[0],'f',m_prec)));
break;
case CONTROLLER_BIRD4_MODEL_PARAMS: // 19 = 10 polar + 9 rect
output.append(QString("BIRD4MODELPARAMS\t%1\t%2\t%3\t%4\t%5\t%6\t%7\t%8\t%9\t%10\t%11\t%12\t%13\t%14\t%15\t%16\t%17\t%18\t%19")
.arg(QString::number(data[0],'f',m_prec2))
.arg(QString::number(data[1],'f',m_prec2))
.arg(QString::number(data[2],'f',m_prec2))
.arg(QString::number(data[3],'f',m_prec2))
.arg(QString::number(data[4],'f',m_prec2))
.arg(QString::number(data[5],'f',m_prec2))
.arg(QString::number(data[6],'f',m_prec2))
.arg(QString::number(data[7],'f',m_prec2))
.arg(QString::number(data[8],'f',m_prec2))
.arg(QString::number(data[9],'f',m_prec2))
.arg(QString::number(data[10],'f',m_prec2))
.arg(QString::number(data[11],'f',m_prec2))
.arg(QString::number(data[12],'f',m_prec2))
.arg(QString::number(data[13],'f',m_prec2))
.arg(QString::number(data[14],'f',m_prec2))
.arg(QString::number(data[15],'f',m_prec2))
.arg(QString::number(data[16],'f',m_prec2))
.arg(QString::number(data[17],'f',m_prec2))
.arg(QString::number(data[18],'f',m_prec2)));
break;
case CONTROLLER_RESETBB: // 16 values
output.append(QString("RESETBB\t%1\t%2\t%3\t%4\t%5\t%6\t%7\t%8\t%9\t%10\t%11\t%12\t%13\t%14\t%15\t%16")
.arg(QString::number(data[0],'f',m_prec2))
.arg(QString::number(data[1],'f',m_prec2))
.arg(QString::number(data[2],'f',m_prec2))
.arg(QString::number(data[3],'f',m_prec2))
.arg(QString::number(data[4],'f',m_prec2))
.arg(QString::number(data[5],'f',m_prec2))
.arg(QString::number(data[6],'f',m_prec2))
.arg(QString::number(data[7],'f',m_prec2))
.arg(QString::number(data[8],'f',m_prec2))
.arg(QString::number(data[9],'f',m_prec2))
.arg(QString::number(data[10],'f',m_prec2))
.arg(QString::number(data[11],'f',m_prec2))
.arg(QString::number(data[12],'f',m_prec2))
.arg(QString::number(data[13],'f',m_prec2))
.arg(QString::number(data[14],'f',m_prec2))
.arg(QString::number(data[15],'f',m_prec2)));
break;
case CONTROLLER_MODES: // 6 values
output.append(QString("MODES\t%1\t%2\t%3\t%4\t%5\t%6")
.arg(QString::number(data[0],'f',1))
.arg(QString::number(data[1],'f',1))
.arg(QString::number(data[2],'f',1))
.arg(QString::number(data[3],'f',1))
.arg(QString::number(data[4],'f',1))
.arg(QString::number(data[5],'f',1)));
break;
case CONTROLLER_USANGLE: // 1 value
output.append(QString("USANGLE\t%1")
.arg(QString::number(data[0],'f',m_prec)));
break;
case CONTROLLER_SWEEP_START: // 4 values
output.append(QString("SWEEP\t%1\t%2\t%3\t%4")
.arg(QString::number(data[0],'f',1)) // nSteps_
.arg(QString::number(data[1],'f',m_prec)) // stepAngle_
.arg(QString::number(data[2],'f',m_prec)) // convLimit_
.arg(QString::number(data[3],'f',1))); // imgDuration_
break;
case CONTROLLER_NEXT_SWEEP: // 1 value
output.append(QString("SWEEPNEXT\t%1")
.arg(QString::number(data[0],'f',m_prec)));
break;
case CONTROLLER_SWEEP_CONVERGED: // 1 value
output.append(QString("SWEEPCONVD\t%1")
.arg(QString::number(data[0],'f',m_prec)));
break;
default:
output.append(QString("UNKNOWN"));
break;
}
QMutexLocker locker(m_mutex);
// output to text
if(m_isReady && m_files[DATALOG_Control_ID]->isOpen())
{
(*m_TextStreams[DATALOG_Control_ID]) << output << '\n';
// emit fileStatusChanged(DATALOG_Control_ID, DATALOG_FILE_DATA_LOGGED);
}
else
;//qDebug() << "Controller text file closed.";
}
void DataLoggerThread::logEvent(int source, int logType, QTime timeStamp, int eventID)
{
// Data Format
// | Time Stamp | Log Type | Source | eventID |
QString output = timeStamp.toString("HH:mm:ss.zzz");
switch(logType)
{
case LOG_INFO:
output.append(" INFO ");
break;
case LOG_WARNING:
output.append(" WARNING ");
break;
case LOG_ERROR:
output.append(" ERROR ");
break;
case LOG_FATAL:
output.append(" FATAL ");
break;
default:
output.append(" UNKNOWN ");
break;
}
switch(source)
{
case SRC_CONTROLLER:
output.append("CONTROLLER ");
break;
case SRC_EM:
output.append("EM ");
break;
case SRC_EPOS:
output.append("EPOS ");
break;
case SRC_FRMGRAB:
output.append("FRMGRAB ");
break;
case SRC_EPIPHAN:
output.append("EPIPHAN ");
break;
case SRC_LABJACK:
output.append("LABJACK ");
break;
case SRC_OMNI:
output.append("OMNI ");
break;
case SRC_GUI:
output.append("GUI ");
break;
case SRC_UNKNOWN:
output.append("UNKNOWN ");
break;
default:
output.append("UNKNOWN ");
break;
}
output.append(QString("%1\n").arg(eventID));
QMutexLocker locker(m_mutex);
if(m_isReady && m_files[DATALOG_Log_ID]->isOpen())
{
(*m_TextStreams[DATALOG_Log_ID]) << output;
emit fileStatusChanged(DATALOG_Log_ID, DATALOG_FILE_DATA_LOGGED);
}
else
qDebug() << "Event logger: File is closed!";
}
void DataLoggerThread::logError(int source, int logType,
QTime timeStamp, int errCode,
QString message)
{
// Data Format
// | Time Stamp | Log Type | Source | eventID |
QString output = timeStamp.toString("HH:mm:ss.zzz");
switch(logType)
{
case LOG_INFO:
output.append(" INFO ");
break;
case LOG_WARNING:
output.append(" WARNING ");
break;
case LOG_ERROR:
output.append(" ERROR ");
break;
case LOG_FATAL:
output.append(" FATAL ");
break;
default:
output.append(" UNKNOWN ");
break;
}
switch(source)
{
case SRC_CONTROLLER:
output.append("CONTROLLER ");
break;
case SRC_EM:
output.append("EM ");
break;
case SRC_EPOS:
output.append("EPOS ");
break;
case SRC_FRMGRAB:
output.append("FRMGRAB ");
break;
case SRC_EPIPHAN:
output.append("EPIPHAN ");
break;
case SRC_LABJACK:
output.append("LABJACK ");
break;
case SRC_OMNI:
output.append("OMNI ");
break;
case SRC_GUI:
output.append("GUI ");
break;
case SRC_UNKNOWN:
output.append("UNKNOWN ");
break;
default:
output.append("UNKNOWN ");
break;
}
output.append(QString("%1 ").arg(errCode));
output.append(message);
QMutexLocker locker(m_mutex);
if(m_isReady && m_files[DATALOG_Error_ID]->isOpen())
{
(*m_TextStreams[DATALOG_Error_ID]) << output << '\n';
emit fileStatusChanged(DATALOG_Error_ID, DATALOG_FILE_DATA_LOGGED);
}
else
qDebug() << "Error logger: File is closed!";
}
void DataLoggerThread::startLogging()
{
QMutexLocker locker(m_mutex);
// make connections
emit statusChanged(DATALOG_LOGGING_STARTED);
}
void DataLoggerThread::stopLogging()
{
QMutexLocker locker(m_mutex);
// sever connections
emit statusChanged(DATALOG_LOGGING_STOPPED);
}
void DataLoggerThread::logNote(QTime timeStamp, QString note)
{
if(m_files[DATALOG_Note_ID]->isOpen())
{
(*m_TextStreams[DATALOG_Note_ID]) << "[" << timeStamp.toString("HH:mm:ss.zzz") << "] " << note << endl;
emit fileStatusChanged(DATALOG_Note_ID, DATALOG_FILE_DATA_LOGGED);
}
}
void DataLoggerThread::closeLogFile(const unsigned short fileID)
{
QMutexLocker locker(m_mutex);
// pointer not null and file is open
if(m_files[fileID] && m_files[fileID]->isOpen())
{
if( DATALOG_EM_ID != fileID )
{
(*m_TextStreams[fileID]) << "File closed at: " << getCurrDateTimeStr() << '\n';
m_TextStreams[fileID]->flush();
//m_DataStreams[fileID]->flush(); // no need to flush, data is not buffered
}
m_files[fileID]->close();
emit fileStatusChanged(fileID, DATALOG_FILE_CLOSED);
}
}
void DataLoggerThread::closeLogFiles()
{
QMutexLocker locker(m_mutex);
for (unsigned short i = 0; i < DATALOG_NUM_FILES; i++) // iterate through items
{
closeLogFile(i);
}
emit statusChanged(DATALOG_CLOSED);
m_isReady = false;
}
// Helper functions
inline const QString getCurrDateTimeFileStr()
{
return QDateTime::currentDateTime().toString("yyyyMMdd_hhmmsszzz");
}
inline const QString getCurrDateTimeStr()
{
return QDateTime::currentDateTime().toString("yyyy/MM/dd - hh:mm:ss.zzz");
}
| 25,116 | C++ | 33.501374 | 135 | 0.508321 |
adegirmenci/HBL-ICEbot/DataLoggerWidget/dataloggerwidget.h | #ifndef DATALOGGERWIDGET_H
#define DATALOGGERWIDGET_H
#include <QWidget>
#include <QThread>
#include <QFileDialog>
#include <QLabel>
#include <QLineEdit>
#include <QCheckBox>
#include "dataloggerthread.h"
namespace Ui {
class DataLoggerWidget;
}
class DataLoggerWidget : public QWidget
{
Q_OBJECT
public:
explicit DataLoggerWidget(QWidget *parent = 0);
~DataLoggerWidget();
DataLoggerThread *m_worker;
signals:
void initializeDataLogger(std::vector<int> enableMask, std::vector<QString> fileNames);
void setRootDir(QString dir);
void closeLogFiles();
void startLogging();
void stopLogging();
void logNote(QTime timeStamp, QString note);
private slots:
void workerStatusChanged(int status);
void workerFileStatusChanged(const unsigned short fileID, int status);
void on_dataDirPushButton_clicked();
void on_initFilesButton_clicked();
void on_closeFilesButton_clicked();
void on_startLoggingButton_clicked();
void on_stopLoggingButton_clicked();
void on_logNoteButton_clicked();
private:
Ui::DataLoggerWidget *ui;
QThread m_thread; // Data Logger Thread will live in here
std::vector<QLabel*> m_statusList;
std::vector<QLineEdit*> m_fileNameList;
std::vector<QCheckBox*> m_checkBoxList;
std::vector<unsigned int> m_writeCount;
};
#endif // DATALOGGERWIDGET_H
| 1,372 | C | 20.453125 | 91 | 0.723761 |
adegirmenci/HBL-ICEbot/DataLoggerWidget/dataloggerthread.h | #ifndef DATALOGGERTHREAD_H
#define DATALOGGERTHREAD_H
#include <QObject>
#include <QMutex>
#include <QMutexLocker>
#include <QThread>
//#include <QWaitCondition>
#include <QString>
#include <QFile>
#include <QDataStream>
#include <QTextStream>
#include <QDir>
#include <QTime>
#include <QTimer>
#include <QDebug>
#include <vector>
#include <memory>
#include "../icebot_definitions.h"
#include "../AscensionWidget/3DGAPI/ATC3DG.h"
#include "../FrmGrabWidget/frmgrabthread.h"
//Q_DECLARE_METATYPE(DOUBLE_POSITION_MATRIX_TIME_Q_RECORD)
Q_DECLARE_METATYPE(std::vector<int>)
class DataLoggerThread : public QObject
{
Q_OBJECT
public:
explicit DataLoggerThread(QObject *parent = 0);
~DataLoggerThread();
signals:
void statusChanged(int event);
void fileStatusChanged(const unsigned short fileID, int status);
void finished(); // emit upon termination
public slots:
// Widget slots
void setEpoch(const QDateTime &epoch);
void setRootDirectory(QString rootDir);
void initializeDataLogger(std::vector<int> enableMask, std::vector<QString> fileNames);
void startLogging();
void stopLogging();
void closeLogFile(const unsigned short fileID);
void closeLogFiles();
void logNote(QTime timeStamp, QString note);
// EM slots
void logEMdata(QTime timeStamp,
int sensorID,
DOUBLE_POSITION_MATRIX_TIME_Q_RECORD data);
void logFrmGrabImage(std::shared_ptr<Frame> frm);
void logLabJackData(qint64 timeStamp, std::vector<double> data);
void logEPOSdata(QTime timeStamp,
int dataType, // EPOS_DATA_IDS
const int motID,
long data);
void logEPOSdata(QTime timeStamp,
int dataType, // EPOS_DATA_IDS
std::vector<long> data);
// void logEvent(LOG_TYPES logType,
// QTime timeStamp,
// EM_EVENT_IDS eventID);
// void logEventWithMessage(LOG_TYPES logType,
// QTime timeStamp,
// EM_EVENT_IDS eventID,
// QString &message);
// void logError(LOG_TYPES logType,
// QTime timeStamp,
// EM_ERROR_CODES,
// QString &message);
// void logData(QTime timeStamp,
// EPOS_DATA_IDS dataType,
// const int motID,
// long data);
// void logData(QTime timeStamp,
// EPOS_DATA_IDS dataType,
// std::vector<long> data);
void logControllerData(QTime timeStamp,
int loopIdx,
int dataType,
std::vector<double> data);
void logEvent(int source,
int logType, // LOG_TYPES
QTime timeStamp,
int eventID);
// log error and log event with message can be combined
void logError(int source, // LOG_SOURCE
int logType, // LOG_TYPE
QTime timeStamp,
int errCode, // EPOS_ERROR_CODES
QString message);
// void logEventWithMessage(LOG_TYPES logType,
// QTime timeStamp,
// EPOS_EVENT_IDS eventID,
// QString &message);
// void logError(LOG_TYPES logType,
// QTime timeStamp,
// EPOS_ERROR_CODES,
// QString &message);
private:
// Instead of using "m_mutex.lock()"
// use "QMutexLocker locker(&m_mutex);"
// this will unlock the mutex when the locker goes out of scope
mutable QMutex *m_mutex;
// Epoch for time stamps
// During initializeDataLogger(), check 'isEpochSet' flag
// If Epoch is set externally from MainWindow, the flag will be true
// Otherwise, Epoch will be set internally
QDateTime m_epoch;
bool m_isEpochSet;
// Flag to indicate if DataLogger is ready for data logging
// True if InitializeDataLogger was successful
bool m_isReady;
// Flag to tell the run() loop to keep logging data
bool m_keepLogging;
// Root directory for creating files
QString m_rootDirectory;
// QFile m_EMfile;
// QFile m_ECGfile;
// QFile m_EPOSfile;
// QFile m_FrameFile;
// QFile m_LogFile;
// QFile m_ErrorFile;
// QFile m_NoteFile;
// QTextStream m_textStream;
const int m_prec = 4; // precision for print operations
const int m_prec2 = 6;
std::vector< std::shared_ptr<QFile> > m_files;
std::vector< std::shared_ptr<QTextStream> > m_TextStreams;
std::vector< std::shared_ptr<QDataStream> > m_DataStreams;
};
inline const QString getCurrTimeStr();
inline const QString getCurrDateTimeStr();
#endif // DATALOGGERTHREAD_H
| 4,771 | C | 30.394737 | 91 | 0.608258 |
liamczm/OmniverseExtensionDev/exts/my.light.start/my/light/start/my_light_ui_model.py | __all__ = ["PrimPathUIModel"]
from pxr import Tf,Usd,UsdGeom,UsdLux
import omni.ui as ui
import omni.usd
class PathValueItem(ui.AbstractItem):
"""单个Item,决定类型"""
def __init__(self):
super().__init__()
self.path_model = ui.SimpleStringModel()
self.path_children = []
class PrimPathUIModel(ui.AbstractItemModel):
"""代表名称-数值表的model"""
def __init__(self):
super().__init__()
# 示例参数
self._children = PathValueItem()
def get_item_children(self, item):
"""当widget询问时返回所有子项"""
if item is not None:
return []
# return self._children
# return item.children
def get_item_value_model_count(self, item):
"""列数"""
return 1
def get_item_value_model(self, item, column_id):
"""
Return value model.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel.
"""
return item.path_model
class TreeViewLayout(omni.ext.IExt):
"""灯光TreeView"""
def __init__(self):
super().__init__()
# self._usd_context = omni.usd.get_context()
# self._selection = self._usd_context.get_selection()
# self._events = self._usd_context.get_stage_event_stream()
# self._stage_event_sub = self._events.create_subscription_to_pop(
# self._on_stage_event, name="customdataview"
# )
# self._selected_primpath_model = ui.SimpleStringModel("-")
def InitLayout(self):
with ui.VStack():
with ui.ScrollingFrame(
height=200,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="LtTreeView",
):
self._model = PrimPathUIModel()
ui.TreeView(self._model, root_visible=False, style={"margin": 0.5}) | 2,010 | Python | 31.967213 | 84 | 0.572637 |
liamczm/OmniverseExtensionDev/exts/my.light.start/my/light/start/extension.py | import omni.ext
import omni.ui as ui
import omni.usd
import carb
import omni.kit.commands
from omni.kit.viewport.utility import get_active_viewport_window
# 加载viewport_scene
from .viewport_scene import ViewportLtInfo
from .my_light_model import LtStartSceneModel
from .my_light_ui_model import PrimPathUIModel
from .my_light_ui_manipulator import Layout as layt
from .my_light_ui_model import TreeViewLayout as tVlt
from .my_light_list_model import LightListModel as lst
class MyExtension(omni.ext.IExt):
def on_startup(self, ext_id):
# 得到当前usd context
self._usd_context = omni.usd.get_context()
self._selection = self._usd_context.get_selection()
# 注册事件
self._events = self._usd_context.get_stage_event_stream()
self._stage_event_sub = self._events.create_subscription_to_pop(
self._on_stage_event, name="customdataview"
)
# self._customdata_model = CustomDataAttributesModel()
self._selected_primpath_model = ui.SimpleStringModel("-")
self._selected_Prim_Family = ui.SimpleStringModel()
self._window = ui.Window("ipolog Selection Info", width=300, height=200)
# 得到当前stage
self.current_stage = self._usd_context.get_stage()
#self.list_model = lst(str(self.current_stage))
# 得到当前激活的视口
viewport_window = get_active_viewport_window()
# 如果没有视口记录错误
if not viewport_window:
carb.log_error(f"No Viewport to add {ext_id} scene to")
return
# 建立scene(覆盖默认的)
self._viewport_scene = ViewportLtInfo(viewport_window,ext_id)
self._window = ui.Window("HNADI Light Studio", width=300, height=300)
#窗口UI
with self._window.frame:
with ui.VStack():
with ui.HStack(height=35):
# Pic 占位
ui.Circle(
name = "iconHolder",
radius = 20,
size_policy = ui.CircleSizePolicy.FIXED,
alignment = ui.Alignment.CENTER,
)
with ui.VStack():
ui.Label("LightType")
self._selected_Prim_Family = ui.StringField(model=self._selected_primpath_model,height=20, read_only=True)
self._selectedPrimName = ui.StringField(model=self._selected_primpath_model, height=20, read_only=True)
with ui.VStack():
ui.Label("Profiles:", height=20)
#tVlt.InitLayout(self)
#ui.TreeView(self.list_model,root_visible = False)
with ui.VStack():
ui.Label("Lights", height=20)
layt.InitLayout(self)
# 创建按钮
with ui.HStack():
ui.Button("Create a set of lights",clicked_fn=lambda: click_lt())
ui.Button("Select",clicked_fn=lambda:select_type())
def click_lt():
omni.kit.commands.execute('CreatePrimWithDefaultXform',
prim_type='Xform',
attributes={})
omni.kit.commands.execute('CreatePrim',
prim_type='RectLight',
attributes={'width': 100, 'height': 100, 'intensity': 15000})
omni.kit.commands.execute('MovePrim',
path_from='/World/RectLight_01',
path_to='/World/Xform/RectLight_01')
def select_type(self):
selection = self._selection.get_selected_prim_paths()
sel_type = selection.select_all_prims(self,type_names="")
# tree_view = ui.TreeView(
# self._customdata_model,
# root_visible=False,
# header_visible=False,
# columns_resizable=True,
# column_widths=[ui.Fraction(0.4), ui.Fraction(0.6)],
# style={"TreeView.Item": {"margin": 4}},
# )
def _on_stage_event(self, event):
"""只跟踪选取变动"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_selection_changed()
def _on_selection_changed(self):
"""选择变动后读取信息"""
selection = self._selection.get_selected_prim_paths()
stage = self._usd_context.get_stage()
# print(f"== selection changed with {len(selection)} items")
if selection and stage:
#-- set last selected element in property model
if len(selection) > 0:
path = selection[-1]
family = selection
self._selected_primpath_model.set_value(path)
self._selected_Prim_Family.set_value(family)
def on_shutdown(self):
#清空自定义scene
if self._viewport_scene:
self._viewport_scene.destroy()
self._viewport_scene = None
print("[my.light.start] MyExtension shutdown")
| 5,093 | Python | 40.414634 | 130 | 0.549185 |
liamczm/OmniverseExtensionDev/exts/my.light.start/my/light/start/viewport_scene.py | from omni.ui import scene as sc
import omni.ui as ui
from .my_light_manipulator import LtStartSceneManipulator
from .my_light_model import LtStartSceneModel
class ViewportLtInfo():
def __init__(self,viewportWindow,ext_id) -> None:
self.sceneView = None
self.viewportWindow = viewportWindow
with self.viewportWindow.get_frame(ext_id):
self.sceneView = sc.SceneView()
# 向SceneView中加载Manipulator
with self.sceneView.scene:
LtStartSceneManipulator(model = LtStartSceneModel())
self.viewportWindow.viewport_api.add_scene_view(self.sceneView)
def __del__(self):
self.destroy()
def destroy(self):
if self.sceneView:
self.sceneView.scene.clear()
if self.viewportWindow:
self.viewportWindow.viewport_api.remove_scene_view(self.sceneView)
self.viewportWindow = None
self.sceneView = None | 958 | Python | 28.968749 | 82 | 0.653445 |
liamczm/OmniverseExtensionDev/exts/my.light.start/my/light/start/my_light_list_model.py | import omni.ui as ui
class LightListItem(ui.AbstractItem):
def __init__(self,text:str):
super().__init__()
self.sub_model = ui.SimpleStringModel(text)
class LightListModel(ui.AbstractItemModel):
def __init__(self,*args):
super().__init__()
self._children = [LightListItem(t) for t in args]
def get_item_children(self,item):
if item is not None:
return[]
else:
return self._children
def get_item_value_model_count(self,item):
return 1
def get_item_value_model(self,item,id):
return item.sub_model | 540 | Python | 24.761904 | 51 | 0.675926 |
liamczm/OmniverseExtensionDev/exts/my.light.start/my/light/start/my_light_manipulator.py | from omni.ui import scene as sc
import omni.ui as ui
from warp.types import transform
from omni.ui import color as cl
class LtStartSceneManipulator(sc.Manipulator):
# 包含model作为参数
def on_build(self):
"""model变动即呼起,重建整个manipulator"""
# 没有model返回
if not self.model:
return
# 没有选择返回
if self.model.get_item("name") == "":
return
# 更新位置信息(通过model)
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform = sc.Matrix44.get_translation_matrix(*position)):
# 屏幕上显示名称信息
with sc.Transform(scale_to = sc.Space.SCREEN):
sc.Label(f"Path:{self.model.get_item('name')}",color=cl("#76b900"),size = 20)
#sc.Label(f"Path:{self.model.get_item('intensity')}")
#sc.Label(f"Path:{self.model.get_item('name')}")
def on_model_updated(self,item):
"""model中某项目更新呼起该方法,核心,重建Manipulator"""
# manipulator自带的方法,删除旧的重新执行on_build生成新的manipulator
self.invalidate()
| 1,067 | Python | 33.451612 | 93 | 0.613871 |
liamczm/OmniverseExtensionDev/exts/my.light.start/my/light/start/my_light_model.py | from pxr import Tf,Usd,UsdGeom,UsdLux
import omni.ui as ui
from omni.ui import scene as sc
import omni.usd
class LtStartSceneModel(sc.AbstractManipulatorModel):
def __init__(self)->None:
super().__init__()
self.prim = None
self.current_path=None
self.stage_listener = None
self.position = LtStartSceneModel.PositionItem()
self.intensity = LtStartSceneModel.IntensityItem()
# 保存当前UsdContext
self.usd_context = omni.usd.get_context()
# self._light = None
# 追踪选择变动
self.events = self.usd_context.get_stage_event_stream()
# 自定义on_stage_event
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event,name = "Light Selection Update"
)
def on_stage_event(self,event):
"""事件方法,只包含了选择变动"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
# 若选择变动,得到新选中物体的路径
prim_path = self.usd_context.get_selection().get_selected_prim_paths()
if not prim_path:
self.current_path = ""
# 如果没有路径,返回_item_changed
self._item_changed(self.position)#_item_changed是自带方法,代表item改变
return
# 得到当前stage内选中的prim
stage = self.usd_context.get_stage()
prim = stage.GetPrimAtPath(prim_path[0])
# 如果选中的prim不是Imageable激活stage_listener继续监听选择变动
if not prim.IsA(UsdGeom.Imageable):
self.prim = None
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
# TODO 是啥?自定义notice_changed
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged,self.notice_changed,stage)
self.prim = prim
self.current_path = prim_path[0]
# 位置变动,新选中物体有新位置
self._item_changed(self.position)
class PositionItem(sc.AbstractManipulatorItem):
"""该model item代表位置"""
def __init__(self) -> None:
super().__init__()
self.value = [0,0,0]
class IntensityItem(sc.AbstractManipulatorItem):
"""该model item代表灯光强度"""
def __init__(self) -> None:
super().__init__()
self.value = 0.0
def get_item(self,identifier):
"""根据标识符得到数据项目"""
if identifier == "name":
return self.current_path
elif identifier == "position":
return self.position
elif identifier == "intensity":
return self.intensity
def get_as_floats(self,item):
"""引用自定义方法得到项目数据为浮点数"""
if item == self.position:
# 索取位置
return self.get_position()
elif item == self.intensity:
# 索取强度
return self.get_intensity()
# TODO 不懂
if item:
# 直接从item得到数值
return item.value
return []
def get_position(self):
"""得到当前选中物体位置的方法,用来作为信息显示的位置"""
# 得到当前stage
stage = self.usd_context.get_stage()
if not stage or self.current_path == "":
return [0,0,0]
# 直接从USD得到位置
prim = stage.GetPrimAtPath(self.current_path)
position = prim.GetAttribute('xformOp:translate').Get()
return position
# 得到强度待定
def get_intensity(self,time:Usd.TimeCode):
"""得到灯光强度"""
stage = self.usd_context.get_stage()
if not stage or self.current_path == "":
return
prim = stage.GetPrimAtPath(self.current_path)
intensity = prim.GetIntensityAttr().Get(time)
#intensity = self._light.GetIntensityAttr().Get(time)
return intensity
# 循环所有通知直到找到选中的
def notice_changed(self,notice:Usd.Notice,stage:Usd.Stage)->None:
"""Tf.Notice呼起,当选中物体变化"""
#TODO 为什么只改动位置
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
def destroy(self):
self.events = None
self.stage_event_delegate.unsubscribe()
| 4,208 | Python | 31.882812 | 109 | 0.573194 |
liamczm/OmniverseExtensionDev/exts/my.light.start/my/light/start/my_light_ui_manipulator.py | import omni.ui as ui
import omni.usd
field = ui.StringField()
class Layout(omni.ext.IExt):
"""TreeView示例"""
def InitLayout(self):
with ui.ScrollingFrame(
height=200,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._model = Model("Root", "Items")
ui.TreeView(self._model, root_visible=False, style={"margin": 0.5})
# model = MyStringModel()
# field.model = model
# ui.StringField(field.model)
class Item(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
self.children = None
class Model(ui.AbstractItemModel):
def __init__(self, *args):
super().__init__()
self._children = [Item(t) for t in args]
# # 编辑时的颜色
# def begin_edit(self):
# custom_treeview.set_style({"color":0xFF00B976})
# def end_edit(self):
# custom_treeview.set_style({"color":0xFFCCCCC})
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
if not item.children:
item.children = [Item(f"Child #{i}") for i in range(5)]
return item.children
return self._children
def get_item_value_model_count(self, item):
"""The number of columns"""
return 1
def get_item_value_model(self, item, column_id):
"""
Return value model.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel.
"""
return item.name_model
# class MyStringModel(ui.SimpleStringModel):
# def __init__(self):
# super().__init__()
# # 开始编辑时变色
# def begin_edit(self):
# field.set_style({"color":0xFF00B976})
# def end_edit(self):
# field.set_style({"color":0xFFCCCCC})
| 2,072 | Python | 29.940298 | 80 | 0.590734 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.