Search Results

Search found 590 results on 24 pages for 'flip'.

Page 5/24 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Confusion on C++ Python extensions. Things like getting C++ values for python values.

    - by Matthew Mitchell
    I'm wanted to convert some of my python code to C++ for speed but it's not as easy as simply making a C++ function and making a few function calls. I have no idea how to get a C++ integer from a python integer object. I have an integer which is an attribute of an object that I want to use. I also have integers which are inside a list in the object which I need to use. I wanted to test making a C++ extension with this function: def setup_framebuffer(surface,flip=False): #Create texture if not done already if surface.texture is None: create_texture(surface) #Render child to parent if surface.frame_buffer is None: surface.frame_buffer = glGenFramebuffersEXT(1) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, c_uint(int(surface.frame_buffer))) glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, surface.texture, 0) glPushAttrib(GL_VIEWPORT_BIT) glViewport(0,0,surface._scale[0],surface._scale[1]) glMatrixMode(GL_PROJECTION) glLoadIdentity() #Load the projection matrix if flip: gluOrtho2D(0,surface._scale[0],surface._scale[1],0) else: gluOrtho2D(0,surface._scale[0],0,surface._scale[1]) That function calls create_texture, so I will have to pass that function to the C++ function which I will do with the third argument. This is what I have so far, while trying to follow information on the python documentation: #include <Python.h> #include <GL/gl.h> static PyMethodDef SpamMethods[] = { ... {"setup_framebuffer", setup_framebuffer, METH_VARARGS,"Loads a texture from a Surface object to the OpenGL framebuffer."}, ... {NULL, NULL, 0, NULL} /* Sentinel */ }; static PyObject * setup_framebuffer(PyObject *self, PyObject *args){ bool flip; PyObject *create_texture, *arg_list,*pyflip,*frame_buffer_id; if (!PyArg_ParseTuple(args, "OOO", &surface,&pyflip,&create_texture)){ return NULL; } if (PyObject_IsTrue(pyflip) == 1){ flip = true; }else{ flip = false; } Py_XINCREF(create_texture); //Create texture if not done already if(texture == NULL){ arglist = Py_BuildValue("(O)", surface) result = PyEval_CallObject(create_texture, arglist); Py_DECREF(arglist); if (result == NULL){ return NULL; } Py_DECREF(result); } Py_XDECREF(create_texture); //Render child to parent frame_buffer_id = PyObject_GetAttr(surface, Py_BuildValue("s","frame_buffer")) if(surface.frame_buffer == NULL){ glGenFramebuffersEXT(1,frame_buffer_id); } glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, surface.frame_buffer)); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, surface.texture, 0); glPushAttrib(GL_VIEWPORT_BIT); glViewport(0,0,surface._scale[0],surface._scale[1]); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //Load the projection matrix if (flip){ gluOrtho2D(0,surface._scale[0],surface._scale[1],0); }else{ gluOrtho2D(0,surface._scale[0],0,surface._scale[1]); } Py_INCREF(Py_None); return Py_None; } PyMODINIT_FUNC initcscalelib(void){ PyObject *module; module = Py_InitModule("cscalelib", Methods); if (m == NULL){ return; } } int main(int argc, char *argv[]){ /* Pass argv[0] to the Python interpreter */ Py_SetProgramName(argv[0]); /* Initialize the Python interpreter. Required. */ Py_Initialize(); /* Add a static module */ initscalelib(); }

    Read the article

  • trigger animation with timer, as3

    - by VideoDnd
    How do I trigger the animation in sync with my timer?My timer and flip animation work, but they are out of sync with each other. I'm lost with the IF ELSE statements. Each time the value of my textfield changes, my number needs to flip. See example. Example //IF ELSE FUNCTION function theFlip(event:TimerEvent):void { count++; if (count < 9) { oldcount = count - 1; } else { count++; fcount=int(count) count++; oldcount = count - 1; } } //Cont... Complete Codehere's the file //Timer var timer:Timer = new Timer(100); //Integer values var count:int = 0; var fcount:int = 0; var oldcount:int = 0; //Formatting String function formatCount(i:int):String { var fraction:int = i % 100; var whole:int = i / 100; return ("00" + whole).substr(-2, 2) + "." + (fraction < 10 ? "0" + fraction : fraction); } //Start the timer timer.start(); timer.addEventListener(TimerEvent.TIMER, theFlip); //IF ELSE FUNCTION function theFlip(event:TimerEvent):void { count++; if (count < 9) { oldcount = count - 1; } else { count++; fcount=int(count) count++; oldcount = count - 1; } var toText:String = formatCount(fcount); sec4.digit.text = toText.substr(4, 1); flip4.flip.digit.text = toText.substr(4, 1); flip4.gotoAndPlay(2); sec3.digit.text = toText.substr(3, 1); flip3.flip.digit.text = toText.substr(3, 1); flip3.gotoAndPlay(2); sec1.digit.text = toText.substr(1, 1); flip1.flip.digit.text = toText.substr(1, 1); flip1.gotoAndPlay(2); }

    Read the article

  • OBJ model loaded in LWJGL has a black area with no texture

    - by gambiting
    I have a problem with loading an .obj file in LWJGL and its textures. The object is a tree(it's a paid model from TurboSquid, so I can't post it here,but here's the link if you want to see how it should look like): http://www.turbosquid.com/FullPreview/Index.cfm/ID/701294 I wrote a custom OBJ loader using the LWJGL tutorial from their wiki. It looks like this: public class OBJLoader { public static Model loadModel(File f) throws FileNotFoundException, IOException { BufferedReader reader = new BufferedReader(new FileReader(f)); Model m = new Model(); String line; Texture currentTexture = null; while((line=reader.readLine()) != null) { if(line.startsWith("v ")) { float x = Float.valueOf(line.split(" ")[1]); float y = Float.valueOf(line.split(" ")[2]); float z = Float.valueOf(line.split(" ")[3]); m.verticies.add(new Vector3f(x,y,z)); }else if(line.startsWith("vn ")) { float x = Float.valueOf(line.split(" ")[1]); float y = Float.valueOf(line.split(" ")[2]); float z = Float.valueOf(line.split(" ")[3]); m.normals.add(new Vector3f(x,y,z)); }else if(line.startsWith("vt ")) { float x = Float.valueOf(line.split(" ")[1]); float y = Float.valueOf(line.split(" ")[2]); m.texVerticies.add(new Vector2f(x,y)); }else if(line.startsWith("f ")) { Vector3f vertexIndicies = new Vector3f(Float.valueOf(line.split(" ")[1].split("/")[0]), Float.valueOf(line.split(" ")[2].split("/")[0]), Float.valueOf(line.split(" ")[3].split("/")[0])); Vector3f textureIndicies = new Vector3f(Float.valueOf(line.split(" ")[1].split("/")[1]), Float.valueOf(line.split(" ")[2].split("/")[1]), Float.valueOf(line.split(" ")[3].split("/")[1])); Vector3f normalIndicies = new Vector3f(Float.valueOf(line.split(" ")[1].split("/")[2]), Float.valueOf(line.split(" ")[2].split("/")[2]), Float.valueOf(line.split(" ")[3].split("/")[2])); m.faces.add(new Face(vertexIndicies,textureIndicies,normalIndicies,currentTexture.getTextureID())); }else if(line.startsWith("g ")) { if(line.length()>2) { String name = line.split(" ")[1]; currentTexture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/" + name + ".png")); System.out.println(currentTexture.getTextureID()); } } } reader.close(); System.out.println(m.verticies.size() + " verticies"); System.out.println(m.normals.size() + " normals"); System.out.println(m.texVerticies.size() + " texture coordinates"); System.out.println(m.faces.size() + " faces"); return m; } } Then I create a display list for my model using this code: objectDisplayList = GL11.glGenLists(1); GL11.glNewList(objectDisplayList, GL11.GL_COMPILE); Model m = null; try { m = OBJLoader.loadModel(new File("res/untitled4.obj")); } catch (Exception e1) { e1.printStackTrace(); } int currentTexture=0; for(Face face: m.faces) { if(face.texture!=currentTexture) { currentTexture = face.texture; GL11.glBindTexture(GL11.GL_TEXTURE_2D, currentTexture); } GL11.glColor3f(1f, 1f, 1f); GL11.glBegin(GL11.GL_TRIANGLES); Vector3f n1 = m.normals.get((int) face.normal.x - 1); GL11.glNormal3f(n1.x, n1.y, n1.z); Vector2f t1 = m.texVerticies.get((int) face.textures.x -1); GL11.glTexCoord2f(t1.x, t1.y); Vector3f v1 = m.verticies.get((int) face.vertex.x - 1); GL11.glVertex3f(v1.x, v1.y, v1.z); Vector3f n2 = m.normals.get((int) face.normal.y - 1); GL11.glNormal3f(n2.x, n2.y, n2.z); Vector2f t2 = m.texVerticies.get((int) face.textures.y -1); GL11.glTexCoord2f(t2.x, t2.y); Vector3f v2 = m.verticies.get((int) face.vertex.y - 1); GL11.glVertex3f(v2.x, v2.y, v2.z); Vector3f n3 = m.normals.get((int) face.normal.z - 1); GL11.glNormal3f(n3.x, n3.y, n3.z); Vector2f t3 = m.texVerticies.get((int) face.textures.z -1); GL11.glTexCoord2f(t3.x, t3.y); Vector3f v3 = m.verticies.get((int) face.vertex.z - 1); GL11.glVertex3f(v3.x, v3.y, v3.z); GL11.glEnd(); } GL11.glEndList(); The currentTexture is an int - it contains the ID of the currently used texture. So my model looks absolutely fine without textures: (sorry I cannot post hyperlinks since I am a new user) i.imgur.com/VtoK0.png But look what happens if I enable GL_TEXTURE_2D: i.imgur.com/z8Kli.png i.imgur.com/5e9nn.png i.imgur.com/FAHM9.png As you can see an entire side of the tree appears to be missing - and it's not transparent, since it's not in the colour of the background - it's rendered black. It's not a problem with the model - if I load it using Kanji's OBJ loader it works fine(but the thing is,that I need to write my own OBJ loader) i.imgur.com/YDATo.png this is my OpenGL init section: //init display try { Display.setDisplayMode(new DisplayMode(Support.SCREEN_WIDTH, Support.SCREEN_HEIGHT)); Display.create(); Display.setVSyncEnabled(true); } catch (LWJGLException e) { e.printStackTrace(); System.exit(0); } GL11.glLoadIdentity(); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glClearColor(1.0f, 0.0f, 0.0f, 1.0f); GL11.glShadeModel(GL11.GL_SMOOTH); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glDepthFunc(GL11.GL_LESS); GL11.glDepthMask(true); GL11.glEnable(GL11.GL_NORMALIZE); GL11.glMatrixMode(GL11.GL_PROJECTION); GLU.gluPerspective (90.0f,800f/600f, 1f, 500.0f); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glEnable(GL11.GL_CULL_FACE); GL11.glCullFace(GL11.GL_BACK); //enable lighting GL11.glEnable(GL11.GL_LIGHTING); ByteBuffer temp = ByteBuffer.allocateDirect(16); temp.order(ByteOrder.nativeOrder()); GL11.glMaterial(GL11.GL_FRONT, GL11.GL_DIFFUSE, (FloatBuffer)temp.asFloatBuffer().put(lightDiffuse).flip()); GL11.glMaterialf(GL11.GL_FRONT, GL11.GL_SHININESS,(int)material_shinyness); GL11.glLight(GL11.GL_LIGHT2, GL11.GL_DIFFUSE, (FloatBuffer)temp.asFloatBuffer().put(lightDiffuse2).flip()); // Setup The Diffuse Light GL11.glLight(GL11.GL_LIGHT2, GL11.GL_POSITION,(FloatBuffer)temp.asFloatBuffer().put(lightPosition2).flip()); GL11.glLight(GL11.GL_LIGHT2, GL11.GL_AMBIENT,(FloatBuffer)temp.asFloatBuffer().put(lightAmbient).flip()); GL11.glLight(GL11.GL_LIGHT2, GL11.GL_SPECULAR,(FloatBuffer)temp.asFloatBuffer().put(lightDiffuse2).flip()); GL11.glLightf(GL11.GL_LIGHT2, GL11.GL_CONSTANT_ATTENUATION, 0.1f); GL11.glLightf(GL11.GL_LIGHT2, GL11.GL_LINEAR_ATTENUATION, 0.0f); GL11.glLightf(GL11.GL_LIGHT2, GL11.GL_QUADRATIC_ATTENUATION, 0.0f); GL11.glEnable(GL11.GL_LIGHT2); Could somebody please help me?

    Read the article

  • how to do event checks for loops?

    - by yao jiang
    I am having some trouble getting the logic down for this. Currently, I have an app that animates the astar pathfinding algorithm. On start of the app, the ui will show the following: User can press "space" to randomly choose start/end coords, then the app will animate it. Or, user can choose the start/end by left-click/right-click. During the animation, the user can also left-click to generate blocks, or right-click to choose a new destiantion. Where I am stuck at is how to handle the events while the app is animating. Right now, I am checking events in the main loop, then when the app is animating, I do event checks again. While it works fine, I feel that I am probably doing it wrong. What is the proper way of setting up the main loop that will handle the events while the app is animating? In main loop, the app start animating once user choose start/end. In my draw function, I am putting another event checker in there. def clear(rows): for r in range(rows): for c in range(rows): if r%3 == 1 and c%3 == 1: color = brown; grid[r][c] = 1; buildCoor.append(r); buildCoor.append(c); else: color = white; grid[r][c] = 0; pick_image(screen, color, width*c, height*r); pygame.display.flip(); os.system('cls'); # draw out the grid def draw(start, end, grid, route_coord): # draw the end coords color = red; pick_image(screen, color, width*end[1],height*end[0]); pygame.display.flip(); # then draw the rest of the route for i in range(len(route_coord)): # pausing because we want animation time.sleep(speed); # get the x/y coords x,y = route_coord[i]; event_on = False; if grid[x][y] == 2: color = green; elif grid[x][y] == 3: color = blue; for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 3: print "destination change detected, rerouting"; # get mouse position, px coords pos = pygame.mouse.get_pos(); # get grid coord c = pos[0] // width; r = pos[1] // height; grid[r][c] = 4; end = [r, c]; elif event.button == 1: print "user generated event"; pos = pygame.mouse.get_pos(); # get grid coord c = pos[0] // width; r = pos[1] // height; # mark it as a block for now grid[r][c] = 1; event_on = True; if check_events([x,y]) or event_on: # there is an event # mark it as a block for now grid[y][x] = 1; pick_image(screen, event_x, width*y, height*x); pygame.display.flip(); # then find a new route new_start = route_coord[i-1]; marked_grid, route_coord = find_route(new_start, end, grid); draw(new_start, end, grid, route_coord); return; # just end draw here so it wont throw the "index out of range" error elif grid[x][y] == 4: color = red; pick_image(screen, color, width*y, height*x); pygame.display.flip(); # clear route coord list, otherwise itll just add more unwanted coords route_coord_list[:] = []; clear(rows); # main loop while not done: # check the events for event in pygame.event.get(): # mouse events if event.type == pygame.MOUSEBUTTONDOWN: # get mouse position, px coords pos = pygame.mouse.get_pos(); # get grid coord c = pos[0] // width; r = pos[1] // height; # find which button pressed, highlight grid accordingly if event.button == 1: # left click, start coords if grid[r][c] == 2: grid[r][c] = 0; color = white; elif grid[r][c] == 0 or grid[r][c] == 4: grid[r][c] = 2; start = [r,c]; color = green; else: grid[r][c] = 1; color = brown; elif event.button == 3: # right click, end coords if grid[r][c] == 4: grid[r][c] = 0; color = white; elif grid[r][c] == 0 or grid[r][c] == 2: grid[r][c] = 4; end = [r,c]; color = red; else: grid[r][c] = 1; color = brown; pick_image(screen, color, width*c, height*r); # keyboard events elif event.type == pygame.KEYDOWN: clear(rows); # one way to quit program if event.key == pygame.K_ESCAPE: print "program will now exit."; done = True; # space key for random start/end elif event.key == pygame.K_SPACE: # first clear the ui clear(rows); # now choose random start/end coords buildLoc = zip(buildCoor,buildCoor[1:])[::2]; #print buildLoc; (start_x, start_y, end_x, end_y) = pick_point(); while (start_x, start_y) in buildLoc or (end_x, end_y) in buildLoc: (start_x, start_y, end_x, end_y) = pick_point(); clear(rows); print "chosen random start/end coords: ", (start_x, start_y, end_x, end_y); if (start_x, start_y) in buildLoc or (end_x, end_y) in buildLoc: print "error"; # draw the route marked_grid, route_coord = find_route([start_x,start_y],[end_x,end_y], grid); draw([start_x, start_y], [end_x, end_y], marked_grid, route_coord); # return key for user defined start/end elif event.key == pygame.K_RETURN: # first clear the ui clear(rows); # get the user defined start/end print "user defined start/end are: ", (start[0], start[1], end[0], end[1]); grid[start[0]][start[1]] = 1; grid[end[0]][end[1]] = 2; # draw the route marked_grid, route_coord = find_route(start, end, grid); draw(start, end, marked_grid, route_coord); # c to clear the screen elif event.key == pygame.K_c: print "clearing screen."; clear(rows); # go fullscreen elif event.key == pygame.K_f: if not full_sc: pygame.display.set_mode([1366, 768], pygame.FULLSCREEN); full_sc = True; rows = 15; clear(rows); else: pygame.display.set_mode(size); full_sc = False; # +/- key to change speed of animation elif event.key == pygame.K_LEFTBRACKET: if speed >= 0.1: print SPEED_UP; speed = speed_up(speed); print speed; else: print FASTEST; print speed; elif event.key == pygame.K_RIGHTBRACKET: if speed < 1.0: print SPEED_DOWN; speed = slow_down(speed); print speed; else: print SLOWEST print speed; # second method to quit program elif event.type == pygame.QUIT: print "program will now exit."; done = True; # limit to 20 fps clock.tick(20); # update the screen pygame.display.flip();

    Read the article

  • Turning on collision crashes game

    - by MomentumGaming
    I am getting a null pointer excecption to both my sprite and level. I am working on my mob class, and when I try to move him and the move function is called, the game crashes after checking collision with a null pointer excecption. Taking out the one line that actually checks if the tile located in front of it fixes the problem. Also, if i keep collision ON but don't move the position of the mob (the spider) the game works fine. I will have collision, and the spider appears on the screen, only problem is, getting it to move causes this nasty error that i just can't fix. true Exception in thread "Display" java.lang.NullPointerException at com.apcompsci.game.entity.mob.Mob.collision(Mob.java:67) at com.apcompsci.game.entity.mob.Mob.move(Mob.java:38) at com.apcompsci.game.entity.mob.spider.update(spider.java:58) at com.apcompsci.game.level.Level.update(Level.java:55) at com.apcompsci.game.Game.update(Game.java:128) at com.apcompsci.game.Game.run(Game.java:106) at java.lang.Thread.run(Unknown Source) Here is my renderMob mehtod: public void renderMob(int xp,int yp,Sprite sprite,int flip) { xp -= xOffset; yp-=yOffset; for(int y = 0; y<32; y++) { int ya = y + yp; int ys = y; if(flip == 2||flip == 3)ys = 31-y; for(int x = 0; x<32; x++) { int xa = x + xp; int xs = x; if(flip == 1||flip == 3)xs = 31-x; if(xa < -32 || xa >=width || ya<0||ya>=height) break; if(xa<0) xa =0; int col = sprite.pixels[xs+ys*32]; if(col!= 0x000000) pixels[xa+ya*width] = col; } } } My spider class which determines the sprite and where I control movement, also rendering the spider onto the screen, when I increment ya to move the sprite, I get the crash, but without ya++, it runs flawlessly with a spider sprite on screen: package com.apcompsci.game.entity.mob; import com.apcompsci.game.entity.mob.Mob.Direction; import com.apcompsci.game.graphics.Screen; import com.apcompsci.game.graphics.Sprite; import com.apcompsci.game.level.Level; public class spider extends Mob{ Direction dir; private Sprite sprite; private boolean walking; public spider(int x, int y) { this.x = x <<4; this.y = y <<4; sprite = sprite.spider_forward; } public void update() { int xa = 0, ya = 0; ya++; if(ya<0) { sprite = sprite.spider_forward; dir = Direction.UP; } if(ya>0) { sprite = sprite.spider_back; dir = Direction.DOWN; } if(xa<0) { sprite = sprite.spider_side; dir = Direction.LEFT; } if(xa>0) { sprite = sprite.spider_side; dir = Direction.LEFT; } if(xa!= 0 || ya!= 0) { System.out.println("true"); move(xa,ya); walking = true; } else{ walking = false; } } public void render(Screen screen) { screen.renderMob(x, y, sprite, 0); } } This is th mob class that contains the move() method that is called in the spider class above. This move method calls the collision method. tile and sprite comes up null in the debugger: package com.apcompsci.game.entity.mob; import java.util.ArrayList; import java.util.List; import com.apcompsci.game.entity.Entity; import com.apcompsci.game.entity.projectile.DemiGodProjectile; import com.apcompsci.game.entity.projectile.Projectile; import com.apcompsci.game.graphics.Sprite; public class Mob extends Entity{ protected Sprite sprite; protected boolean moving = false; protected enum Direction { UP,DOWN,LEFT,RIGHT } protected Direction dir; public void move(int xa,int ya) { if(xa != 0 && ya != 0) { move(xa,0); move(0,ya); return; } if(xa>0) dir = Direction.RIGHT; if(xa<0) dir = Direction.LEFT; if(ya>0)dir = Direction.DOWN; if(ya<0)dir = Direction.UP; if(!collision(xa,ya)){ x+= xa; y+=ya; } } public void update() { } public void shoot(int x, int y, double dir) { //dir = Math.toDegrees(dir); Projectile p = new DemiGodProjectile(x, y,dir); level.addProjectile(p); } public boolean collision(int xa,int ya) { boolean solid = false; for(int c = 0; c<4; c++) { int xt = ((x+xa) + c % 2 * 14 - 8 )/16; int yt = ((y+ya) + c / 2 * 12 +3 )/16; if(level.getTile(xt, yt).solid()) solid = true; } return solid; } public void render() { } } Finally, here is the method in which i call the add() method for the spider to add it to the level: protected void loadLevel(String path) { try{ BufferedImage image = ImageIO.read(SpawnLevel.class.getResource(path)); int w = width =image.getWidth(); int h = height = image.getHeight(); tiles = new int[w*h]; image.getRGB(0, 0, w,h, tiles,0, w); } catch(IOException e){ e.printStackTrace(); System.out.println("Exception! Could not load level file!"); } add(new spider(20,45)); } I don't think i need to include the level class but just in case, I have provided a gistHub link for better context. It contains all of the full classes listed above , plus my entity class and maybe another. Thanks for the help if you decide to do so, much appreciated! Also, please tell me if i'm in the wrong section of stackeoverflow, i figured that since this is the gamign section that it belonged but debugging code normally goes into the general section.

    Read the article

  • Problems with SAT Collision Detection

    - by DJ AzKai
    I'm doing a project in one of my modules for college in C++ with SFML and I was hoping someone may be able to help me. I'm using a vector of squares and triangles and I am using the SAT collision detection method to see if objects collide and to make the objects respond to the collision appropriately using the MTV(minimum translation vector) Below is my code: //from the main method int main(){ // Create the main window sf::RenderWindow App(sf::VideoMode(800, 600, 32), "SFML OpenGL"); // Create a clock for measuring time elapsed sf::Clock Clock; srand(time(0)); //prepare OpenGL surface for HSR glClearDepth(1.f); glClearColor(0.3f, 0.3f, 0.3f, 0.f); //background colour glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); //// Setup a perspective projection & Camera position glMatrixMode(GL_PROJECTION); glLoadIdentity(); //set up a 3D Perspective View volume //gluPerspective(90.f, 1.f, 1.f, 300.0f);//fov, aspect, zNear, zFar //set up a orthographic projection same size as window //this mease the vertex coordinates are in pixel space glOrtho(0,800,0,600,0,1); // use pixel coordinates // Finally, display rendered frame on screen vector<BouncingThing*> triangles; for(int i = 0; i < 10; i++) { //instantiate each triangle; triangles.push_back(new BouncingTriangle(Vector2f(rand() % 700, rand() % 500), 3)); } vector<BouncingThing*> boxes; for(int i = 0; i < 10; i++) { //instantiate each box; boxes.push_back(new BouncingBox(Vector2f(rand() % 700, rand() % 500), 4)); } CollisionDetection * b = new CollisionDetection(); // Start game loop while (App.isOpen()) { // Process events sf::Event Event; while (App.pollEvent(Event)) { // Close window : exit if (Event.type == sf::Event::Closed) App.close(); // Escape key : exit if ((Event.type == sf::Event::KeyPressed) && (Event.key.code == sf::Keyboard::Escape)) App.close(); } //Prepare for drawing // Clear color and depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Apply some transformations glMatrixMode(GL_MODELVIEW); glLoadIdentity(); for(int i = 0; i < 10; i++) { triangles[i]->draw(); boxes[i]->draw(); triangles[i]->update(Vector2f(800,600)); boxes[i]->draw(); boxes[i]->update(Vector2f(800,600)); } for(int j = 0; j < 10; j++) { for(int i = 0; i < 10; i++) { triangles[j]->setCollision(b->CheckCollision(*(triangles[j]),*(boxes[i]))); } } for(int j = 0; j < 10; j++) { for(int i = 0; i < 10; i++) { boxes[j]->setCollision(b->CheckCollision(*(boxes[j]),*(triangles[i]))); } } for(int i = 0; i < triangles.size(); i++) { for(int j = i + 1; j < triangles.size(); j ++) { triangles[j]->setCollision(b->CheckCollision(*(triangles[j]),*(triangles[i]))); } } for(int i = 0; i < triangles.size(); i++) { for(int j = i + 1; j < triangles.size(); j ++) { boxes[j]->setCollision(b->CheckCollision(*(boxes[j]),*(boxes[i]))); } } App.display(); } return EXIT_SUCCESS; } (ignore this line) //from the BouncingThing.cpp BouncingThing::BouncingThing(Vector2f position, int noSides) : pos(position), pi(3.14), radius(3.14), nSides(noSides) { collided = false; if(nSides ==3) { Vector2f vert1 = Vector2f(-12.0f,-12.0f); Vector2f vert2 = Vector2f(0.0f, 12.0f); Vector2f vert3 = Vector2f(12.0f,-12.0f); verts.push_back(vert1); verts.push_back(vert2); verts.push_back(vert3); } else if(nSides == 4) { Vector2f vert1 = Vector2f(-12.0f,12.0f); Vector2f vert2 = Vector2f(12.0f, 12.0f); Vector2f vert3 = Vector2f(12.0f,-12.0f); Vector2f vert4 = Vector2f(-12.0f, -12.0f); verts.push_back(vert1); verts.push_back(vert2); verts.push_back(vert3); verts.push_back(vert4); } velocity.x = ((rand() % 5 + 1) / 3) + 1; velocity.y = ((rand() % 5 + 1) / 3 ) +1; } void BouncingThing::update(Vector2f screenSize) { Transform t; t.rotate(0); for(int i=0;i< verts.size(); i++) { verts[i]=t.transformPoint(verts[i]); } if(pos.x >= screenSize.x || pos.x <= 0) { velocity.x *= -1; } if(pos.y >= screenSize.y || pos.y <= 0) { velocity.y *= -1; } if(collided) { //velocity.x *= -1; //velocity.y *= -1; collided = false; } pos += velocity; } void BouncingThing::setCollision(bool x){ collided = x; } void BouncingThing::draw() { glBegin(GL_POLYGON); glColor3f(0,1,0); for(int i = 0; i < verts.size(); i++) { glVertex2f(pos.x + verts[i].x,pos.y + verts[i].y); } glEnd(); } vector<Vector2f> BouncingThing::getNormals() { vector<Vector2f> normalVerts; if(nSides == 3) { Vector2f ab = Vector2f((verts[1].x + pos.x) - (verts[0].x + pos.x), (verts[1].y + pos.y) - (verts[0].y + pos.y)); ab = flip(ab); ab.x *= -1; normalVerts.push_back(ab); Vector2f bc = Vector2f((verts[2].x + pos.x) - (verts[1].x + pos.x), (verts[2].y + pos.y) - (verts[1].y + pos.y)); bc = flip(bc); bc.x *= -1; normalVerts.push_back(bc); Vector2f ac = Vector2f((verts[2].x + pos.x) - (verts[0].x + pos.x), (verts[2].y + pos.y) - (verts[0].y + pos.y)); ac = flip(ac); ac.x *= -1; normalVerts.push_back(ac); return normalVerts; } if(nSides ==4) { Vector2f ab = Vector2f((verts[1].x + pos.x) - (verts[0].x + pos.x), (verts[1].y + pos.y) - (verts[0].y + pos.y)); ab = flip(ab); ab.x *= -1; normalVerts.push_back(ab); Vector2f bc = Vector2f((verts[2].x + pos.x) - (verts[1].x + pos.x), (verts[2].y + pos.y) - (verts[1].y + pos.y)); bc = flip(bc); bc.x *= -1; normalVerts.push_back(bc); return normalVerts; } } Vector2f BouncingThing::flip(Vector2f v){ float vyTemp = v.x; float vxTemp = v.y * -1; return Vector2f(vxTemp, vyTemp); } (Ignore this line) CollisionDetection::CollisionDetection() { } vector<float> CollisionDetection::bubbleSort(vector<float> w) { int temp; bool finished = false; while (!finished) { finished = true; for (int i = 0; i < w.size()-1; i++) { if (w[i] > w[i+1]) { temp = w[i]; w[i] = w[i+1]; w[i+1] = temp; finished=false; } } } return w; } class Vector{ public: //static int dp_count; static float dot(sf::Vector2f a,sf::Vector2f b){ //dp_count++; return a.x*b.x+a.y*b.y; } static float length(sf::Vector2f a){ return sqrt(a.x*a.x+a.y*a.y); } static Vector2f add(Vector2f a, Vector2f b) { return Vector2f(a.x + b.y, a.y + b.y); } static sf::Vector2f getNormal(sf::Vector2f a,sf::Vector2f b){ sf::Vector2f n; n=a-b; n/=Vector::length(n);//normalise float x=n.x; n.x=n.y; n.y=-x; return n; } }; bool CollisionDetection::CheckCollision(BouncingThing & x, BouncingThing & y) { vector<Vector2f> xVerts = x.getVerts(); vector<Vector2f> yVerts = y.getVerts(); vector<Vector2f> xNormals = x.getNormals(); vector<Vector2f> yNormals = y.getNormals(); int size; vector<float> xRange; vector<float> yRange; for(int j = 0; j < xNormals.size(); j++) { Vector p; for(int i = 0; i < xVerts.size(); i++) { xRange.push_back(p.dot(xNormals[j], Vector2f(xVerts[i].x, xVerts[i].x))); } for(int i = 0; i < yVerts.size(); i++) { yRange.push_back(p.dot(xNormals[j], Vector2f(yVerts[i].x , yVerts[i].y))); } yRange = bubbleSort(yRange); xRange = bubbleSort(xRange); if(xRange[xRange.size() - 1] < yRange[0] || yRange[yRange.size() - 1] < xRange[0]) { return false; } float x3 = Min(xRange[0], yRange[0]); float y3 = Max(xRange[xRange.size() - 1], yRange[yRange.size() - 1]); float length = Max(x3, y3) - Min(x3, y3); } for(int j = 0; j < yNormals.size(); j++) { Vector p; for(int i = 0; i < xVerts.size(); i++) { xRange.push_back(p.dot(yNormals[j], xVerts[i])); } for(int i = 0; i < yVerts.size(); i++) { yRange.push_back(p.dot(yNormals[j], yVerts[i])); } yRange = bubbleSort(yRange); xRange = bubbleSort(xRange); if(xRange[xRange.size() - 1] < yRange[0] || yRange[yRange.size() - 1] < xRange[0]) { return false; } } return true; } float CollisionDetection::Min(float min, float max) { if(max < min) { min = max; } else return min; } float CollisionDetection::Max(float min, float max) { if(min > max) { max = min; } else return min; } On the screen the objects will freeze for a small amount of time before moving off again. However the problem is is that when this happens there are no collisions actually happening and I would really love to find out where the flaw is in the code. If you need any more information/code please don't hesitate to ask and I'll reply as soon as possible Regards, AzKai

    Read the article

  • WPF storyboard animation issue when using VisualBrush

    - by Flack
    Hey guys, I was playing around with storyboards, a flipping animation, and visual brushes. I have encountered an issue though. Below is the xaml and code-behind of a small sample I quickly put together to try to demonstrate the problem. When you first start the app, you are presented with a red square and two buttons. If you click the "Flip" button, the red square will "flip" over and a blue one will appear. In reality, all that is happening is that the scale of the width of the StackPanel that the red square is in is being decreased until it reaches zero and then the StackPanel where a blue square is, whose width is initially scaled to zero, has its width increased. If you click the "Flip" button a few times, the animation looks ok and smooth. Now, if you hit the "Reflection" button, a reflection of the red/blue buttons is added to their respective StackPanels. Hitting the "Flip" button now will still cause the flip animation but it is no longer a smooth animation. The StackPanels width often does not shrink to zero. The width shrinks somewhat but then just stops before being completely invisible. Then the other StackPanel appears as usual. The only thing that changed was adding the reflection, which is just a VisualBrush. Below is the code. Does anyone have any idea why the animations are different between the two cases (stalling in the second case)? Thanks. <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xml:lang="en-US" xmlns:d="http://schemas.microsoft.com/expression/blend/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="WpfFlipTest.Window1" x:Name="Window" Title="Window1" Width="214" Height="224"> <Window.Resources> <Storyboard x:Key="sbFlip"> <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="redStack" Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleX)"> <SplineDoubleKeyFrame KeyTime="00:00:00.4" Value="0"/> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames BeginTime="00:00:00.4" Storyboard.TargetName="blueStack" Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleX)"> <SplineDoubleKeyFrame KeyTime="00:00:00.8" Value="1"/> </DoubleAnimationUsingKeyFrames> </Storyboard> <Storyboard x:Key="sbFlipBack"> <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="blueStack" Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleX)"> <SplineDoubleKeyFrame KeyTime="00:00:00.4" Value="0"/> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames BeginTime="00:00:00.4" Storyboard.TargetName="redStack" Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleX)"> <SplineDoubleKeyFrame KeyTime="00:00:00.8" Value="1"/> </DoubleAnimationUsingKeyFrames> </Storyboard> </Window.Resources> <Grid x:Name="LayoutRoot" Background="Gray"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <StackPanel Name="redStack" Grid.Row="0" Grid.Column="0" RenderTransformOrigin="0.5,0.5"> <StackPanel.RenderTransform> <ScaleTransform/> </StackPanel.RenderTransform> <Border Name="redBorder" BorderBrush="Transparent" BorderThickness="4" Width="Auto" Height="Auto"> <Button Margin="0" Name="redButton" Height="75" Background="Red" Width="105" /> </Border> <Border Width="{Binding ElementName=redBorder, Path=ActualWidth}" Height="{Binding ElementName=redBorder, Path=ActualHeight}" Opacity="0.2" BorderBrush="Transparent" BorderThickness="4" Name="redRefelction" Visibility="Collapsed"> <Border.OpacityMask> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <LinearGradientBrush.GradientStops> <GradientStop Offset="0" Color="Black"/> <GradientStop Offset=".6" Color="Transparent"/> </LinearGradientBrush.GradientStops> </LinearGradientBrush> </Border.OpacityMask> <Border.Background> <VisualBrush Visual="{Binding ElementName=redButton}"> <VisualBrush.Transform> <ScaleTransform ScaleX="1" ScaleY="-1" CenterX="52.5" CenterY="37.5" /> </VisualBrush.Transform> </VisualBrush> </Border.Background> </Border> </StackPanel> <StackPanel Name="blueStack" Grid.Row="0" Grid.Column="0" RenderTransformOrigin="0.5,0.5"> <StackPanel.RenderTransform> <ScaleTransform ScaleX="0"/> </StackPanel.RenderTransform> <Border Name="blueBorder" BorderBrush="Transparent" BorderThickness="4" Width="Auto" Height="Auto"> <Button Grid.Row="0" Grid.Column="1" Margin="0" Width="105" Background="Blue" Name="blueButton" Height="75"/> </Border> <Border Width="{Binding ElementName=blueBorder, Path=ActualWidth}" Height="{Binding ElementName=blueBorder, Path=ActualHeight}" Opacity="0.2" BorderBrush="Transparent" BorderThickness="4" Name="blueRefelction" Visibility="Collapsed"> <Border.OpacityMask> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <LinearGradientBrush.GradientStops> <GradientStop Offset="0" Color="Black"/> <GradientStop Offset=".6" Color="Transparent"/> </LinearGradientBrush.GradientStops> </LinearGradientBrush> </Border.OpacityMask> <Border.Background> <VisualBrush Visual="{Binding ElementName=blueButton}"> <VisualBrush.Transform> <ScaleTransform ScaleX="1" ScaleY="-1" CenterX="52.5" CenterY="37.5" /> </VisualBrush.Transform> </VisualBrush> </Border.Background> </Border> </StackPanel> <Button Grid.Row="1" Click="FlipButton_Click" Height="19.45" HorizontalAlignment="Left" VerticalAlignment="Top" Width="76">Flip</Button> <Button Grid.Row="0" Grid.Column="1" Click="ReflectionButton_Click" Height="19.45" HorizontalAlignment="Left" VerticalAlignment="Top" Width="76">Reflection</Button> </Grid> </Window> Here are the button click handlers: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Media.Animation; namespace WpfFlipTest { public partial class Window1 : Window { public Window1() { InitializeComponent(); } bool flipped = false; private void FlipButton_Click(object sender, RoutedEventArgs e) { Storyboard sbFlip = (Storyboard)Resources["sbFlip"]; Storyboard sbFlipBack = (Storyboard)Resources["sbFlipBack"]; if (flipped) { sbFlipBack.Begin(); flipped = false; } else { sbFlip.Begin(); flipped = true; } } bool reflection = false; private void ReflectionButton_Click(object sender, RoutedEventArgs e) { if (reflection) { reflection = false; redRefelction.Visibility = Visibility.Collapsed; blueRefelction.Visibility = Visibility.Collapsed; } else { reflection = true; redRefelction.Visibility = Visibility.Visible; blueRefelction.Visibility = Visibility.Visible; } } } } UPDATE: I have been testing this some more to try to find out what is causing the issue I am seeing and I believe I found what is causing the issue. Below I have pasted new xaml and code-behind. The new sample below is very similar to the original sample, with a few minor modifications. The xaml basically consists of two stack panels, each containing two borders. The second border in each stack panel is a visual brush (a reflection of the border above it). Now, when I click the "Flip" button, one stack panel gets its ScaleX reduced to zero, while the second stack panel, whose initial ScaleX is zero, gets its ScaleX increased to 1. This animation gives the illusion of flipping. There are also two textblocks which display the scale factor of each stack panel. I added those to try to diagnose my issue. The issue is (as described in the oringal post) that the flipping animation is not smooth. Every time I hit the flip button, the animation starts but whenever the ScaleX factor gets to around .14 to .16, the animation looks like it stalls and the stack panels never have there ScaleX reduced to zero, so they never totally disappear. Now, the strange thing is that if I change the Width/Height properties of the "frontBorder" and "backBorder" borders defined below to use explict values instead of Auto, such as Width=105 and Height=75 (to match the button in the border) everything works fine. The animation stutters the first two or three times I run it but after that the flips are smooth and flawless. (BTW, when an animation is run for the first time, is there something going on in the background, some sort of initialization, that causes it to be a little slow the first time?) Is it possible that the Auto Width/Height of the borders are causing the issue? I can reproduce it everytime but I am not sure why Auto Width/Height would be a problem. Below is the sample. Thanks for the help. <Window x:Class="FlipTest.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Window.Resources> <Storyboard x:Key="sbFlip"> <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="front" Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleX)"> <SplineDoubleKeyFrame KeyTime="00:00:00.5" Value="0"/> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames BeginTime="00:00:00.5" Storyboard.TargetName="back" Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleX)"> <SplineDoubleKeyFrame KeyTime="00:00:00.5" Value="1"/> </DoubleAnimationUsingKeyFrames> </Storyboard> <Storyboard x:Key="sbFlipBack"> <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="back" Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleX)"> <SplineDoubleKeyFrame KeyTime="00:00:00.5" Value="0"/> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames BeginTime="00:00:00.5" Storyboard.TargetName="front" Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleX)"> <SplineDoubleKeyFrame KeyTime="00:00:00.5" Value="1"/> </DoubleAnimationUsingKeyFrames> </Storyboard> </Window.Resources> <Grid x:Name="LayoutRoot" Background="White" ShowGridLines="True"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <StackPanel x:Name="front" RenderTransformOrigin="0.5,0.5"> <StackPanel.RenderTransform> <ScaleTransform/> </StackPanel.RenderTransform> <Border Name="frontBorder" BorderBrush="Yellow" BorderThickness="2" Width="Auto" Height="Auto"> <Button Margin="0" Name="redButton" Height="75" Background="Red" Width="105" Click="FlipButton_Click"/> </Border> <Border Width="{Binding ElementName=frontBorder, Path=ActualWidth}" Height="{Binding ElementName=frontBorder, Path=ActualHeight}" Opacity="0.2" BorderBrush="Transparent"> <Border.OpacityMask> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <LinearGradientBrush.GradientStops> <GradientStop Offset="0" Color="Black"/> <GradientStop Offset=".6" Color="Transparent"/> </LinearGradientBrush.GradientStops> </LinearGradientBrush> </Border.OpacityMask> <Border.Background> <VisualBrush Visual="{Binding ElementName=frontBorder}"> <VisualBrush.Transform> <ScaleTransform ScaleX="1" ScaleY="-1" CenterX="52.5" CenterY="37.5" /> </VisualBrush.Transform> </VisualBrush> </Border.Background> </Border> </StackPanel> <StackPanel x:Name="back" RenderTransformOrigin="0.5,0.5"> <StackPanel.RenderTransform> <ScaleTransform ScaleX="0"/> </StackPanel.RenderTransform> <Border Name="backBorder" BorderBrush="Yellow" BorderThickness="2" Width="Auto" Height="Auto"> <Button Margin="0" Width="105" Background="Blue" Name="blueButton" Height="75" Click="FlipButton_Click"/> </Border> <Border Width="{Binding ElementName=backBorder, Path=ActualWidth}" Height="{Binding ElementName=backBorder, Path=ActualHeight}" Opacity="0.2" BorderBrush="Transparent"> <Border.OpacityMask> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <LinearGradientBrush.GradientStops> <GradientStop Offset="0" Color="Black"/> <GradientStop Offset=".6" Color="Transparent"/> </LinearGradientBrush.GradientStops> </LinearGradientBrush> </Border.OpacityMask> <Border.Background> <VisualBrush Visual="{Binding ElementName=backBorder}"> <VisualBrush.Transform> <ScaleTransform ScaleX="1" ScaleY="-1" CenterX="52.5" CenterY="37.5" /> </VisualBrush.Transform> </VisualBrush> </Border.Background> </Border> </StackPanel> <Button Grid.Row="1" Click="FlipButton_Click" Height="19.45" HorizontalAlignment="Left" VerticalAlignment="Top" Width="76">Flip</Button> <TextBlock Grid.Row="2" Grid.Column="0" Foreground="DarkRed" Height="19.45" HorizontalAlignment="Left" VerticalAlignment="Top" Width="76" Text="{Binding ElementName=front, Path=(UIElement.RenderTransform).(ScaleTransform.ScaleX)}"/> <TextBlock Grid.Row="3" Grid.Column="0" Foreground="DarkBlue" Height="19.45" HorizontalAlignment="Left" VerticalAlignment="Top" Width="76" Text="{Binding ElementName=back, Path=(UIElement.RenderTransform).(ScaleTransform.ScaleX)}"/> </Grid> </Window> Code-behind: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Media.Animation; namespace FlipTest { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); } bool flipped = false; private void FlipButton_Click(object sender, RoutedEventArgs e) { Storyboard sbFlip = (Storyboard)Resources["sbFlip"]; Storyboard sbFlipBack = (Storyboard)Resources["sbFlipBack"]; if (flipped) { sbFlipBack.Begin(); flipped = false; } else { sbFlip.Begin(); flipped = true; } } } }

    Read the article

  • How to draw an UIImageView in -drawRect:?

    - by mystify
    I'm trying since 5 hours now: - (void)drawRect:(CGRect)rect { // flip the wrong coordinate system CGContextTranslateCTM(context, 0.0f, rect.size.height); //shift the origin up CGContextScaleCTM(context, 1.0f, -1.0f); //flip the y-axis CGContextDrawImage(context, myImgView.frame, myImageView.image.CGImage); } The problem: While the image draws correctly, the coordinates specified by the UIImageView frame are completely useless. The image appears placed completely wrong on screen. I guess I must also flip the CGRect of the UIImageView? But how?

    Read the article

  • flipping 2d components in java

    - by aniket
    i am trying to flip a pentahex (5 hexagons joined at their sides). Is it possible to do so in Java? I mean suppose 2 of the 3 hexagons are in one quadrant can I change their quadrant? It is similar to what we do to flip images in Paint. The same utility I am trying to perform in Java. I have heard about Affine transform wherein it makes use of a bit called TYPE_FLIP, but I am not sure how to use it. Any small example would be of great help. Note: I do not want to flip images, but actual 2D objects.

    Read the article

  • Flipping an image using a one dimensional array of characters.

    - by Jeff
    I have the data of an image loaded into memory as a one dimensional array. Since I'm trying to use OpenGL to draw it, and since it reads from the bottom up, I want to try and flip the elements of the array before they're sent to OpenGL. Maybe there's a way to tell OpenGL to read from the top to the bottom? Anyways, I tried using a few methods of sorting arrays and they also flip the image horizontally, which is very much like the original problem. So can I flip the data only one way?

    Read the article

  • Truly Random Numbers

    German researchers use a "flip-flop" to improve random number generator Random number generation - Algorithms - Pseudorandom Numbers - Math - Recreation

    Read the article

  • How do I fix dragging windows to the adjacent workspace?

    - by Bill O'Dwyer
    I installed CompizConfig-Settings-Manager and I put on all the settings I liked and had in 11.10, including the ability to drag my windows to the adjacent workspace. It's under the Desktop Wall section, on the Edge Flipping tab and I've checked "Edge Flip Move" and "Edge Flip DnD." In 11.10, the movement was smooth between each workspace, and the window would still be "grabbed" in the same place. In 12.04, it's leaving the window behind and the mouse appears to be "grabbing" nothing, but I'm still holding onto the window, and I can still move and place it within the workspace (or indeed the previous workspace as it won't appear in the desired place until I drag the mouse all the way to the edge of the screen). Any way to fix this? I'm running 12.04 beta 2.

    Read the article

  • Fliping the video stream in Sony Vegas Studio!

    - by NoCanDo
    How do I flip a video stream, making it effectively appear to run backwards. For example, I've got a 6 second video stream. I cut it at 2, 4, 6, so I've got now 3 seperate streams with 2 seconds each. 1-2 ; 3-4; 5-6 - That how it'll be displayed normal. Now what I want to do in Sony Vegas is to copy/paste and flip a selected stream. Let say: 1-2; 3-4; 3'-4' (copy/pasted); 5-6 - Now I've got a video stream with 8 seconds. Now I want to flip this copy pasted making it effectively run backwards. 1-2; 3-4; 4'-3'; 5-6. The idea is I want something like a movie, it goes, and goes and goes, then a text appears "WAIT! What just happend?", then the movie goes back to second 3 (1-2-3-4-'WAIT, WHAT JUST HAPPEND?'-4-3-4-5-6. I hope you get what I want to do in Sony Vegas.

    Read the article

  • Flipping the video stream in Sony Vegas Studio!

    - by NoCanDo
    How do I flip a video stream, making it effectively appear to run backwards? For example, I've got a 6 second video stream. I cut it at 2, 4, 6, so I've got now 3 seperate streams with 2 seconds each. 1-2 ; 3-4; 5-6 - That's how it'll be displayed normally. Now what I want to do in Sony Vegas is to copy/paste and flip a selected stream. Let say: 1-2; 3-4; 3'-4'; 5-6 - The second 3-4 is copy/pasted; now I've got a video stream with 8 seconds. Now I want to flip this copy pasted making it effectively run backwards. 1-2; 3-4; 4'-3'; 5-6. The idea is I want something like a movie, it goes, and goes and goes, then a text appears "WAIT! What just happend?", then the movie goes back to second 3. 1-2-3-4-'WAIT! What just happened?'-4-3-4-5-6. I hope you get what I want to do in Sony Vegas.

    Read the article

  • popViewControllerAnimated not working, but back button works

    - by Manu
    Hi, I am creating an application based on the Utility template. The main screen consists of a menu with several buttons, each of which creates a different flip-side view. In one of those flip-side views I also configured a Navigation Controller, which works perfectly as long as I have the NavigationBar activated... I can push the view but I have to use the "back" button to return to my flip-side view, which would be the root of the Navigation Controller. The problem comes if I try to go back using "popViewControllerAnimated", properly configured with a button, instead of the "back" button of the NavigationBar. My application crashes for some reason and I am not able to understand why. I could just use the "back" button in the NavigationBar and forget about the problem, but I would prefer to have my own button in order to go back. My app consists of the following: My APPDelegate.m: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { MenuViewController *menuController = [[MenuViewController alloc] initWithNibName:@"MenuView" bundle:nil]; self.menuViewController = menuController; [menuController release]; menuViewController.view.frame = [UIScreen mainScreen].applicationFrame; [window addSubview:[menuViewController view]]; [window makeKeyAndVisible]; return YES; } MenuViewController.m starting my flip-side view: - (IBAction)showFuelUpliftView { FuelUpliftViewController *controller = [[FuelUpliftViewController alloc] initWithNibName:@"FuelUpliftView" bundle:nil]; controller.delegate = self; controller.title = @"Fuel Uplift"; UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller]; [navController setNavigationBarHidden: NO]; navController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; [self presentModalViewController:navController animated:YES]; [navController release]; [controller release]; } FuelUpliftViewController.m, where I push the second view of the NavigationController with a button: - (IBAction)showFuelUplift2View:(id)sender { UIViewController *controller = [[UIViewController alloc] initWithNibName:@"FuelUplift2View" bundle:nil]; controller.title = @"Settings"; [self.navigationController pushViewController:controller animated:YES]; [controller release]; } And finally, my FuelUplift2ViewController.m, where the app crashes when trying to go back: - (IBAction)backFromFuelUplift2View { [self.navigationController popViewControllerAnimated:YES]; } I do not know if all this makes sense, I am currently beginning with my first application and am still learning thanks to the traditional trial an error method. Nevertheless, I cannot see the reason for this problem and would appreciate any help I can get. Thanks very much, Manu

    Read the article

  • New View when device is rotated

    - by Sebastian
    Hi, I want to call "presentmodalviewcontroller" when the iPhone / iPod Touch is rotated to landscape mode with a flip animation. When it gets rotated back to portrait, I want to present the first view again, again with the flip animation. Weren't able to find something working on the web :( I'm sure you can help me :) Thanks a lot ! Sebastian

    Read the article

  • Android Add Icon to homescreen to set member variable in broadcast receiver

    - by JonF
    I would like to add some sort of icon that a user can press in order to flip a variable in a broadcast receiver my app uses. Basically I just can a icon that they can press which will flip the value of a boolean in the broadcast receiver, and change the icon to indicate something happened. I think I need to do something with a widget? Could anyone point me in the direction of some tutorial I could check out?

    Read the article

  • Image animation problem in silverlight

    - by Jak
    Hi followed " http://www.switchonthecode.com/tutorials/silverlight-3-tutorial-planeprojection-and-perspective-3d#comment-4688 ".. the animation is working fine. I am new to silver light. when i use dynamic image from xml instead of static image as in tutorial,.. it is not working fine, please help me on this. i used list box.. for this animation effect do i need to change listbox to some other arrangement ? if your answer yes means, pls give me some sample code. Thanks in advance. Xaml code: <ListBox Name="listBox1"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <Image Source="{Binding imgurl}" HorizontalAlignment="Left" Name="image1" Stretch="Fill" VerticalAlignment="Top" MouseLeftButtonUp="FlipImage" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> My C# code: //getting image URL from xml XElement xmlads = XElement.Parse(e.Result); //i bind the url in to listBox listBox1.ItemsSource = from ads in xmlads.Descendants("ad") select new zestItem { imgurl = ads.Element("picture").Value }; public class zestItem { public string imgurl { get; set; } } private int _zIndex = 10; private void FlipImage(object sender, MouseButtonEventArgs e) { Image image = sender as Image; // Make sure the image is on top of all other images. image.SetValue(Canvas.ZIndexProperty, _zIndex++); // Create the storyboard. Storyboard flip = new Storyboard(); // Create animation and set the duration to 1 second. DoubleAnimation animation = new DoubleAnimation() { Duration = new TimeSpan(0, 0, 1) }; // Add the animation to the storyboard. flip.Children.Add(animation); // Create a projection for the image if it doesn't have one. if (image.Projection == null) { // Set the center of rotation to -0.01, which will put a little space // between the images when they're flipped. image.Projection = new PlaneProjection() { CenterOfRotationX = -0.01 }; } PlaneProjection projection = image.Projection as PlaneProjection; // Set the from and to properties based on the current flip direction of // the image. if (projection.RotationY == 0) { animation.To = 180; } else { animation.From = 180; animation.To = 0; } // Tell the animation to animation the image's PlaneProjection object. Storyboard.SetTarget(animation, projection); // Tell the animation to animation the RotationYProperty. Storyboard.SetTargetProperty(animation, new PropertyPath(PlaneProjection.RotationYProperty)); flip.Begin(); }

    Read the article

  • Jquery page turn with html or asp

    - by vishal
    I was asked by a client to create a bookflip (Page Turn) effect that did not require Flash. The imBookFlip plugin can load a book in an iframe or directly on the page. The book's pages can be set to turn when manually clicked only, begin auto flip (turn automatically) as soon as the html page loads, or begin auto flip when first page (front cover is clicked).

    Read the article

  • Stack Info button above UIView in Utility App

    - by bgw
    I've started creating a iPhone Utility app (main view and flip view). I want to draw some graphics in the Main view, so I dragged a UIView object onto it. This works, but I find that if I resize the UIView to fill the Main view, it covers the Info button that invokes the Flip view. Is there any way to get the Info button to appear on top of the UIView? In IB? In code?

    Read the article

  • Undefined function

    - by Luke
    Just a simple problem for most of you i'm sure. I have a function addTeamFixtures and it calls on a function flip. That function is defined later in the script. But I don't think it is happy with that. The code where it calls the function: $rounds[$round][0] = flip($rounds[$round][0]); Any ideas?

    Read the article

  • what is the best way to use loops to detect events while the main loop is running?

    - by yao jiang
    I am making an "game" that has pathfinding using pygame. I am using Astar algo. I have a main loop which draws the whole map. In the loop I check for events. If user press "enter" or "space", random start and end are selected, then animation starts and it will try to get from start to end. My draw function is stupid as hell right now, it works as expected but I feel that I am doing it wrong. It'll draw everything to the end of the animation. I am also detecting events in there as well. What is a better way of implementing the draw function such that it will draw one "step" at a time while checking for events? animating = False; while loop: check events: if not animating: # space or enter press will choose random start/end coords if enter_pressed or space_pressed: start, end = choose_coords route = find_route(start, end) draw(start, end, grid, route) else: # left click == generate an event to block the path # right click == user can choose a new destination if left_mouse_click: gen_event() reroute() elif right_mouse_click: new_end = new_end() new_start = current_pos() route = find_route(new_start, new_end) draw(new_start, new_end, grid, route) # draw out the grid def draw(start, end, grid, route_coord): # draw the end coords color = red; pick_image(screen, color, width*end[1],height*end[0]); pygame.display.flip(); # then draw the rest of the route for i in range(len(route_coord)): # pausing because we want animation time.sleep(speed); # get the x/y coords x,y = route_coord[i]; event_on = False; if grid[x][y] == 2: color = green; elif grid[x][y] == 3: color = blue; for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 3: print "destination change detected, rerouting"; # get mouse position, px coords pos = pygame.mouse.get_pos(); # get grid coord c = pos[0] // width; r = pos[1] // height; grid[r][c] = 4; end = [r, c]; elif event.button == 1: print "user generated event"; pos = pygame.mouse.get_pos(); # get grid coord c = pos[0] // width; r = pos[1] // height; # mark it as a block for now grid[r][c] = 1; event_on = True; if check_events([x,y]) or event_on: # there is an event # mark it as a block for now grid[y][x] = 1; pick_image(screen, event_x, width*y, height*x); pygame.display.flip(); # then find a new route new_start = route_coord[i-1]; marked_grid, route_coord = find_route(new_start, end, grid); draw(new_start, end, grid, route_coord); return; # just end draw here so it wont throw the "index out of range" error elif grid[x][y] == 4: color = red; pick_image(screen, color, width*y, height*x); pygame.display.flip(); # clear route coord list, otherwise itll just add more unwanted coords route_coord_list[:] = [];

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >