UIView drawRect is jerky i.e., does not scroll smoothly across the screen. I have tried performing 'setNeedsDisplay' at various intervals from 200-ms to 500-ms and nothing seems
to improve the look. That is as the plots move across the screen they stop and start.
Is there any way that I can improve this to make the display more smooth?
/*==============================================================================*/
/* 'drawRect' - override function. */
/* */
/* This function is responsible for plotting cardiac waveforms (ECG) and also */
/* erases any prior ECG plot values that may be currently visible on the */
/* screen. */
/* */
/* It does this indirectly via 'EcgThread' or 'ECGErase' which send the */
/* 'setNeedsDisplay' message which triggers the 'drawRect' callback function. */
/* Once an ECG is started 'EcgThread' controls the frequency of 'drawRect' */
/* being by simple timer. (See 'EcgThread' for current timer value.) */
/* */
/*==============================================================================*/
/* Here's how the entire ECG process works: */
/* */
/* 1) User starts ECG which causes a 'send_ecg' command to be sent to */
/* 'CommThread'. */
/* */
/* 2) 'CommThread' the sends the 'send_ecg' command to the Pacemaker and then */
/* sends itself the 'read_ecg' command.*/
/* */
/* 3) The Pacemaker then starts acquiring 64 cardiac A/D samples (10-bits) per */
/* second and sends them back to 'CommThread'. */
/* */
/* 4) As samples are received by 'CommThread' (via 'read_ecg') on a streaming */
/* basis they are stored in 'ECGY' array (vertical plots) in reverse order */
/* i.e., from top to bottom (currently room for 128 samples). */
/* */
/* 5) 'EcgThread' runs continuously on a timer basis sending 'setNeedsDisplay' */
/* message which causes 'iOS' to perform callbacks to 'drawRect' who is */
/* responsible for drawing the cardiac (plots) waveforms from left to right */
/* across (horizontally) the screen. */
/* */
/* 6) 'drawRect' processes 'ECGY' bottom to top (opposite of 'CommThread') and */
/* each draw loop (plotting new values) takes about 13-millseconds. This is */
/* necessary because not doing so results in drawing upside down plots. */
/* */
/* 7) User stops ECG and 'TimerProc' sends a series of 'send_ecgstop' commands */
/* to 'CommThread' who in turn sends the 'send_ecgstop' commands to the PM. */
/* The reason why we send multiple 'send_ecgstop' is due to the streaming */
/* nature of the sending ECG samples and getting the PM to 'listen' to us. */
/* Usually stopping will go smoothly. Occasionally it may be necessary to */
/* move the Wand away, wait a few seconds and place Wand back over patient's */
/* chest (causing an interrupt) before normal operation returns. */
/* */
/*==============================================================================*/
- (void) drawRect : (CGRect) rect // Callback routine
{
int i, ii, x, xx, y; // Local array indices
fEcgDraw = YES; // Show 'drawRect' is running
[super drawRect : rect]; // Call standard handler
CGContextRef context = UIGraphicsGetCurrentContext (); // Get graphics context
CGContextSetAllowsAntialiasing (context, NO); // Turn off anti-alliaing
CGContextSetLineWidth (context, 1); // Set width of 'pen'
/*==============================================================================*/
/* 'HH' is used as a height bias in order to position the waveform plots in */
/* middle of the view (screen). */
/*==============================================================================*/
HH = 424; // Force height bias for now
if (fEcgErase == YES) // Show we erase the view?
{
CGContextSetStrokeColorWithColor (context, // Set color of 'pen'
[UIColor blackColor].CGColor); // Black (to erase)
/*==============================================================================*/
/* Erase the last screen. */
/*==============================================================================*/
for (i = 0, x = 0; i < 127; i++) // Iterate for all array elements
{
CGContextMoveToPoint (context, // Update current position to specified point
ECGX[x], // Starting X-coordinate
(HH - ECGS[x])); // Starting Y-coordinate (with height bias)
CGContextAddLineToPoint (context, ECGX[(x + 1)], // Draw line from current position
(HH - ECGS[((x + 1) % 127)])); // Ending Y-coordinate (with height bias)
x++; // Step to next array element
} // end - for (i = 0; i < 127; i++)
CGContextClosePath (context); // Close current path
CGContextStrokePath (context); // Stroke current path (paint the path)
fEcgErase = NO; // Reset erase flag
} // end - if (fEcgErase == YES)
else if (fECGLOOP) // Did request come from 'EcgThread'?
/*==============================================================================*/
/* Draw ECG cardiac waveforms on view. */
/*==============================================================================*/
{
xx = 1; // Counts markers
x = 0; // Reset horizontal axis
y = YY; // Use saved startimg ECGY[] index
ii = 0; // Initialize marker count
#define GRIDSIZE 12 // Grid width in pixels
int width = rect.size.width; // Get the view width
int height = rect.size.height; // Get the view height
/*==============================================================================*/
/* First draw a grid pattern to draw ECG waveforms into. */
/*==============================================================================*/
CGContextSetStrokeColorWithColor (context, // Set color of 'pen'
[UIColor lightGrayColor].CGColor); // Use 'light gray' for grid pattern
for (i = 0; i <= width; i = i+GRIDSIZE) // First the vertical lines
{
CGContextMoveToPoint (context, i, 0); // Update current position to specified point
CGContextAddLineToPoint (context, i, height); // Draw line from current position
} // end - for (i = 0; i <= width; i = i+GRIDSIZE)
for (i = 0 ; i <= height; i = i+GRIDSIZE) // Then the horizontal lines
{
CGContextMoveToPoint (context, 0, i); // Update current position to specified point
CGContextAddLineToPoint (context, width, i); // Draw line from current position
} // end - for (i = 0 ; i <= height; i = i+GRIDSIZE)
CGContextClosePath (context); // Close current path
CGContextStrokePath (context); // Stroke current path (paint the path)
/*==============================================================================*/
/* Now draw (plot) cardiac waveforms using using pre-stored ECG sample values. */
/*==============================================================================*/
for (i = 0; i < 127; i++) // Iterate for number ECGY[] entries
{
/*==============================================================================*/
/* Erase the prior ECG A/D plot value. */
/*==============================================================================*/
#if 0 // NOT NEEDED CUZ WE SELECTED CLEAR CONTEXT IN EcgViewController.xib
CGContextSetStrokeColorWithColor (context, // Set color of 'pen'
[UIColor blackColor].CGColor); // Black to erase old plot
CGContextMoveToPoint (context, // Update current position to specified point
ECGX[x], // Starting X-coordinate of prior position
(HH - ECGS[x])); // Starting Y-corrdinate with height bias
CGContextAddLineToPoint (context, // Draw line from current position
ECGX[(x + 1)], // Ending X-coordinate
(HH - ECGS[((x + 1))])); // Ending Y-coordinate using saved Y-axis (with height bias)
CGContextClosePath (context); // Close current path
CGContextStrokePath (context); // Stroke current path (paint the path)
#endif // NOT NEEDED CUZ WE SELECTED CLEAR CONTEXT IN EcgViewController.xib
/*==============================================================================*/
/* Plot the next ECG A/D plot value. */
/*==============================================================================*/
CGContextSetStrokeColorWithColor (context, // Set color of 'pen'
[UIColor greenColor].CGColor); // White to draw new plot
CGContextMoveToPoint (context, // Update current position to specified point
ECGX[x], // Starting X-coordinate of new position
(HH - ECGY[y])); // Starting Y-coordinate with height bias
CGContextAddLineToPoint (context, // Draw line & prevent overrun
ECGX[(x + 1)], // Ending X-coordinate
(HH - ECGY[((y + 1) % 127)])); // Ending Y-axis (with height bias)
CGContextClosePath (context); // Close current path
CGContextStrokePath (context); // Stroke current path (paint the path)
ECGS[x] = ECGY[y]; // Save last plot value for erase
x++; // Next ECGX[] (y-axis) plot value index
/*==============================================================================*/
/* Below as we increment 'y' it will eventually roll to zero and when we get */
/* to the end of the above 'for' loop 'y' will have its starting value. */
/*==============================================================================*/
y = ((y + 1) % 127); // Next ECGY[] (y-axis) plot value & prevent overrun
ulPlots++; // Count number of plots
} // end - for (i = 0; i < 127; i++)
y = ((y + 16) % 127); // Next starting y-axis 'ECGY' index
YY = y; // Save it for next iteration
EcgCount = 0; // Reset skip count (inc. by 'CommThread'
} // end - if (fEcgErase == YES)
// UIGraphicsPopContext();
fEcgDraw = NO; // Show 'drawRect' not running
// [NSThread sleepForTimeInterval : 0.1]; // Delay a little
} // end - 'drawRect'
/*===============================END OF FUNCTION================================*/
Keep in mind that drawing only ever happens on the main thread, which means that while drawRect: is running, your entire UI blocks. If this drawing code is slow, then your application will be nonresponsive while the drawing is taking place. Based on the size of the code and amount of individual drawing operations you're doing in this method, that seems to be what's happening here.
drawRect: gets its name from the fact that you're supposed to limit your drawing to the area described by rect. It's not 100% clear from your question if the entire graph changes every time, or if only a little bit of new data is being added. If there's a way you can restructure your code so that the entire thing doesn't need to be redrawn every time, that will almost certainly eliminate your jerkiness problems.
For example, you could also avoid drawing the gridlines on each refresh by putting them in a separate view behind the view that contains the plot. The gridlines (I'm guessing) don't need to be redrawn very often, so if you make your plot view transparent, UIKit will composite them for you and you can avoid a drawing operation. Probably a small savings, but anything helps. That would also mean that you can erase your view by filling it with the [UIColor clearColor]. Drawing over the old plot with the background color is an extremely expensive operation, but rectangle fills are dirt cheap. It's less code and it runs faster.
If that's not enough, you could also do your drawing into a separate UIImage offscreen, and then simply replace the contents of your view with this image. This would give you better performance because you would be able to do the image drawing (which is the expensive part) in a separate thread, and so the drawing operation wouldn't block the main application thread, which will eliminate the jerkiness.
I had a similar problem where I wanted to rotate an object through a specific number of radians based on a touch gesture. The rotation was jittery. I solved the problem by using CADisplayLink to synchronize the updates with the run loop:
#property (nonatomic, strong) CADisplayLink *displayLink;
self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:#selector(rotate)];
[self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
Every time the run loop updated the UI, my 'rotate' method was called. The rotation was smooth and I didn't notice any performance hits.
This was for an affine transformation that is not a very expensive operation. I suppose you could put setNeedsDisplay in a method that is called by a CADisplayLink object but that would likely be an expensive operation. Still, maybe worth a try.
Related
I am new to AR, I am working on an APP using ARCore using this one AR-REMOTE-SUPPORT
When I am drawing it from my screen it is creating default android anchor, I want line instead of default android anchor.
How can I achieve this.
here is the function which is placing Anchors on the screen
public void onDrawFrame(GL10 gl) {
// Clear screen to notify driver it should not load any pixels from previous frame.
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
if (mSession == null) {
return;
}
// Notify ARCore session that the view size changed so that the perspective matrix and
// the video background can be properly adjusted.
mDisplayRotationHelper.updateSessionIfNeeded(mSession);
try {
// Obtain the current frame from ARSession. When the configuration is set to
// UpdateMode.BLOCKING (it is by default), this will throttle the rendering to the
// camera framerate.
Frame frame = mSession.update();
Camera camera = frame.getCamera();
// Handle taps. Handling only one tap per frame, as taps are usually low frequency
// compared to frame rate.
MotionEvent tap = queuedSingleTaps.poll();
if (tap != null && camera.getTrackingState() == TrackingState.TRACKING) {
for (HitResult hit : frame.hitTest(tap)) {
// Check if any plane was hit, and if it was hit inside the plane polygon
Trackable trackable = hit.getTrackable();
// Creates an anchor if a plane or an oriented point was hit.
if ((trackable instanceof Plane && ((Plane) trackable).isPoseInPolygon(hit.getHitPose()))
|| (trackable instanceof Point
&& ((Point) trackable).getOrientationMode()
== Point.OrientationMode.ESTIMATED_SURFACE_NORMAL)) {
// Hits are sorted by depth. Consider only closest hit on a plane or oriented point.
// Cap the number of objects created. This avoids overloading both the
// rendering system and ARCore.
if (anchors.size() >= 250) {
anchors.get(0).detach();
anchors.remove(0);
}
// Adding an Anchor tells ARCore that it should track this position in
// space. This anchor is created on the Plane to place the 3D model
// in the correct position relative both to the world and to the plane.
anchors.add(hit.createAnchor());
break;
}
}
}
// Draw background.
mBackgroundRenderer.draw(frame);
// If not tracking, don't draw 3d objects.
if (camera.getTrackingState() == TrackingState.PAUSED) {
return;
}
// Get projection matrix.
float[] projmtx = new float[16];
camera.getProjectionMatrix(projmtx, 0, 0.1f, 100.0f);
// Get camera matrix and draw.
float[] viewmtx = new float[16];
camera.getViewMatrix(viewmtx, 0);
// Compute lighting from average intensity of the image.
final float lightIntensity = frame.getLightEstimate().getPixelIntensity();
if (isShowPointCloud()) {
// Visualize tracked points.
PointCloud pointCloud = frame.acquirePointCloud();
mPointCloud.update(pointCloud);
mPointCloud.draw(viewmtx, projmtx);
// Application is responsible for releasing the point cloud resources after
// using it.
pointCloud.release();
}
// Check if we detected at least one plane. If so, hide the loading message.
if (mMessageSnackbar != null) {
for (Plane plane : mSession.getAllTrackables(Plane.class)) {
if (plane.getType() == Plane.Type.HORIZONTAL_UPWARD_FACING
&& plane.getTrackingState() == TrackingState.TRACKING) {
hideLoadingMessage();
break;
}
}
}
if (isShowPlane()) {
// Visualize planes.
mPlaneRenderer.drawPlanes(
mSession.getAllTrackables(Plane.class), camera.getDisplayOrientedPose(), projmtx);
}
// Visualize anchors created by touch.
float scaleFactor = 1.0f;
for (Anchor anchor : anchors) {
if (anchor.getTrackingState() != TrackingState.TRACKING) {
continue;
}
// Get the current pose of an Anchor in world space. The Anchor pose is updated
// during calls to session.update() as ARCore refines its estimate of the world.
anchor.getPose().toMatrix(mAnchorMatrix, 0);
// Update and draw the model and its shadow.
mVirtualObject.updateModelMatrix(mAnchorMatrix, mScaleFactor);
//mVirtualObjectShadow.updateModelMatrix(mAnchorMatrix, scaleFactor);
mVirtualObject.draw(viewmtx, projmtx, lightIntensity);
mVirtualObjectShadow.draw(viewmtx, projmtx, lightIntensity);
}
sendARViewMessage();
} catch (Throwable t) {
// Avoid crashing the application due to unhandled exceptions.
Log.e(TAG, "Exception on the OpenGL thread", t);
}
}
Any help would be appreciated
TIA
One simple way to draw a line in ARCore is to create it between two anchor points.
The line itself is generally a 3D object also.
Here is a tested working example, based on the nice approach in this answer: https://stackoverflow.com/a/52816504/334402
private void drawLine(AnchorNode node1, AnchorNode node2) {
//Draw a line between two AnchorNodes (adapted from https://stackoverflow.com/a/52816504/334402)
Log.d(TAG,"drawLine");
Vector3 point1, point2;
point1 = node1.getWorldPosition();
point2 = node2.getWorldPosition();
//First, find the vector extending between the two points and define a look rotation
//in terms of this Vector.
final Vector3 difference = Vector3.subtract(point1, point2);
final Vector3 directionFromTopToBottom = difference.normalized();
final Quaternion rotationFromAToB =
Quaternion.lookRotation(directionFromTopToBottom, Vector3.up());
MaterialFactory.makeOpaqueWithColor(getApplicationContext(), new Color(0, 255, 244))
.thenAccept(
material -> {
/* Then, create a rectangular prism, using ShapeFactory.makeCube() and use the difference vector
to extend to the necessary length. */
Log.d(TAG,"drawLine insie .thenAccept");
ModelRenderable model = ShapeFactory.makeCube(
new Vector3(.01f, .01f, difference.length()),
Vector3.zero(), material);
/* Last, set the world rotation of the node to the rotation calculated earlier and set the world position to
the midpoint between the given points . */
Anchor lineAnchor = node2.getAnchor();
nodeForLine = new Node();
nodeForLine.setParent(node1);
nodeForLine.setRenderable(model);
nodeForLine.setWorldPosition(Vector3.add(point1, point2).scaled(.5f));
nodeForLine.setWorldRotation(rotationFromAToB);
}
);
}
You can see the full source here: https://github.com/mickod/LineView
I would like to create a brush for drawing on a PGraphics element with Processing. I would like past brush strokes to be visible. However, since the PGraphics element is loaded every frame, previous brush strokes disappear immediatly.
My idea was then to create PGraphics pg in setup(), make a copy of it in void(), alter the original graphic pg and update the copy at every frame. This produces a NullPointerException, most likely because pg is defined locally in setup().
This is what I have got so far:
PGraphics pg;
PFont font;
void setup (){
font = createFont("Pano Bold Kopie.otf", 600);
size(800, 800, P2D);
pg = createGraphics(800, 800, P2D);
pg.beginDraw();
pg.background(0);
pg.fill(255);
pg.textFont(font);
pg.textSize(400);
pg.pushMatrix();
pg.translate(width/2, height/2-140);
pg.textAlign(CENTER, CENTER);
pg.text("a", 0 , 0);
pg.popMatrix();
pg.endDraw();
}
void draw () {
copy(pg, 0, 0, width, height, 0, 0, width, height);
loop();
int c;
loadPixels();
for (int x=0; x<width; x++) {
for (int y=0; y<height; y++) {
pg.pixels[mouseX+mouseY*width]=0;
}
}
updatePixels();
}
My last idea, which I have not attempted to implement yet, is to append pixels which have been touched by the mouse to a list and to draw from this list each frame. But this seems quite complicated to me as it might result into super long arrays needing to be processed on top of the original image. So, I hope there is another way around!
EDIT: My goal is to create a smudge brush, hence a brush which kind of copies areas from one part of the image to other parts.
There's no need to manually copy pixels like that. The PGraphics class extends PImage, which means you can simply render it with image(pg,0,0); for example.
The other thing you could do is an old trick to fade the background: instead of clearing pixels completely you can render a sketch size slightly opaque rectangle with no stroke.
Here's a quick proof of concept based on your code:
PFont font;
PGraphics pg;
void setup (){
//font = createFont("Pano Bold Kopie.otf", 600);
font = createFont("Verdana",600);
size(800, 800, P2D);
// clear main background once
background(0);
// prep fading background
noStroke();
// black fill with 10/255 transparnecy
fill(0,10);
pg = createGraphics(800, 800, P2D);
pg.beginDraw();
// leave the PGraphics instance transparent
//pg.background(0);
pg.fill(255);
pg.textFont(font);
pg.textSize(400);
pg.pushMatrix();
pg.translate(width/2, height/2-140);
pg.textAlign(CENTER, CENTER);
pg.text("a", 0 , 0);
pg.popMatrix();
pg.endDraw();
}
void draw () {
// test with mouse pressed
if(mousePressed){
// slowly fade/clear the background by drawing a slightly opaque rectangle
rect(0,0,width,height);
}
// don't clear the background, render the PGraphics layer directly
image(pg, mouseX - pg.width / 2, mouseY - pg.height / 2);
}
If you hold the mouse pressed you can see the fade effect.
(changing transparency to 10 to a higher value with make the fade quicker)
Update To create a smudge brush you can still sample pixels and then manipulate the read colours to some degree. There are many ways to implement a smudge effect based on what you want to achieve visually.
Here's a very rough proof of concept:
PFont font;
PGraphics pg;
int pressX;
int pressY;
void setup (){
//font = createFont("Pano Bold Kopie.otf", 600);
font = createFont("Verdana",600);
size(800, 800, P2D);
// clear main background once
background(0);
// prep fading background
noStroke();
// black fill with 10/255 transparnecy
fill(0,10);
pg = createGraphics(800, 800, JAVA2D);
pg.beginDraw();
// leave the PGraphics instance transparent
//pg.background(0);
pg.fill(255);
pg.noStroke();
pg.textFont(font);
pg.textSize(400);
pg.pushMatrix();
pg.translate(width/2, height/2-140);
pg.textAlign(CENTER, CENTER);
pg.text("a", 0 , 0);
pg.popMatrix();
pg.endDraw();
}
void draw () {
image(pg,0,0);
}
void mousePressed(){
pressX = mouseX;
pressY = mouseY;
}
void mouseDragged(){
// sample the colour where mouse was pressed
color sample = pg.get(pressX,pressY);
// calculate the distance from where the "smudge" started to where it is
float distance = dist(pressX,pressY,mouseX,mouseY);
// map this distance to transparency so the further the distance the less smudge (e.g. short distance, high alpha, large distnace, small alpha)
float alpha = map(distance,0,30,255,0);
// map distance to "brush size"
float size = map(distance,0,30,30,0);
// extract r,g,b values
float r = red(sample);
float g = green(sample);
float b = blue(sample);
// set new r,g,b,a values
pg.beginDraw();
pg.fill(r,g,b,alpha);
pg.ellipse(mouseX,mouseY,size,size);
pg.endDraw();
}
As the comments mention, one idea is to sample colour on press then use the sample colour and fade it as your drag away from the source area. This shows simply reading a single pixel. You may want to experiment with sampling/reading more pixels (e.g. a rectangle or ellipse).
Additionally, the code above isn't optimised.
A few things could be sped up a bit, like reading pixels, extracting colours, calculating distance, etc.
For example:
void mouseDragged(){
// sample the colour where mouse was pressed
color sample = pg.pixels[pressX + (pressY * pg.width)];
// calculate the distance from where the "smudge" started to where it is (can use manual distance squared if this is too slow)
float distance = dist(pressX,pressY,mouseX,mouseY);
// map this distance to transparency so the further the distance the less smudge (e.g. short distance, high alpha, large distnace, small alpha)
float alpha = map(distance,0,30,255,0);
// map distance to "brush size"
float size = map(distance,0,30,30,0);
// extract r,g,b values
int r = (sample >> 16) & 0xFF; // Like red(), but faster
int g = (sample >> 8) & 0xFF;
int b = sample & 0xFF;
// set new r,g,b,a values
pg.beginDraw();
pg.fill(r,g,b,alpha);
pg.ellipse(mouseX,mouseY,size,size);
pg.endDraw();
}
The idea is to start simple with clear, readable code and only at the end, if needed look into optimisations.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
actually, I've tried to run the spherical POV. For run POV, each image should be converted to the number of lines which is used in each revolution, I've tried to use processing software to convert the 2d to 3d image by its library, but when insert those pixel data on the spherical POV, the image is really unrecognizable, any clue to how to map 2d image on a spherical surface
The Processing editor comes with examples, one of which maps a texture image to a sphere. It does this by splitting the sphere into triangles, and then using the texture() and vertex() functions to draw the textured sphere.
You can get to the code from the Processing editor by going to File > Examples > Topics > Textures > TextureSphere, but here's the code:
/**
* Texture Sphere
* by Gillian Ramsay
*
* Rewritten by Gillian Ramsay to better display the poles.
* Previous version by Mike 'Flux' Chang (and cleaned up by Aaron Koblin).
* Original based on code by Toxi.
*
* A 3D textured sphere with simple rotation control.
*/
int ptsW, ptsH;
PImage img;
int numPointsW;
int numPointsH_2pi;
int numPointsH;
float[] coorX;
float[] coorY;
float[] coorZ;
float[] multXZ;
void setup() {
size(640, 360, P3D);
background(0);
noStroke();
img=loadImage("world32k.jpg");
ptsW=30;
ptsH=30;
// Parameters below are the number of vertices around the width and height
initializeSphere(ptsW, ptsH);
}
// Use arrow keys to change detail settings
void keyPressed() {
if (keyCode == ENTER) saveFrame();
if (keyCode == UP) ptsH++;
if (keyCode == DOWN) ptsH--;
if (keyCode == LEFT) ptsW--;
if (keyCode == RIGHT) ptsW++;
if (ptsW == 0) ptsW = 1;
if (ptsH == 0) ptsH = 2;
// Parameters below are the number of vertices around the width and height
initializeSphere(ptsW, ptsH);
}
void draw() {
background(0);
camera(width/2+map(mouseX, 0, width, -2*width, 2*width),
height/2+map(mouseY, 0, height, -height, height),
height/2/tan(PI*30.0 / 180.0),
width, height/2.0, 0,
0, 1, 0);
pushMatrix();
translate(width/2, height/2, 0);
textureSphere(200, 200, 200, img);
popMatrix();
}
void initializeSphere(int numPtsW, int numPtsH_2pi) {
// The number of points around the width and height
numPointsW=numPtsW+1;
numPointsH_2pi=numPtsH_2pi; // How many actual pts around the sphere (not just from top to bottom)
numPointsH=ceil((float)numPointsH_2pi/2)+1; // How many pts from top to bottom (abs(....) b/c of the possibility of an odd numPointsH_2pi)
coorX=new float[numPointsW]; // All the x-coor in a horizontal circle radius 1
coorY=new float[numPointsH]; // All the y-coor in a vertical circle radius 1
coorZ=new float[numPointsW]; // All the z-coor in a horizontal circle radius 1
multXZ=new float[numPointsH]; // The radius of each horizontal circle (that you will multiply with coorX and coorZ)
for (int i=0; i<numPointsW ;i++) { // For all the points around the width
float thetaW=i*2*PI/(numPointsW-1);
coorX[i]=sin(thetaW);
coorZ[i]=cos(thetaW);
}
for (int i=0; i<numPointsH; i++) { // For all points from top to bottom
if (int(numPointsH_2pi/2) != (float)numPointsH_2pi/2 && i==numPointsH-1) { // If the numPointsH_2pi is odd and it is at the last pt
float thetaH=(i-1)*2*PI/(numPointsH_2pi);
coorY[i]=cos(PI+thetaH);
multXZ[i]=0;
}
else {
//The numPointsH_2pi and 2 below allows there to be a flat bottom if the numPointsH is odd
float thetaH=i*2*PI/(numPointsH_2pi);
//PI+ below makes the top always the point instead of the bottom.
coorY[i]=cos(PI+thetaH);
multXZ[i]=sin(thetaH);
}
}
}
void textureSphere(float rx, float ry, float rz, PImage t) {
// These are so we can map certain parts of the image on to the shape
float changeU=t.width/(float)(numPointsW-1);
float changeV=t.height/(float)(numPointsH-1);
float u=0; // Width variable for the texture
float v=0; // Height variable for the texture
beginShape(TRIANGLE_STRIP);
texture(t);
for (int i=0; i<(numPointsH-1); i++) { // For all the rings but top and bottom
// Goes into the array here instead of loop to save time
float coory=coorY[i];
float cooryPlus=coorY[i+1];
float multxz=multXZ[i];
float multxzPlus=multXZ[i+1];
for (int j=0; j<numPointsW; j++) { // For all the pts in the ring
normal(-coorX[j]*multxz, -coory, -coorZ[j]*multxz);
vertex(coorX[j]*multxz*rx, coory*ry, coorZ[j]*multxz*rz, u, v);
normal(-coorX[j]*multxzPlus, -cooryPlus, -coorZ[j]*multxzPlus);
vertex(coorX[j]*multxzPlus*rx, cooryPlus*ry, coorZ[j]*multxzPlus*rz, u, v+changeV);
u+=changeU;
}
v+=changeV;
u=0;
}
endShape();
}
Hopefully this is a good start, but more generally: Stack Overflow isn't really designed for general "how do I do this" type questions. It's more designed for specific "I tried X, expected Y, but got Z instead" type questions. Can you post anything you've tried? Where is your Minimal, Complete, and Verifiable example?
If you have no idea how to start, then start smaller: can you get an image mapped to a rectangle? Work your way up from there and post if you get stuck. Good luck.
I am using this Accelerometer graph from Apple and trying to convert their G-force code to calculate +/- 128.
The following image shows that the x, y, z values in the labels do not match the output on the graph: (Note that addX:y:z values are what is shown in the labels above the graph)
ViewController
The x, y, z values are received from a bluetooth peripheral, then converted using:
// Updates LABELS
- (void)didReceiveRawAcceleromaterDataWithX:(NSInteger)x Y:(NSInteger)y Z:(NSInteger)z
{
dispatch_async(dispatch_get_main_queue(), ^{
_labelAccel.text = [NSString stringWithFormat:#"x:%li y:%li z:%li", (long)x, (long)y, (long)z];
});
}
// Updates GRAPHS
- (void)didReceiveAcceleromaterDataWithX:(NSInteger)x Y:(NSInteger)y Z:(NSInteger)z
{
dispatch_async(dispatch_get_main_queue(), ^{
float xx = ((float)x) / 8192;
float yy = ((float)y) / 8192;
float zz = ((float)z) / 8192;
[_xGraph addX:xx y:0 z:0];
[_yGraph addX:0 y:yy z:0];
[_zGraph addX:0 y:0 z:zz];
});
}
GraphView
- (BOOL)addX:(UIAccelerationValue)x y:(UIAccelerationValue)y z:(UIAccelerationValue)z
{
// If this segment is not full, then we add a new acceleration value to the history.
if (index > 0)
{
// First decrement, both to get to a zero-based index and to flag one fewer position left
--index;
xhistory[index] = x;
yhistory[index] = y;
zhistory[index] = z;
// And inform Core Animation to redraw the layer.
[layer setNeedsDisplay];
}
// And return if we are now full or not (really just avoids needing to call isFull after adding a value).
return index == 0;
}
- (void)drawLayer:(CALayer*)l inContext:(CGContextRef)context
{
// Fill in the background
CGContextSetFillColorWithColor(context, kUIColorLightGray(1.f).CGColor);
CGContextFillRect(context, layer.bounds);
// Draw the grid lines
DrawGridlines(context, 0.0, 32.0);
// Draw the graph
CGPoint lines[64];
int i;
float _granularity = 16.f; // 16
NSInteger _granualCount = 32; // 32
// X
for (i = 0; i < _granualCount; ++i)
{
lines[i*2].x = i;
lines[i*2+1].x = i + 1;
lines[i*2].y = xhistory[i] * _granularity;
lines[i*2+1].y = xhistory[i+1] * _granularity;
}
CGContextSetStrokeColorWithColor(context, _xColor.CGColor);
CGContextStrokeLineSegments(context, lines, 64);
// Y
for (i = 0; i < _granualCount; ++i)
{
lines[i*2].y = yhistory[i] * _granularity;
lines[i*2+1].y = yhistory[i+1] * _granularity;
}
CGContextSetStrokeColorWithColor(context, _yColor.CGColor);
CGContextStrokeLineSegments(context, lines, 64);
// Z
for (i = 0; i < _granualCount; ++i)
{
lines[i*2].y = zhistory[i] * _granularity;
lines[i*2+1].y = zhistory[i+1] * _granularity;
}
CGContextSetStrokeColorWithColor(context, _zColor.CGColor);
CGContextStrokeLineSegments(context, lines, 64);
}
How can I calculate the above code to show the correct accelerometer values on the graph with precision?
I post this as an aswer not a comment, because I have not enough reputation, but what I'll write might be enough to send you in the right direction, that it even may count as an answer...
Your question still doesn't include what is really important. I assume the calculation of the xx/yy/zz is no problem. Although I have no idea what the 8192 is supposed to mean.
I guess the preblem is in the part where you map your values to pixel coordinates...
the lines[] contains your values in a range of 1/8192th of the values in the label. so your x value of -2 should be at a pixel position of -0.0000something, so slightly(far less than 1 Pixel) above the view... Because you see the line a lot further down there must be some translation in place (not shown in your code)
The second part that is important but not shown is DrawGridlines. Probably in there is a different approach to map the values to pixel-coordinates...
Use the debugger to check what pixel-coordinates you get when draw your +127-line and what you get if you insert the value of +127 in your history-array
And some Ideas for improvements when reading your code:
1.)Put the graph in it's own class that draws one graph(and has only one history. Somehow you seem to have that partially already (otherwise I cannot figure out your _xGraph/_yGraph/_zGraph) But on the other hand you draw all 3 values in one drawLayer??? Currently you seem to have 3*3 history buffers of which 3*2 are filled with zeros...
2.) use one place where you do the calculation of Y that you use both for drawing the grid and drawing the lines...
3.) use CGContextMoveToPoint(); + CGContextAddLineToPoint(); instead of copying into lines[] with these ugly 2*i+1 indecies...
I would like to allow the user to draw curves in such a way that no line can cross another line or even itself. Drawing the curves is no problem, and I even found that I can create a path that is closed and still pretty line-like by tracing the nodes of the line forwards and back and then closing the path.
Unfortunately, iOS only provides a test for whether a point is contained in a closed path (containsPoint: and CGPathContainsPoint). Unfortunately, a user can pretty easily move their finger fast enough that the touch points land on both sides of an existing path without actually being contained by that path, so testing the touch points is pretty pointless.
I can't find any "intersection" of paths method.
Any other thoughts on how to accomplish this task?
Well, I did come up with a way to do this. It is imperfect, but I thought others might want to see the technique since this question was upvoted a few times. The technique I used draws all the items to be tested against into a bitmap context and then draws the new segment of the progressing line into another bitmap context. The data in those contexts is compared using bitwise operators and if any overlap is found, a hit is declared.
The idea behind this technique is to test each segment of a newly drawn line against all the previously drawn lines and even against earlier pieces of the same line. In other words, this technique will detect when a line crosses another line and also when it crosses over itself.
A sample app demonstrating the technique is available: LineSample.zip.
The core of hit testing is done in my LineView object. Here are two key methods:
- (CGContextRef)newBitmapContext {
// creating b&w bitmaps to do hit testing
// based on: http://robnapier.net/blog/clipping-cgrect-cgpath-531
// see "Supported Pixel Formats" in Quartz 2D Programming Guide
CGContextRef bitmapContext =
CGBitmapContextCreate(NULL, // data automatically allocated
self.bounds.size.width,
self.bounds.size.height,
8,
self.bounds.size.width,
NULL,
kCGImageAlphaOnly);
CGContextSetShouldAntialias(bitmapContext, NO);
// use CGBitmapContextGetData to get at this data
return bitmapContext;
}
- (BOOL)line:(Line *)line canExtendToPoint:(CGPoint) newPoint {
// Lines are made up of segments that go from node to node. If we want to test for self-crossing, then we can't just test the whole in progress line against the completed line, we actually have to test each segment since one segment of the in progress line may cross another segment of the same line (think of a loop in the line). We also have to avoid checking the first point of the new segment against the last point of the previous segment (which is the same point). Luckily, a line cannot curve back on itself in just one segment (think about it, it takes at least two segments to reach yourself again). This means that we can both test progressive segments and avoid false hits by NOT drawing the last segment of the line into the test! So we will put everything up to the last segment into the hitProgressLayer, we will put the new segment into the segmentLayer, and then we will test for overlap among those two and the hitTestLayer. Any point that is in all three layers will indicate a hit, otherwise we are OK.
if (line.failed) {
// shortcut in case a failed line is retested
return NO;
}
BOOL ok = YES; // thinking positively
// set up a context to hold the new segment and stroke it in
CGContextRef segmentContext = [self newBitmapContext];
CGContextSetLineWidth(segmentContext, 2); // bit thicker to facilitate hits
CGPoint lastPoint = [[[line nodes] lastObject] point];
CGContextMoveToPoint(segmentContext, lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(segmentContext, newPoint.x, newPoint.y);
CGContextStrokePath(segmentContext);
// now we actually test
// based on code from benzado: http://stackoverflow.com/questions/6515885/how-to-do-comparisons-of-bitmaps-in-ios/6515999#6515999
unsigned char *completedData = CGBitmapContextGetData(hitCompletedContext);
unsigned char *progressData = CGBitmapContextGetData(hitProgressContext);
unsigned char *segmentData = CGBitmapContextGetData(segmentContext);
size_t bytesPerRow = CGBitmapContextGetBytesPerRow(segmentContext);
size_t height = CGBitmapContextGetHeight(segmentContext);
size_t len = bytesPerRow * height;
for (int i = 0; i < len; i++) {
if ((completedData[i] | progressData[i]) & segmentData[i]) {
ok = NO;
break;
}
}
CGContextRelease(segmentContext);
if (ok) {
// now that we know we are good to go,
// we will add the last segment onto the hitProgressLayer
int numberOfSegments = [[line nodes] count] - 1;
if (numberOfSegments > 0) {
// but only if there is a segment there!
CGPoint secondToLastPoint = [[[line nodes] objectAtIndex:numberOfSegments-1] point];
CGContextSetLineWidth(hitProgressContext, 1); // but thinner
CGContextMoveToPoint(hitProgressContext, secondToLastPoint.x, secondToLastPoint.y);
CGContextAddLineToPoint(hitProgressContext, lastPoint.x, lastPoint.y);
CGContextStrokePath(hitProgressContext);
}
} else {
line.failed = YES;
[linesFailed addObject:line];
}
return ok;
}
I'd love to hear suggestions or see improvements. For one thing, it would be a lot faster to only check the bounding rect of the new segment instead of the whole view.
Swift 4, answer is based on CGPath Hit Testing - Ole Begemann (2012)
From Ole Begemann blog:
contains(point: CGPoint)
This function is helpful if you want to hit test on the entire region
the path covers. As such, contains(point: CGPoint) doesn’t work with
unclosed paths because those don’t have an interior that would be
filled.
copy(strokingWithWidth lineWidth: CGFloat, lineCap: CGLineCap, lineJoin: CGLineJoin, miterLimit: CGFloat, transform: CGAffineTransform = default) -> CGPath
This function creates a mirroring tap target object that only covers
the stroked area of the path. When the user taps on the screen, we
iterate over the tap targets rather than the actual shapes.
My solution in code
I use a UITapGestureRecognizer linked to the function tap():
var bezierPaths = [UIBezierPath]() // containing all lines already drawn
var tappedPaths = [CAShapeLayer]()
#IBAction func tap(_ sender: UITapGestureRecognizer) {
let point = sender.location(in: imageView)
for path in bezierPaths {
// create tapTarget for path
if let target = tapTarget(for: path) {
if target.contains(point) {
tappedPaths.append(layer)
}
}
}
}
fileprivate func tapTarget(for path: UIBezierPath) -> UIBezierPath {
let targetPath = path.copy(strokingWithWidth: path.lineWidth, lineCap: path..lineCapStyle, lineJoin: path..lineJoinStyle, miterLimit: path.miterLimit)
return UIBezierPath.init(cgPath: targetPath)
}