Is it possible to increment a variable's value by passing this variable to some function parameter, so that variable's value changes e.g.
int y=0;
void someFunc(int a);
somefunc(y+50);
NSLog(#"y=#f",y);
prints "y = 50"
You can do it this way
someFunc(y=y+50);
someFunc(y=+50);
but is there more elegant way accomplishing this, using pointers maybe? e.g
someFunc(*y+50);
This is the snippet of my code where I want to accomplish this
-(void)drawRect:(CGRect)rect
{
CGFloat currentX = 0;
CGFloat currentY = height / 2;
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(ctx, 5);
CGContextSetStrokeColorWithColor(ctx, [UIColor blackColor].CGColor);
CGContextSetFillColorWithColor(ctx, [UIColor redColor].CGColor);
CGContextMoveToPoint(ctx,currentX, currentY);
CGContextAddLineToPoint(ctx, currentX=currentX+50, currentY - 200);
CGContextAddLineToPoint(ctx, currentX=+50, currentY - 200);
CGContextAddLineToPoint(ctx, currentX=+50, currentY - 200);
CGContextAddLineToPoint(ctx, currentX=+50, currentY - 200);
CGContextDrawPath(ctx, kCGPathStroke);
}
I want to keep that currentX's value being updated everytime I increment it in the function parameter. Get it?
You can do this by passing a pointer to the variable. This is called an "out parameter" or "call by reference":
void someFunc( int * a, int o )
{
…
*a = *a + o;
}
int y = 0;
someFunc( &y, 50 );
// y is y+o
Either you need to change the value before calling the function, in which case you do:
x = x + something;
func(x);
or if you need to change the value after calling the function, you do like this:
func(x);
x = x + something;
Common sense.
NOTE: never write code like func(x=something) with the assignment inside the parameter list. Because in case you get a habit of doing so, you will soon be writing order-of-evaluation bugs such as func(x, x=something) // BAD, unspecified behavior.
Alternatively, if you need to change the value inside the function, you could pass its address:
void func (int* param)
{
*param = something;
}
...
func(&x);
But you can obviosuly only do this if the function is written by you. This doesn't seem to be the case here, since those functions are apparently part of some Apple library.
Related
I am using OSMSharp for an iOS project.
I'll like to be able to convert a given point in the view/map to GeoCoordinates (based on the current MapCenter, view size, zoom, etc).
I thought mapView.Map.Project.ToGeoCoordinates would do that, but the result is not correct. The inverse function (mapView.Map.Project.ToPixel) returns values in a coordinate system that doesn't correspond to the actual view (it returns value up to 10000 or so, and the size of my view is 1024x768).
So, how do I convert a given pixel coordinate in a OsmSharp.iOS.UI.MapView to its corresponding GeoCoordinate?.
Right now there's no method to get it. But it's easy to get
Add below method to MapView class in OsmSharp.iOS.UI project
public GeoCoordinate PointToCoordinate(int PointX, int PointY)
{
View2D view = _cacheRenderer.Create(this.Width, this.Height, this.Map,
(float)this.Map.Projection.ToZoomFactor(this.MapZoom), this.MapCenter, false, true);
// get scene coordinates.
double x, y;
var fromMatrix = view.CreateFromViewPort(this.Width, this.Height);
fromMatrix.Apply(PointX, PointY, out x, out y);
return this.Map.Projection.ToGeoCoordinates(x, y);
}
If you want the Point from Geocoordinate, add below method to the same class
public Point CoordinateToPoint(GeoCoordinate gc)
{
var gcPx = this.Map.Projection.ToPixel(gc);
View2D view = _cacheRenderer.Create(this.Width, this.Height, this.Map,
(float)this.Map.Projection.ToZoomFactor(this.MapZoom), this.MapCenter, false, true);
// get scene coordinates.
double x, y;
var fromMatrix = view.CreateFromViewPort(this.Width, this.Height);
fromMatrix.Remove(gcPx[0], gcPx[1], out x, out y);
return new Point((int)System.Math.Round(x, 0), (int)System.Math.Round(y, 0));
}
And below method to Matrix2D class in OsmSharp.UI.Renderer project
public void Remove(double x, double y, out double xNew, out double yNew)
{
xNew = (x * this.E11 - this.E02 * this.E11 + this.E01 * this.E12 - this.E01 * y) / (this.E00 * this.E11 - this.E01 * this.E10);
yNew = (y - this.E12 - this.E10 * xNew) / this.E11;
}
my program is Directx Program that draws a container cube within it smaller cubes....these smaller cubes fall by time i hope you understand what i mean...
The program isn't complete yet ...it should draws the container only ....but it draws nothing ...only the background color is visible... i only included what i think is needed ...
this is the routines that initialize the program
bool Game::init(HINSTANCE hinst,HWND _hw){
Directx11 ::init(hinst , _hw);
return LoadContent();}
Directx11::init()
bool Directx11::init(HINSTANCE hinst,HWND hw){
_hinst=hinst;_hwnd=hw;
RECT rc;
GetClientRect(_hwnd,&rc);
height= rc.bottom - rc.top;
width = rc.right - rc.left;
UINT flags=0;
#ifdef _DEBUG
flags |=D3D11_CREATE_DEVICE_DEBUG;
#endif
HR(D3D11CreateDevice(0,_driverType,0,flags,0,0,D3D11_SDK_VERSION,&d3dDevice,&_featureLevel,&d3dDeviceContext));
if (d3dDevice == 0 || d3dDeviceContext == 0)
return 0;
DXGI_SWAP_CHAIN_DESC sdesc;
ZeroMemory(&sdesc,sizeof(DXGI_SWAP_CHAIN_DESC));
sdesc.Windowed=true;
sdesc.BufferCount=1;
sdesc.BufferDesc.Format=DXGI_FORMAT_R8G8B8A8_UNORM;
sdesc.BufferDesc.Height=height;
sdesc.BufferDesc.Width=width;
sdesc.BufferDesc.Scaling=DXGI_MODE_SCALING_UNSPECIFIED;
sdesc.BufferDesc.ScanlineOrdering=DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
sdesc.OutputWindow=_hwnd;
sdesc.BufferDesc.RefreshRate.Denominator=1;
sdesc.BufferDesc.RefreshRate.Numerator=60;
sdesc.Flags=0;
sdesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
if (m4xMsaaEnable)
{
sdesc.SampleDesc.Count=4;
sdesc.SampleDesc.Quality=m4xMsaaQuality-1;
}
else
{
sdesc.SampleDesc.Count=1;
sdesc.SampleDesc.Quality=0;
}
IDXGIDevice *Device=0;
HR(d3dDevice->QueryInterface(__uuidof(IDXGIDevice),reinterpret_cast <void**> (&Device)));
IDXGIAdapter*Ad=0;
HR(Device->GetParent(__uuidof(IDXGIAdapter),reinterpret_cast <void**> (&Ad)));
IDXGIFactory* fac=0;
HR(Ad->GetParent(__uuidof(IDXGIFactory),reinterpret_cast <void**> (&fac)));
fac->CreateSwapChain(d3dDevice,&sdesc,&swapchain);
ReleaseCOM(Device);
ReleaseCOM(Ad);
ReleaseCOM(fac);
ID3D11Texture2D *back = 0;
HR(swapchain->GetBuffer(0,__uuidof(ID3D11Texture2D),reinterpret_cast <void**> (&back)));
HR(d3dDevice->CreateRenderTargetView(back,0,&RenderTarget));
D3D11_TEXTURE2D_DESC Tdesc;
ZeroMemory(&Tdesc,sizeof(D3D11_TEXTURE2D_DESC));
Tdesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
Tdesc.ArraySize = 1;
Tdesc.Format= DXGI_FORMAT_D24_UNORM_S8_UINT;
Tdesc.Height= height;
Tdesc.Width = width;
Tdesc.Usage = D3D11_USAGE_DEFAULT;
Tdesc.MipLevels=1;
if (m4xMsaaEnable)
{
Tdesc.SampleDesc.Count=4;
Tdesc.SampleDesc.Quality=m4xMsaaQuality-1;
}
else
{
Tdesc.SampleDesc.Count=1;
Tdesc.SampleDesc.Quality=0;
}
HR(d3dDevice->CreateTexture2D(&Tdesc,0,&depthview));
HR(d3dDevice->CreateDepthStencilView(depthview,0,&depth));
d3dDeviceContext->OMSetRenderTargets(1,&RenderTarget,depth);
D3D11_VIEWPORT vp;
vp.TopLeftX=0.0f;
vp.TopLeftY=0.0f;
vp.Width = static_cast <float> (width);
vp.Height= static_cast <float> (height);
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
d3dDeviceContext -> RSSetViewports(1,&vp);
return true;
SetBuild() Prepare the matrices inside the container for the smaller cubes ....i didnt program it to draw the smaller cubes yet
and this the function that draws the scene
void Game::Render(){
d3dDeviceContext->ClearRenderTargetView(RenderTarget,reinterpret_cast <const float*> (&Colors::LightSteelBlue));
d3dDeviceContext->ClearDepthStencilView(depth,D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL,1.0f,0);
d3dDeviceContext-> IASetInputLayout(_layout);
d3dDeviceContext-> IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
d3dDeviceContext->IASetIndexBuffer(indices,DXGI_FORMAT_R32_UINT,0);
UINT strides=sizeof(Vertex),off=0;
d3dDeviceContext->IASetVertexBuffers(0,1,&vertices,&strides,&off);
D3DX11_TECHNIQUE_DESC des;
Tech->GetDesc(&des);
Floor * Lookup; /*is a variable to Lookup inside the matrices structure (Floor Contains XMMATRX Piese[9])*/
std::vector<XMFLOAT4X4> filled; // saves the matrices of the smaller cubes
XMMATRIX V=XMLoadFloat4x4(&View),P = XMLoadFloat4x4(&Proj);
XMMATRIX vp = V * P;XMMATRIX wvp;
for (UINT i = 0; i < des.Passes; i++)
{
d3dDeviceContext->RSSetState(BuildRast);
wvp = XMLoadFloat4x4(&(B.Memory[0].Pieces[0])) * vp; // Loading The Matrix at translation(0,0,0)
HR(ShadeMat->SetMatrix(reinterpret_cast<float*> ( &wvp)));
HR(Tech->GetPassByIndex(i)->Apply(0,d3dDeviceContext));
d3dDeviceContext->DrawIndexed(build_ind_count,build_ind_index,build_vers_index);
d3dDeviceContext->RSSetState(PieseRast);
UINT r1=B.GetSize(),r2=filled.size();
for (UINT j = 0; j < r1; j++)
{
Lookup = &B.Memory[j];
for (UINT r = 0; r < Lookup->filledindeces.size(); r++)
{
filled.push_back(Lookup->Pieces[Lookup->filledindeces[r]]);
}
}
for (UINT j = 0; j < r2; j++)
{
ShadeMat->SetMatrix( reinterpret_cast<const float*> (&filled[i]));
Tech->GetPassByIndex(i)->Apply(0,d3dDeviceContext);
d3dDeviceContext->DrawIndexed(piese_ind_count,piese_ind_index,piese_vers_index);
}
}
HR(swapchain->Present(0,0));}
thanks in Advance
One bug in your program appears to be that you're using i, the index of the current pass, as an index into the filled vector, when you should apparently be using j.
Another apparent bug is that in the loop where you are supposed to be iterating over the elements of filled, you're not iterating over all of them. The value r2 is set to the size of filled before you append anything to it during that pass. During the first pass this means that nothing will be drawn by this loop. If your technique only has one pass then this means that the second DrawIndexed call in your code will never be executed.
It also appears you should be only adding matrices to filled once, regardless of the number of the passes the technique has. You should consider if your code is actually meant to work with techniques with multiple passes.
I have a function which does some array manipulation on an NSMutableArray. Somehow after a couple of loops of the while function the values inside 2 local variables are total garbage. They are not being assigned or manipulated anywhere. Here's how:
Here's the function:
-(void) normalize_path:(NSMutableArray *)path tool:(Tool)tool
{
NSUInteger last_accepted_point_index = 0;
NSUInteger current_point_index = 1;
while(current_point_index < [path count]){
VPoint * p1, * p2;
[[path objectAtIndex:last_accepted_point_index] getValue:&p1];
[[path objectAtIndex:current_point_index] getValue:&p2];
//float distance = [self distance_between:p1 and:p2];
// if(distance < MIN_POINT_DISTANCE){
// [path removeObjectAtIndex:current_point_index];
// }else{
// float opacity = tool.max_opacity - distance * tool.opacity_sensitivity;
// opacity = opacity <= tool.min_opacity ? tool.min_opacity : opacity;
// p2->opacity = opacity;
// float thickness = tool.max_thickness - distance * tool.thickness_sensitivity;
// thickness = thickness <= tool.min_thickness ? tool.min_thickness : thickness;
// p2->thickness = thickness;
// last_accepted_point_index = current_point_index;
// //current_point_index++;
// }
}
}
And it's called only in one place like so:
//...
[self normalize_path:opath tool:pen];
//...
Every run creates different values. I am confounded! What is going on here?
I think that this may be a memory issue which you can fix by removing the & from in front of p1 and p2 in the getValue: call. It's difficult to be totally sure as you haven't said what VPoint is, but normally this code would look like this:
VPoint p1, p2;
[[path objectAtIndex:last_accepted_point_index] getValue:&p1];
[[path objectAtIndex:current_point_index] getValue:&p2];
This would then set p1 and p2 to the actual values. Your distance between function would then not take references but the actual values of p1 and p2 (if you want to pass references as you are doing now, you'd put & in front of p1 and p2 in the distance callBetween method call.
Simple question. What is the best way to turn a CGPoint into a GLKVector?
These structures are identical so it would be nice to be able to reinterpret_cast or memcpy or something like that. My solution below works but hardly seems optimum. I'm creating a GLKVector2 on the stack assigning each member then returning this as a value which is then assigned to another GLKVector.
It's not going to break the bank or anything but there must be a neater way to do this?
GLKVector2 Vector2FromPoint(CGPoint point)
{
GLKVector2 v;
v.x = point.x;
v.y = point.y;
return v;
}
You could try using memcpy in a function like this:
bool vector2ToCGPoint(GLKVector2* s, CGPoint* d) {
memcpy(d, s, sizeof(*d));
}
but then it is probably better to have:
bool copyVector2ToCGPoint(GLKVector2* s, CGPoint* d) {
d.x = s.x;
d.y = s.x;
}
if you really want optimization, you could go for a macro:
#define copyS2D(S,D) (D.x = S.x, D.y = S.y)
so you can do:
CGPoint b;
GLKVector2 a;
vector2FromCGPoint(a, b);
of course, as you know, macros will not be that much type-safe...
GLKVector2 v = GLKVector2Make(point.x, point.y);
I have a for loop like so
for (int i = 0; i < circles->total; i++)
{
// round the floats to an int
float* p = (float*)cvGetSeqElem(circles, i);
cv::Point center(cvRound(p[0]), cvRound(p[1]));
int radius = cvRound(p[2]);
int num_red = 0;
//uchar* ptr;
//ptr = cvPtr2D(img, center.y, center.x, NULL);
//printf("B: %d G: %d R: %d\n", ptr[0],ptr[1],ptr[2]);
CvScalar s;
s = cvGet2D(img,center.y, center.x);//colour of circle
printf("B: %f G: %f R: %f\n",s.val[0],s.val[1],s.val[2]);
if (s.val[2]<=255 && s.val[2]>=230 && s.val[1]<=40 && s.val[1]>=0 && s.val[0] <=40 && s.val[0]>=0)
{
printf("Red Ball\n");
num_red++;
}
which is working. but later on in my code i tried to use the s.val[] and num_red like this
int count_red = 0;
int red_pot = 0;
if(s.val[2]<=255 && s.val[2]>=230 && s.val[1]<=40 && s.val[1]>=0 && s.val[0] <=40 && s.val[0]>=0)
count_red ++;//count the reds detected
num_red - count_red = red_pot;//originally detected - whats left = whats potted
im getting undeclared identifier error for 's'. Left of .val must have class/struct and 'num_red' : undeclared identifier. I dont understand why the program doesnt can't read these values from above further down. anyone able to help?
You create s inside the for loop. So as soon as the for loop terminates, s goes out of scope. You need to create a variable at a scope that includes every scope in which you intend to access it.