3/21/15

iOS Scene Kit Jet

The Scene Kit 3D Jet in flight with clockwise roll, in iPad airspace.
Trailing transparent snapshots are 3D model clones of the jet at variable intervals.
Use SCNView allowsCameraControl to zoom and rotate the entire scene, including models, for different points of view.

* The 3D Jet ship mesh is part of the default Xcode Scene Kit project.





@import SceneKit;
@import GLKit;


@interface ESJet: NSObject

    @property (nonatomic) SCNNode * node;
    @property (nonatomic, assign) CGFloat velocity;
    @property (nonatomic, assign) BOOL roll;
    @property (nonatomic, assign) CGFloat rollRate;


    -(void)update:(NSTimeInterval)aTime isVisible:(BOOL)aVisible;

    -(instancetype)init;
    -(instancetype)initWithNode:(SCNNode *)aNode zPosition:(int)aZPosition;
@end


@implementation ESJet

    -(void)update:(NSTimeInterval)aTime isVisible:(BOOL)aVisible;
    {
        CGFloat nextZPosition = self.velocity;

     // NSLog(@"jet position: %@", NSStringFromGLKVector3(SCNVector3ToGLKVector3(self.node.position)));

        if (aVisible)
        {
            NSLog(@"jet visible");
        }
        else
        {
            //when jet flys off right-side of screen, reposition on left
            NSLog(@"...");
            nextZPosition = -(self.node.position.x * 1.95);
        }

        GLKVector3 nextFramePosition = GLKVector3Make(0, 0, nextZPosition);
        GLKMatrix4 transform = SCNMatrix4ToGLKMatrix4(self.node.transform);
        self.node.transform = SCNMatrix4FromGLKMatrix4(GLKMatrix4TranslateWithVector3(transform, nextFramePosition));


        if (self.roll)
        {
            //rotate jet ~ 1 degree per frame on X axis
            GLKQuaternion rot = GLKQuaternionMakeWithAngleAndAxis((M_1_PI * self.rollRate), 1, 0, 0);
            GLKQuaternion orientation = GLKQuaternionMultiply(rot, GLKQuaternionMake(self.node.orientation.x,
                                                                                     self.node.orientation.y,
                                                                                     self.node.orientation.z,
                                                                                     self.node.orientation.w));

            self.node.orientation = SCNVector4Make(orientation.x, orientation.y, orientation.z, orientation.w);
        }
    }

    -(instancetype)init
    {
        if (self = [super init])
        {
            self.velocity = 0.33f;
            self.rollRate = (self.velocity * 0.364);
        }

        return self;
    }

    -(instancetype)initWithNode:(SCNNode *)aNode zPosition:(int)aZPosition
    {
        if ([self init])
        {
            self.node = aNode;
            [self.node removeAllActions];

            //rotate jet 90 degrees on Y axis, facing right edge of screen
            GLKQuaternion rot = GLKQuaternionMakeWithAngleAndAxis(M_PI_2, 0, 1, 0);
            self.node.orientation = SCNVector4Make(rot.x, rot.y, rot.z, rot.w);
            self.node.position = SCNVector3Make(0, 0, aZPosition);
        }

        return self;
    }
@end


@interface GameViewController: UIViewController<SCNSceneRendererDelegate>
@end

@implementation GameViewController
{
    SCNScene * skScene;
    SCNView * skView;
    SCNNode * cameraNode;

    NSMutableArray * nodeSnapshots;
    NSDate * frameTimer;

    ESJet * jet;
}

    -(void)viewDidLoad
    {
        //default project code here...

        skScene = scene;
        skView = scnView;
        skView.delegate = self;
        skView.playing = YES;

        nodeSnapshots = [NSMutableArray array];

        jet = [[ESJet alloc] initWithNode:ship zPosition:-20];
        jet.roll = YES;
    }

    //SCNSceneRendererDelegate
    -(void)renderer:(id<SCNSceneRenderer>)aRenderer updateAtTime:(NSTimeInterval)time
    {
                void (^cloneNode)() = ^
                { 
                    dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
                    dispatch_async(q, ^
                                   {
                                       SCNNode * clone = [jet.node clone];
                                       clone.opacity = 0.20f;
                                       [nodeSnapshots addObject:clone];
                                       [skScene.rootNode addChildNode:clone];
                                   });
                };

                void (^cloneNodeOnTimer)(float) = ^(float interval)
                {
                    if ((frameTimer == nil) || (frameTimer.timeIntervalSinceNow <= -interval))
                    {
                        frameTimer = [NSDate date];
                        cloneNode();
                    }
                };


        //SCNSceneRenderer protocol
        BOOL nodeIsVisible = [aRenderer isNodeInsideFrustum:jet.node withPointOfView:cameraNode];

        if (nodeIsVisible)
        {
            cloneNodeOnTimer(0.6f);
        }
        else
        {
            skView.playing = NO;
            jet.node.hidden = YES;

            if (nodeSnapshots.count > 0)
            {
                //remove transparency from last cloned node
                ((SCNNode *)[nodeSnapshots lastObject]).opacity = 1.0;
            }
        }


        [jet update:time isVisible:nodeIsVisible];
    }

    //tap any node to render new scene
    -(void)handleTap:(UIGestureRecognizer*)gestureRecognize
    {
        CGPoint tp = [gestureRecognize locationInView:skView];

        NSArray * hitTestResults = [skView hitTest:tp options:nil];
        if (hitTestResults.count > 0)
        {
            [nodeSnapshots enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL * stop)
            {
                [(SCNNode *)obj removeFromParentNode];
            }];

            [nodeSnapshots removeAllObjects];

            jet.node.hidden = NO;
            skView.playing = YES;
        }
    }

3/15/15

iOS Gradient View with Clipped Path

Custom gradient view with support for 3 shapes: default, circle, circle-outline.
Copy path with CGPathCreateCopyByStrokingPath, clip, then draw gradient.




//swift

import UIKit

class ViewController: UIViewController
{
    override func viewDidLoad()
    {
        super.viewDidLoad()

        var gv = [ESGradientView]()
        var x = 100
        for i in 0...5
        {
            var g = ESGradientView()
            g.frame = CGRect(x:x, y:200, width:100, height:100)
            g.gradientColors = i < 3 ? g.gradientColors : [UIColor.redColor().CGColor, UIColor.blackColor().CGColor]
            gv.append(g)
            self.view.addSubview(g)
            x += 110
        }

        gv[1].shape = .Circle
        gv[2].shape = .CircleOutline
        gv[4].shape = .Circle
        gv[5].shape = .CircleOutline
        gv[5].circleOutlineWidth = 1
    }
}


class ESGradientView: UIView
{

    enum Shape
    {
        case Default, Circle, CircleOutline
    }

    var shape = Shape.Default
    var circleOutlineWidth:Int = 4
    var gradientColors = [UIColor.redColor().CGColor, UIColor.blueColor().CGColor]
    var gradientLocations:[CGFloat] = [0, 1]
    var gradientEndOffset:CGFloat = 20


    override func drawRect(rect: CGRect)
    {
        var context = UIGraphicsGetCurrentContext()

        if (shape == .Circle)
        {
            let path = getCirclePath(1)
            path.addClip()
        }
        else if (shape == .CircleOutline)
        {
            let path = getCirclePath(circleOutlineWidth + 2)
            var pathRef = CGPathCreateCopyByStrokingPath(path.CGPath, nil, CGFloat(circleOutlineWidth), kCGLineCapRound, kCGLineJoinRound, 1)
            UIBezierPath(CGPath: pathRef).addClip()
        }

        var gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), gradientColors, gradientLocations)
        let gradientEndPoint = CGPointMake(bounds.width - gradientEndOffset, bounds.height - gradientEndOffset)
        CGContextDrawLinearGradient(context, gradient!, CGPointZero, gradientEndPoint, UInt32(kCGGradientDrawsAfterEndLocation))
    }   

    func getCirclePath(inset:Int) -> UIBezierPath
    {
        let center = CGFloat(bounds.width * 0.5)
        let radius = CGFloat(center * CGFloat(100 - inset) * 0.01)
        let centerPoint = CGPointMake(center, center)
        var cp = UIBezierPath(arcCenter:centerPoint, radius:radius, startAngle:0, endAngle:CGFloat(M_PI * 2), clockwise:true)

        return cp
    }
}

3/7/15

We Can Has WWDC Session Videoz Descriptions?

Javascript to show all WWDC session video descriptions.
Expands sessions to show descriptions and view search matches. *
To use, copy and paste script into browser console and then call show() function.

var sessions = $$('li.session')

function show()
{
    toggle('session active');
}

function hide()
{
    toggle('session');
}

function toggle(css)
{
    for (var i = 0; i < sessions.length; i++)
    {
        sessions[i].className = css;
    }
}

WWDC
2014
2013
2012
2011
2010


* Usability clue for Apple Web Dev Team
"We can't wait to show you."