Thursday, 25 April 2013

Python: re.sub does not replace all matches

Trying to replace patterns in a multiline string:

re.sub(pattern, replacement, string, re.M)

This does not replace all matches, because the fourth parameter is the number of matches to be replaced. The fix is

re.sub(pattern, replacement, string, flags=re.M)

Saturday, 13 April 2013

iOS: OpenGL ES: implementing color picking

Color picking is a method to pick an object by rendering different objects with different color and reading pixel at the picking point.

To implement color picking for OpenGL ES on iOS, you need to make two changes:

1. in your touch handler, record the location of the touch and convert it to OpenGL window coordinates.

2. in your renderer, add a special rendering pass before your regular rendering pass. In this special rendering pass, clean the scene,  disable lighting and rendering each object with different color, then read the pixel at the saved picking position and convert it to object id. After that, clean the scene and render again with your normal rendering pass. Since the result of the special rendering pass is overwritten by the normal render pass, the user never sees it.

iOS: OpenGL ES disable/enable lighting changes light position

If you disable lighting then re-enable it, the light position will depend on the modelview matrix when you enable the lighting. This can causes light position to change between frames. This may be a bug of iOS 6.1.

If you want to keep the light position fixed when re-enable lighting, you need to set light position again after re-enabling lighting. Also you need to make sure the modelview matrix is the same each time you set the light position.

iOS: Adding UIGestureRecognizer causes subview not responding to touches

If you have an UIView which contains some subview such as buttons, adding UIGestureRecognizer will cause these subviews not responding to touches. The reason is by default the gesture recognizer handles all touches and discard them, therefore the subviews do not receive any touch.

The fix is adding


    recognizer.cancelsTouchesInView = NO;

http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIGestureRecognizer_Class/Reference/Reference.html

Friday, 12 April 2013

iOS: OpenGL window coordinates calculated from location in UIView is wrong

Usually a point's OpenGL window coordinates can be calculated from its location in UIView by:

    CGPoint pt = [gestureRecognizer locationInView:self];
    pt.y = self.bounds.size.height - pt.y;

However this calculation could be wrong if OpenGL viewport size does not match UIView size. 

I tried to resize OpenGL viewport at various point to match UIView size but did not succeed. Finally I got a workaround which allows me to get the correct OpenGL window coordinates:

    float viewport[4];
    glGetFloatv(GL_VIEWPORT, viewport);
    pt.y = (1.0f - pt.y/self.bounds.size.height) * viewport[3];