Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a function in C or C++ to do "saturation" on an integer

Tags:

c++

c

I am doing some 3D graphics and I have an open ocean. For this ocean, I have a matrix representing the sea state (i.e. wave heights) for a particular rectangular subsection of the sea. The rest of the ocean is flat. My problem is that my controlled sea, where there are waves, is positioned in the middle of open flat sea, and the discontinuity at the edges of my grid causes some bad artifacts. The reason I am only generating waves for a subsection and not the entire sea is because my noise function is prohibitively expensive to compute on the entire sea (and I know the easiest solution is to use a cheaper noise function like simplex noise, but that's not an option).

Having said that my question is really rather simple. If say I have a grid (aka matrix aka 2d array) of size 100x40, and I want to find the value for position 120x33, I simply want to take the nearest neighbour, which would be 100x33. So for any number that lies outside a given range, I want that number to saturate to lie within the given range. Is there a function in C or C++ that does this?

Edit: the position parameters are of type float

I know I can do this with some simple if statements, but it just seems like something that the standard libraries would include.

like image 339
lmirosevic Avatar asked Dec 06 '10 20:12

lmirosevic


People also ask

What is a saturation function?

Saturation functions relate the gas-aqueous capillary pressure to aqueous, gas, and entrapped gas saturations. Model options and parameters for these functions are specified through the Saturation Function Card. Every rock/soil type defined on the Rock/Soil Zonation Card must be referenced.

How do you stop an INT overflow?

You cannot prevent integer-overflow completely. If it happens, it happens. You need to be carefully at coding in the first place. But you can try to check before the assignment if an overflow can occur.

What is unsigned saturation?

Unsigned saturation specifies that the value is then clipped to its range. In other words, values less than 0 are converted to 0, more than 255 to 255.


2 Answers

And now there is, in the form of std::clamp. And I'm barely seven years late :)

like image 159
Quentin Avatar answered Oct 23 '22 02:10

Quentin


template<typename T>
T saturate(T val, T min, T max) {
    return std::min(std::max(val, min), max);
}
like image 43
etarion Avatar answered Oct 23 '22 03:10

etarion