I would like to realize the code taken from this answer and simulate a click without simulating mouse movement inside non-java app window. I know about JNA which, in theory, should have all WinAPI functions. The latest JNA version is 5.6.0 but I didn't find something similar to MAKELPARAM.
POINT pt;
pt.x = 30; // This is your click coordinates
pt.y = 30;
HWND hWnd = WindowFromPoint(pt);
LPARAM lParam = MAKELPARAM(pt.x, pt.y);
PostMessage(hWnd, WM_RBUTTONDOWN, MK_RBUTTON, lParam);
PostMessage(hWnd, WM_RBUTTONUP, MK_RBUTTON, lParam);
Does anyone know if there is something similar in Java or JNA?
Please do not suggest Java Robot. I have tried it, but unfortunately the mouse cursor moves (disappears) by about a milliseconds from the starting position to the point where you need to click and back to the starting position.
public void performClick(int x, int y) {
Point origLoc = MouseInfo.getPointerInfo().getLocation();
robot.mouseMove(x, y);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.mouseMove(origLoc.x, origLoc.y);
}
Short answer:
No, but you can easily do it yourself.
Long answer:
As you said, "JNA ... in theory, should have all WinAPI functions." What is important to recognize is that there are two components to JNA, the core functionality that allows Java to interface with native (C) code via libffi, contained in the jna artifact; and the user-contributed platform mappings (including many WinAPI mappings) in jna-platform. So JNA has the ability to map anything in WinAPI but someone needs to contribute it to the project to share their work with others.
Now regarding MAKELPARAM, it is simply a macro. You can see the source code for it here:
#define MAKELPARAM(l, h) ((LPARAM)(DWORD)MAKELONG(l, h))
It calls the MAKELONG macro with (WORD) inputs l and h, casts that to a DWORD, and further casts that to a LPARAM.
The MAKELONG macro is defined in Windef.h:
#define MAKELONG(a, b) ((LONG)(((WORD)(((DWORD_PTR)(a)) & 0xffff)) | ((DWORD)((WORD)(((DWORD_PTR)(b)) & 0xffff))) << 16))
JNA does have the LPARAM type mapped, present in the WinDef class. It takes a long argument to the constructor.
So you must simply take two 16-bit values l and h, map them to the rightmost 32 bits of a long, and send that long to the LPARAM constructor.
So the solution you seek is:
// int args are needed for unsigned 16-bit values
public static WinDef.LPARAM makeLParam(int l, int h) {
// note the high word bitmask must include L
return new WinDef.LPARAM((l & 0xffff) | (h & 0xffffL) << 16);
}
Related
it's my first time with CGAL, some of you may argue why do I have to learn CGAL from something like that, but it's a new project that I must do (and... yes, I must use CGAL and Java combined) :/ Long story short... I only have:
Two double arrays, representing x and y coordinates of my vertices. Let's call them double[] x, y;.
Both arrays have S random values.
Two vertices, u and w are connected if distance(x[u], y[u], x[w], y[w]) < CONSTANT (ofc. I do distanceSquared(x[u], y[u], x[w], y[w]) < CONSTANT_SQUARED, so I avoid to call sqrt()).
x and y are filled randomly with values from 0 to UPPER_LIMIT, no other infos are given.
Question, do x and y describes a connected graph?
Right now I have two algoritms:
Algorithm 1:
Build adjacency list (Arraylist<Integer>[] adjLists;) for each vertex (only upper triangular matrix explored). Complexity O(|V|^2) (V = vertices set).
Recursive graph exploration, vertex marking and counting, if visited vertex equals S my graph have only one connected component, my graph is connected. Complexity O(|E|) (E = edges set).
Algorithm 2:
private static boolean algorithmGraph(double[] x, double[] y) {
int unchecked, inside = 0, current = 0;
double switchVar;
while (current <= inside && inside != S - 1) {
unchecked = inside + 1;
while (unchecked < S) {
if ((x[current] - x[unchecked]) * (x[current] - x[unchecked]) + (y[current] - y[unchecked]) * (y[current] - y[unchecked]) <= CONSTANT_SQUARED) {
inside++;
// switch x coordinates | unchecked <-> inside
switchVar = x[unchecked];
x[unchecked] = x[inside];
x[inside] = switchVar;
// switch y coordinates | unchecked <-> inside
switchVar = y[unchecked];
y[unchecked] = y[inside];
y[inside] = switchVar;
}
unchecked++;
}
current++;
}
return inside == S - 1;
}
Funny thing the second one is slower, I do not use data structures, the code is iterative and in-place but the heavy use of switch makes it slow as hell.
The problem spec changed and now I must do it with CGAL and Java, I'll read the whole "https://github.com/CGAL/cgal-swig-bindings" to learn how to use CGAL within Java.... but I'd like some help about this specific instance of CGAL code... Are there faster algorithms already implemented in CGAL?
Thank you for your times guys! Happy coding!
I believe that, without a method of spatial indexing, the best performance you are going to achieve in the worst-case-scenario (all connected) is going to be O(n*(n-1)/2).
If you can afford to build a spatial index (have enough memory to pay for the boost in speed), you may consider R-tree and variants - insertion is O(n) searching is O(log2(n)): this will get your "outlier detection by examining distances" approach for a cost of of O(n*log2(n)) in the worst-case-scenario.
A notable result
I'm trying to use the OpenCV library (Java version). I found some code written in C++and I'm trying to rewrite it to Java. However, I can't understand one construction.
Here is the C++ code:
void scaleDownImage(cv::Mat &originalImg,cv::Mat &scaledDownImage )
{
for(int x=0;x<16;x++)
{
for(int y=0;y<16 ;y++)
{
int yd =ceil((float)(y*originalImg.cols/16));
int xd = ceil((float)(x*originalImg.rows/16));
scaledDownImage.at<uchar>(x,y) = originalImg.at<uchar>(xd,yd);
}
}
}
I can't understand how to translate this line:
scaledDownImage.at<uchar>(x,y) = originalImg.at<uchar>(xd,yd);
have a look at the Mat accessor functions here: http://docs.opencv.org/java/org/opencv/core/Mat.html#get(int,%20int)
so, to translate your example:
scaledDownImage.at<uchar>(r,c) = originalImg.at<uchar>(rd,cd); // c++
would be :
byte [] pixel = new byte[1]; // byte[3] for rgb
originalImg.get( rd, cd, pixel );
scaledDownImage.put( r,c, pixel );
note, that it's (row,col), not (x,y) !
uchar = unsigned char.
This statement:
scaledDownImage.at<uchar>(x,y)
returns unsigned char(I guess, pointer) at positions(x,y).
So, in java it will be like:
unsigned char scaledDownImageChar = scaledDownImage.charAt(x, y);
scaledDownImageChar = originalImg.charAt(x, y);
This is not real code, just an example.
It is called template, search generics for java.
Basically, the "at" method´s code uses some type T
(don´t know if it is called T or something else)
which could be int, float, char, any class...
just something which is unspecified at the moment
And in this case, you´re calling the method with T being an uchar
private static void convert(int x) {
// assume we've passed in x=640.
final int y = (x + 64 + 127) & (~127);
// as expected, y = 768
final int c = y;
// c is now 320?!
}
Are there any sane explanations for why the above code would produce the values above? This method is called from JNI. The x that is passed in is originally a C++ int type that is static_cast to a jint like so: static_cast<jint>(x);
In the debugger, with the breakpoint set on the y assignment, I see x=640. Stepping one line, I see y=768. Stepping another line and c=320. Using the debugger, I can set the variable c = y and it will correctly assign it 768.
This code is single threaded and runs many times per second and the same result is always observed.
Update from comments below
This problem has now disappeared entirely after a day of debugging it. I'd blame it on cosmic rays if it didn't happen reproducibly for an entire day. Oddest thing I've seen in a very long time.
I'll leave this question open for a while in case someone has some insight on what could possibly cause this.
Step 01: compile it right, see comments under your post.
if needed i with this code it will go:
C# Code:
private void callConvert(object sender, EventArgs e)
{
string myString = Convert.ToString(convert123(640));
textBox1.Text = myString;
}
private static int convert123(int x) {
// assume we've passed in x=640.
int y = (x + 64 + 127) & (~127);
// as expected, y = 768
int c = y;
// c is now 320?!
return (c);
}
but its a c# code
and a tipp for you NEVER call your funktion with a name that is used in the compiler as an standart.
convert is in the most langues used.
(system.convert)
Have you set c to 320 recently? If so, it may have been stored in some memory and the compiler may have reassigned it to what it thought it was and not what it should be. I am, in part, guessing though.
It looks like problem of memory byte size of temporary variables if program is optimized for memory usage. Debugger may not be reliable. I see if the temporary ~127 is store in a byte, then you may reach at the scenario you observed. It all depends on what is ~127 is stored in at run time.
I've been trying to make a dynamic light system in java, without using libraries. For some reason, though, it seems I can't get light to run efficiently. It flickers and lags a ton. I'm doing this with no previous understanding of lighting engines in games, so I'm open to suggestions. Here is my current update method:
public void updateLight( ArrayList<Block> blocks )
{
//reset light
light.reset();
//add the x and y of this light
light.addPoint( x, y );
//precision for loops
int ires = 1;
int jres = 2;
for( int i = 0; i < width; i += ires )
{
//get radians of current angle
float rdir = (float)Math.toRadians( dir + i - width/2 );
//set up pixel vars
int px, py;
for( int j = 0; j < length; j += jres )
{
//get position of pixel
px = (int)ZZmath.getVectorX( x, rdir, j );
py = (int)ZZmath.getVectorY( y, rdir, j );
//if point gets found
boolean foundpoint = false;
for( int n = 0; n < blocks.size(); n ++ )
{
//check if block is solid
//also check that collision is possible really quickly for efficiency
if( blocks.get( n ).solid )
{
//get info on block
int bx = blocks.get( n ).x;
int by = blocks.get( n ).y;
//quick trim
if( Math.abs( bx - px ) <= 32 && Math.abs( by - py ) <= 32 )
{
int bw = blocks.get( n ).w;
int bh = blocks.get( n ).h;
if( ZZmath.pointInBounds( px, py, bx, by, bw, bh ) )
{
//add point to polygon
light.addPoint( px, py );
//found point
foundpoint = true;
}
}
}
}
//if a point is found, break
if( foundpoint )
{
break;
}
//if at end of loop, add point
//loose definition of "end" to prevent flickers
if( j >= length - jres*2 )
{
light.addPoint( px, py );
}
}
}
}
This modifies a polygon that displays for light. I'll change that later. Any idea of ways I can make this run better? Also, no, no libraries. I don't have anything against them, just don't want to use one now.
You implementation doesn't appear to use much of the stuff I see here:
http://www.cs.utah.edu/~shirley/books/fcg2/rt.pdf
I'd recommend digesting this completely. If your objective is to understand ray tracing deeply, that's how it should be done.
Maybe your objective was to learn by writing your own raytracer. In my experience I would end up rewriting this code several times and still not get it completely right. It's good to get your hands dirty but it's not necessarily the most effective way to go about things.
Overall it looks like you need to study (object oriented) programming concepts, and take a data structures and algorithms course.
The biggest thing is readability. Document your code, for your future self if no one else. This means Clear comments before and during updateLight(). The existing comments are alright (though they paraphrase the code more than justify it), but "really quickly for efficiency" is a lie.
For a small issue of readability that could be a tiny drag on performance, make a local variable for blocks.get(n). Name it something short but descriptive, save typing and only make one method call to retrieve it.
"if at end of loop": I have no idea which loop you mean, and the for loops have definite ends. A comment }//end for or }//end for width is often helpful.
Checking if the block is solid is unnecessary! Just store your blocks in two lists, and only go through the solid blocks. Even if you have some desire to have flickering blocks, one remove and add is cheaper than O(width*length*numbernotsolid) extra work.
There are many ways you could structure how the blocks are stored to facilitate quick testing. You only want or need to test blocks whose coordinates are near to a particular light. The basic strategy is divide the space into a grid, and sort the blocks based on what section of the grid they fall into. Then when you have light in a particular section of the grid, you know you only need to test blocks in that section (and possibly a neighboring section - there are details depending on their width and the light's).
I have no idea whether that is along the lines of the right approach or not. I don't know much about raytracing, although it is or used to be rather slow. It looks like you have a decent naive implementation. There might be a slightly different naive approach that is faster and some more difficult (to code to completion) algorithms that are moderately yet more fast.
Also, I see no need to do this breadth first. Why not solve for one line (you call them pixels?) at a time. Count the number of times this code calls Math.toRadians. It looks like it's just an extraneous line because you could work along the same angle until ready for the next.
I need your help, and thank you for reading my question!
I am currently writing a java Programm that will use an Direket Form 2 Transposed Filter. I know that the function filter in Matlab will do that just fine, but i have to use Java.
So does anyone know you to implement this Direkt Form 2 Transposed , this Math Function:
y(n) = b(1)*x(n) + b(2)*x(n-1) + ... + b(nb+1)*x(n-nb)
- a(2)*y(n-1) - ... - a(na+1)*y(n-na)
in any Programmm Language? All it takes is hopefully a point to the wrigth direction so i can figure it out! Maybe there is an C Lib that implements some of the matlab functions, just anything.
So thank you for your time
yours Elektro
Follow up:
I tried for a couple of days to understand your function but i couldn't.
This is the function from Matlab: filter
http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/ref/filter.html&http://www.google.de/search?hl=de&q=filter+matlab&btnG=Google-Suche&meta=&aq=f&oq=
All i know is that i use in matlab the function like this:
newArray = filter(1,LPC_Faktor,OldArray)
All I have to do is to implement the filter function.
So could you help again?
Thanks
Elektro
Whatever language you use, the direct form II transposed structure is quite simple.
For example, in C, it could be something like:
float myFilter( float u)
{
static float[nb] x = {0,0,0,...,0); // initialize x
static float[na] y = {0,0,0,...,0); // initialize y
static float b1 = ....; // put b(1) here
static float[nb] b = {...,...,...,...,...}; // put b(2) to b(nb+1) here
static float[na] a = {...,...,...,...,...}; // put a(2) to a(na+1) values here
// initialization
float sum = 0;
int i=0;
// compute the value
for(i=0;i<nb;i++)
sum += b[i]*x[i];
for(i=0;i<na;i++)
sum -= a[i]*y[i];
sum += b1*u;
// prepare the values for the next time
for(i=1;i<nb;i++)
x[i] = x[i-1];
x[0] = u;
for(i=1;i<na;i++)
y[i] = y[i-1];
y[0] = sum;
// return the value
return sum;
}
I did not test the code, but it is something like that.
The Direct Form II transposed is the simplest form to implement a FIR filter (numerically, and specially in fixed-point, it is not the best, but it is the form that requires the less operations).
Of course, it is possible to have a better implementation (with cycling array, for example). If needed, I can provide it, too.
EDIT: I answered too quickly. The algorithm you provide
y(n) = b(1)x(n) + b(2)x(n-1) + ... + b(nb+1)x(n-nb) - a(2)y(n-1) - ... - a(na+1)*y(n-na)
is not the Direct Form II, but the direct form I. It requires to store na+nb values (n is the order of your filter), whereas the Direct Form II requires only max(na,nb).
The algorithm used for the Direct Form II is
e(n) = u(n) - a(1)*e(n-1) - a(2)*e(n-2) - ... - a(na)*e(n-na)
y(n) = b(1)*e(n-1) + b(2)*e(n-2) + ... + b(nb)*e(n-nb)
Tell me if you need this form or not.
after long searching i found the answer,
thank you showed the rigth way:
filter(int ord, float *a, float *b, int np, float *x, float *y)
{
int i,j;
y[0]=b[0] * x[0];
for (i=1;i<ord+1;i++)
{
y[i]=0.0;
for (j=0;j<i+1;j++)
y[i]=y[i]+b[j]*x[i-j];
for (j=0;j<i;j++)
y[i]=y[i]-a[j+1]*y[i-j-1];
}
/* end of initial part */
for (i=ord+1;i<np+1;i++)
{
y[i]=0.0;
for (j=0;j<ord+1;j++)
y[i]=y[i]+b[j]*x[i-j];
for (j=0;j<ord;j++)
y[i]=y[i]-a[j+1]*y[i-j-1];
}
} /* end of filter */