Matrix conversion OpenGL ES 2.0 - matrix

I would like to know how I can use this matrix in my custom GL renderer to implement pinch zoom. I keep getting an error that is telling me I cannot set an opengl.Matrix which is type float[16] with the Matrix object I am changing in my activity below. What is the correct way to pass my graphics.matrix through such that it will update my view correctly? As a workaround I am passing the newDist value to my renderer, but then every time I touch the screen with 2 fingers, it resets the eyeZ value, so I think I really need to get this matrix to work so it holds my zoom values.
#Override public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
Log.d(TAG, "mode=DRAG");
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
Log.d(TAG, "oldDist=" + oldDist);
if (oldDist > 10f) {
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
Log.d(TAG, "mode=ZOOM");
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
Log.d(TAG, "mode=NONE");
break;
case MotionEvent.ACTION_MOVE:
if (mode == ZOOM) {
final float newDist = spacing(event);
Log.d(TAG, "newDist=" + newDist);
if (newDist > 10f) {
matrix.set(savedMatrix);
float scale = newDist / oldDist;
matrix.postScale(scale, scale, mid.x, mid.y);
mGLSurfaceView.queueEvent(new Runnable() {
#Override
public void run() {
mGLSurfaceView.setMyMatrix(newDist);
Log.d(TAG, "runnable exists");
}
});
}
}
break;
}
return true; // indicate event was handled
}

Related

pointerIndex out of range exception came whenever i touch the event Android multitouch

Whenever i touch the event call and pointer index exception came and crash the app in android xamarin forms
/** Determine the space between the first two fingers */
private float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return (float)Math.sqrt(x * x + y * y);
}
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
ImageView view = (ImageView) v;
dumpEvent(event);
// Handle touch events here...
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
Log.d(TAG, "mode=DRAG");
mode = DRAG;
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
Log.d(TAG, "oldDist=" + oldDist);
if (oldDist > 10f) {
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
Log.d(TAG, "mode=ZOOM");
}
}

How to "refresh" TListBox?

I'm creating an app which shows bill numbers, like the one you see at Mcdonald's. A POS system send bill numbers to my app and the numbers are showed in a TListBox called "ListBoxPrep". Then, when the POS system sends my app the number of a bill to be removed, my app gets rid of it from "ListBoxPrep" and add it to "ListBoxReady". Every communication between the POS and my app is done via TCP connection and I have no problem with it.
The problem I'm facing is that I still see the number remain in "ListBoxPrep" even after deleting it by "pItem->Free();". "pItem" is a pointer of TListBoxItem. I want the numbers disappear as soon as my app receives the "delete signal" from the POS and especially without user's interation such as clicking the panel etc. I think of using TTimer, but I have no idea how to make "ListBoxPrep" refresh by itself. Do you have any idea to do that? Any suggestion would be appreciated. I'm using RAD Studio 10.4.
After my app received the "delete signal" from the POS, I still see the numbers at right side. They are supposed to disappear.
As soon as I click the "ListBoxPrep", the numbers disappear.
void __fastcall TForm1::IdTCPServerExecute(TIdContext *AContext)
{
//We receive data: POS --> Screen(PC)
String sentDataFromPOS = AContext->Connection->Socket->ReadLn();
if(sentDataFromPOS .IsEmpty())
{
ShowMessage("Data sent from POS is empty!");
return;
}
// 1. Find an order number to move to the right (prep -> ready)
int indexOrderToRemove = ListBoxPrep->Items->IndexOf(sentDataFromPOS);
// 2. Add the order number to the "Ready list"
addNumberToReady(sentDataFromPOS);
// 3. Remove the order from the "Prep list"
ListBoxPrep->BeginUpdate();
TListBoxItem* pItem = ListBoxPrep->ItemByIndex(indexOrderToRemove);
pItem->Free(); // HERE I have a problem
// test: To refresh the screen
LayoutLeft->Visible = false;
LayoutLeft->Visible = true;
/*
ListBoxPrep->Enabled = false;
ListBoxPrep->Visible = false;
ListBoxPrep->Enabled = true;
ListBoxPrep->Visible = true;
ListBoxPrep->Repaint();
*/
ListBoxPrep->EndUpdate();
}
TIdTCPServer is a multi-threaded component. Its OnExecute event is called in the context of a worker thread. As such, it MUST synchronize with the main UI thread when accessing UI controls (that goes for ShowMessage() too, BTW). You can use the RTL's TThread::Synchronize() (synchronous) or TThread::Queue() (asynchronous) method for that.
Also, you should not be Free()'ing the TListBoxItem objects directly. You have the index of the desired item, you can use ListBoxPrep->Items->Delete() instead.
If you are using one of the clang-based compilers, try something more like this:
void __fastcall TForm1::IdTCPServerExecute(TIdContext *AContext)
{
//We receive data: POS --> Screen(PC)
String sentDataFromPOS = AContext->Connection->Socket->ReadLn();
if (sentDataFromPOS.IsEmpty())
{
TThread::Synchronize(nullptr,
[](){ ShowMessage("Data sent from POS is empty!"); }
);
return;
}
TThread::Queue(nullptr, // or Synchronize(), your choice...
[=, this](){ this->orderIsReady(sentDataFromPOS); }
);
}
void __fastcall TForm1::orderIsReady(String orderNumber)
{
// 1. Find an order number to move to the right (prep -> ready)
int indexOrderToRemove = ListBoxPrep->Items->IndexOf(orderNumber);
// 2. Add the order number to the "Ready list"
addNumberToReady(orderNumber);
// 3. Remove the order from the "Prep list"
if (indexOrderToRemove != -1)
ListBoxPrep->Items->Delete(indexOrderToRemove);
}
If, on the other hand, you are using the "classic" Borland compiler, then try this instead:
struct orderHelper
{
String orderNumber;
orderHelper(const String &orderNumber)
: orderNumber(orderNumber)
{
}
void __fastcall orderIsReady()
{
Form1->orderIsReady(orderNumber);
}
};
void __fastcall TForm1::orderIsEmpty()
{
ShowMessage("Data sent from POS is empty!");
}
void __fastcall TForm1::IdTCPServerExecute(TIdContext *AContext)
{
//We receive data: POS --> Screen(PC)
String sentDataFromPOS = AContext->Connection->Socket->ReadLn();
if (sentDataFromPOS.IsEmpty())
{
TThread::Synchronize(NULL, &orderIsEmpty);
return;
}
orderHelper helper(sentDataFromPOS);
TThread::Synchronize(NULL, &(helper.orderIsReady));
}
void __fastcall TForm1::orderIsReady(String orderNumber)
{
// 1. Find an order number to move to the right (prep -> ready)
int indexOrderToRemove = ListBoxPrep->Items->IndexOf(orderNumber);
// 2. Add the order number to the "Ready list"
addNumberToReady(orderNumber);
// 3. Remove the order from the "Prep list"
if (indexOrderToRemove != -1)
ListBoxPrep->Items->Delete(indexOrderToRemove);
}
Or this:
struct orderHelper
{
String orderNumber;
orderHelper(const String &orderNumber)
: orderNumber(orderNumber)
{
}
void __fastcall orderIsReady()
{
try {
Form1->orderIsReady(orderNumber);
} __finally {
delete this;
}
}
};
void __fastcall TForm1::orderIsEmpty()
{
ShowMessage("Data sent from POS is empty!");
}
void __fastcall TForm1::IdTCPServerExecute(TIdContext *AContext)
{
//We receive data: POS --> Screen(PC)
String sentDataFromPOS = AContext->Connection->Socket->ReadLn();
if (sentDataFromPOS.IsEmpty())
{
TThread::Synchronize(NULL, &orderIsEmpty);
return;
}
orderHelper *helper = new orderHelper(sentDataFromPOS);
TThread::Queue(NULL, &(helper->orderIsReady));
}
void __fastcall TForm1::orderIsReady(String orderNumber)
{
// 1. Find an order number to move to the right (prep -> ready)
int indexOrderToRemove = ListBoxPrep->Items->IndexOf(orderNumber);
// 2. Add the order number to the "Ready list"
addNumberToReady(orderNumber);
// 3. Remove the order from the "Prep list"
if (indexOrderToRemove != -1)
ListBoxPrep->Items->Delete(indexOrderToRemove);
}
I modified some code in IdTCPServerExecute to remove a few compile errors. Here is the code which has worked well. Thank you again, Remy Lebeau !
void __fastcall TForm1::IdTCPServerExecute(TIdContext *AContext)
{
//We receive data: POS --> Screen(PC)
String sentDataFromPos = AContext->Connection->Socket->ReadLn();
// test
//sentDataFromPos = "";
if(sentDataFromPos.IsEmpty())
{
TThread::Synchronize(nullptr,
[=](){ ShowMessage("Data sent from POS is empty!"); }
);
return;
}
TThread::Synchronize(nullptr,
// Queue doesn't make the numbers disappear. It doesn't display them at right side either .
[&, this]()
{
this->orderIsReady(sentDataFromPos);
}
);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::orderIsReady(String orderNumber)
{
// 1. Find an order to move to the right (prep -> ready)
int indexOrderToRemove = ListBoxPrep->Items->IndexOf(orderNumber);
// 2. Add an order of the same order number to the "Ready list"
addNumberToReady(orderNumber);
// 3. Remove the order from the "Prep list"
if(indexOrderToRemove != -1)
{
ListBoxPrep->Items->Delete(indexOrderToRemove);
}
}

How to get smooth animation with KeyPress event in javaFX?

I am trying to implement LEFT RIGHT movement of a rectangle shape in JavaFX. Below is my code:
public void start(Stage primaryStage) throws Exception {
AnchorPane ancPane = new AnchorPane();
final Rectangle rect = new Rectangle();
rect.setHeight(50);
rect.setWidth(50);
ancPane.getChildren().add(rect);
Scene scene = new Scene(ancPane, 400, 200, Color.GREEN);
primaryStage.setScene(scene);
primaryStage.show();
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent keyEvent) {
System.out.println("hello");
if(keyEvent.getCode().toString() == "RIGHT"){
System.out.println("Move Right");
TranslateTransition translateTransitionRight = new TranslateTransition();
translateTransitionRight.setDuration(Duration.millis(200));
translateTransitionRight.setNode(rect);
translateTransitionRight.setFromX(rect.getTranslateX());
translateTransitionRight.setToX(rect.getTranslateX()+30);
translateTransitionRight.play();
}
if(keyEvent.getCode().toString() == "LEFT"){
System.out.println("Move Left");
TranslateTransition translateTransitionRight = new TranslateTransition();
translateTransitionRight.setDuration(Duration.millis(200));
translateTransitionRight.setNode(rect);
translateTransitionRight.setFromX(rect.getTranslateX());
translateTransitionRight.setToX(rect.getTranslateX()-30);
translateTransitionRight.play();
}
}
});
}
Here when I press either LEFT/RIGHT key continuously (i.e. I don't released the key, I hold it for some times) the rectangle moves but not continuously. It pauses for a small fraction of time just after animation started. After the pause the animation continues smoothly.
How can I get rid of this pausing of animation with KeyEvents?
I would use an AnimationTimer for moving the rectangle, and just update a property representing the velocity on key pressed or key released:
final Rectangle rect = ... ;
final double rectangleSpeed = 100 ; // pixels per second
final double minX = 0 ;
final double maxX = 800 ; // whatever the max value should be.. can use a property and bind to scene width if needed...
final DoubleProperty rectangleVelocity = new SimpleDoubleProperty();
final LongProperty lastUpdateTime = new SimpleLongProperty();
final AnimationTimer rectangleAnimation = new AnimationTimer() {
#Override
public void handle(long timestamp) {
if (lastUpdateTime.get() > 0) {
final double elapsedSeconds = (timestamp - lastUpdateTime.get()) / 1_000_000_000.0 ;
final double deltaX = elapsedSeconds * rectangleVelocity.get();
final double oldX = rect.getTranslateX();
final double newX = Math.max(minX, Math.min(maxX, oldX + deltaX));
rect.setTranslateX(newX);
}
lastUpdateTime.set(timestamp);
}
};
rectangleAnimation.start();
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if (event.getCode()==KeyCode.RIGHT) { // don't use toString here!!!
rectangleVelocity.set(rectangleSpeed);
} else if (event.getCode() == KeyCode.LEFT) {
rectangleVelocity.set(-rectangleSpeed);
}
}
});
scene.setOnKeyReleased(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if (event.getCode() == KeyCode.RIGHT || event.getCode() == KeyCode.LEFT) {
rectangleVelocity.set(0);
}
}
});
UPDATE:
The AnimationTimer executes its handle method once each time a frame is rendered by the JavaFX mechanism. The long passed into the handle method is a timestamp of the render frame, in nanoseconds.
The way this works is that we keep track of the last update time. The handle(...) method computes the elapsed time since the last update, multiplies it by the rectangle's velocity, and updates the translateX of the rectangle by that amount. The AnimationTimer is always running, but initially the velocity is set to zero so the rectangle doesn't move.
The keyPressed handler simply changes the velocity: to a positive value if moving right and a negative value if moving left. The keyReleased handler sets the velocity back to zero.

My AsyncTask does not update UI smoothly (animation)

I want to make a TextView appear little by little, like animation. The problem is, the animation is not smooth. It gets stuck for a little while sometimes and then resumes. Sometimes even worse, it goes back... I mean, the TextView gets bigger and bigger but suddenly gets smaller then bigger again. Could anyone help me?
private class UnfoldTask extends AsyncTask<Integer, Integer, Integer> {
View view;
public UnfoldTask(View v) {
this.view = v;
ViewGroup.LayoutParams pa = view.getLayoutParams();
pa.height = 0;
view.setLayoutParams(pa);
}
#Override
protected Integer doInBackground(Integer... maxHeight) {
ViewGroup.LayoutParams pa = view.getLayoutParams();
while (pa.height < maxHeight[0]) {
pa.height += (int) (24 * getResources().getDisplayMetrics().density + 0.5f);
sleep(100);
publishProgress(pa.height);
}
return maxHeight[0];
}
private void sleep(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(Integer... values) {
ViewGroup.LayoutParams pa = view.getLayoutParams();
pa.height = values[0];
view.setLayoutParams(pa);
}
#Override
protected void onPostExecute(Integer result) {
ViewGroup.LayoutParams pa = view.getLayoutParams();
pa.height = result;
view.setLayoutParams(pa);
}
}
You should be using a scale animation for this. Here's an example:
ScaleAnimation animation = new ScaleAnimation(1, 2, 1, 2, centerX, centerY); // Scales from normal size (1) to double size (2). centerX/Y is the center of your text view. Change this to set the pivot point of your animation.
animation.setDuration(1000);
myTextView.startAnimation(animation);
You can use droidQuery to simplify this:
//this will set the height of myView to 0px.
$.with(myView).height(0);
//when you are ready to animate to height (in pixels):
$.with(myView).animate("{height:" + height + "}", new AnimationOptions());
Check the documentation if you want to get fancy - such as adding duration, and event callbacks. If you are still noticing non-smooth animation, consider adding the application attribute to your AndroidManifest:
android:hardwareAccelerated="true"

Slowly initialized components that cause lack of user experience

This is the view that appears when I click a button on a previous view.
The text boxes, the smiling face image and the labels are predesigned created by xCode.
Please see the image and the code of the view to clear why all the view's components are initializing very slowly and getting ready to give the last shoot that is captured by me when it is finished to be totally loaded . Moreover, It is very slow when I type letters, the letters are appearing very slowly while I am typing with the keyboard that iOS provides on every touch on the text box.
The Code of The View;
using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace IstanbulCity
{
public partial class AskForNAme : UIViewController
{
public delegate void AskForNAmeClosingDelegate (AskForNAme form);
public event AskForNAmeClosingDelegate AskForNAmeClosed;
NSObject obs1;
float scrollamount = 0.0f;
float bottomPoint = 0.0f;
float yOffset = 0.2f;
bool moveViewUp = false;
public AskForNAme () : base ("AskForNAme", null)
{
}
public override void DidReceiveMemoryWarning ()
{
// Releases the view if it doesn't have a superview.
base.DidReceiveMemoryWarning ();
// Release any cached data, images, etc that aren't in use.
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Perform any additional setup after loading the view, typically from a nib.
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(true);
obs1 = NSNotificationCenter.DefaultCenter.AddObserver (
"UIKeyboardDidShowNotification", KeyboardUpNotification);
this.tbOwnerMailAdress.ShouldReturn += TextFieldShouldReturn;
this.tbOwnerBirthDay.ShouldReturn += TextFieldShouldReturn;
this.uivGuguPhoto.Image = UIImage.FromFile ("image/fcuk.jpeg");
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(false);
obs1 = NSNotificationCenter.DefaultCenter.AddObserver (
"UIKeyboardDidShowNotification", KeyboardUpNotification);
this.tbOwnerMailAdress.ShouldReturn += TextFieldShouldReturn;
this.tbOwnerBirthDay.ShouldReturn += TextFieldShouldReturn;
this.uivGuguPhoto.Image = UIImage.FromFile ("image/fcuk.jpeg");
}
public override void ViewDidUnload ()
{
base.ViewDidUnload ();
// Clear any references to subviews of the main view in order to
// allow the Garbage Collector to collect them sooner.
//
// e.g. myOutlet.Dispose (); myOutlet = null;
ReleaseDesignerOutlets ();
}
public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
{
// Return true for supported orientations
return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown);
}
void HandleIstanbulCityViewControllerClosed (babyAge form)
{
form.DismissModalViewControllerAnimated (true);
form = null;
}
partial void tbKadikoyHallEditDidEndOnExit (MonoTouch.Foundation.NSObject sender)
{
tbIstanbulName.ResignFirstResponder ();
}
private bool TextFieldShouldReturn (UITextField tf)
{
tf.ResignFirstResponder ();
if (moveViewUp) {
ScrollTheView (false);
}
return true;
}
private void KeyboardUpNotification (NSNotification notification)
{
ResetTheView ();
RectangleF r = UIKeyboard.BoundsFromNotification (notification);
if (this.tbOwnerMailAdress.IsEditing ) {
//Calculate the bottom of the Texbox
//plus a small margin...
bottomPoint = (this.tbOwnerMailAdress.Frame.Y + this.tbOwnerMailAdress.Frame.Height + yOffset);
//Calculate the amount to scroll the view
//upwards so the Textbox becomes visible...
//This is the height of the Keyboard -
//(the height of the display - the bottom
//of the Texbox)...
scrollamount = (r.Height - (View.Frame.Size.Height - bottomPoint));
}
else if (this.tbOwnerBirthDay.IsEditing)
{
bottomPoint = (this.tbOwnerBirthDay.Frame.Y + this.tbOwnerBirthDay.Frame.Height + yOffset);
scrollamount = (r.Height - (View.Frame.Size.Height - bottomPoint));
}
else
{
scrollamount = 0;
}
//Check to see whether the view
//should be moved up...
if (scrollamount > 0) {
moveViewUp = true;
ScrollTheView (moveViewUp);
} else
moveViewUp = false;
}
private void ResetTheView ()
{
UIView.BeginAnimations (string.Empty, System.IntPtr.Zero);
UIView.SetAnimationDuration (0.3);
RectangleF frame = View.Frame;
frame.Y = 0;
View.Frame = frame;
UIView.CommitAnimations ();
}
private void ScrollTheView (bool movedUp)
{
//To invoke a views built-in animation behaviour,
//you create an animation block and
//set the duration of the move...
//Set the display scroll animation and duration...
UIView.BeginAnimations (string.Empty, System.IntPtr.Zero);
UIView.SetAnimationDuration (0.3);
//Get Display size...
RectangleF frame = View.Frame;
if (movedUp) {
//If the view should be moved up,
//subtract the keyboard height from the display...
frame.Y -= scrollamount;
} else {
//If the view shouldn't be moved up, restore it
//by adding the keyboard height back to the original...
frame.Y += scrollamount;
}
//Assign the new frame to the view...
View.Frame = frame;
//Tell the view that your all done with setting
//the animation parameters, and it should
//start the animation...
UIView.CommitAnimations ();
}
}
}
The Recent Version - Still The Same User Experience' slow!
using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace IstanbulCity
{
public partial class AskForNAme : UIViewController
{
public delegate void AskForNAmeClosingDelegate (AskForNAme form);
public event AskForNAmeClosingDelegate AskForNAmeClosed;
public AskForNAme () : base ("AskForNAme", null)
{
}
public override void DidReceiveMemoryWarning ()
{
// Releases the view if it doesn't have a superview.
base.DidReceiveMemoryWarning ();
// Release any cached data, images, etc that aren't in use.
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Perform any additional setup after loading the view, typically from a nib.
}
public override void ViewDidUnload ()
{
base.ViewDidUnload ();
// Clear any references to subviews of the main view in order to
// allow the Garbage Collector to collect them sooner.
//
// e.g. myOutlet.Dispose (); myOutlet = null;
ReleaseDesignerOutlets ();
}
public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
{
// Return true for supported orientations
return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown);
}
void HandleIstanbulCityViewControllerClosed (babyAge form)
{
form.DismissModalViewControllerAnimated (true);
form = null;
}
}
}
This does not look to be initialization related. You are adding notifications from both ViewDidAppear and ViewWillAppear. You're also always calling ResetTheView, which does animations, on every keyboard notification (even if nothing else changed).
My guess is that you are calling ResetTheView way more often that you realize - and the continuous animations are killing the performance of your application.
You can confirm this by putting a Console.WriteLine, and maybe a counter, in the ResetTheView method.

Resources