Skip to content

Commit

Permalink
Partial port of the LayerPolynomials example from Chapter 32.
Browse files Browse the repository at this point in the history
  • Loading branch information
Tim Burks committed May 23, 2008
1 parent 6a7f7e9 commit 9a28962
Show file tree
Hide file tree
Showing 10 changed files with 3,263 additions and 0 deletions.
Binary file not shown.
2,639 changes: 2,639 additions & 0 deletions 32_CoreAnimation/LayerPolynomials/English.lproj/MainMenu.nib/designable.nib

Large diffs are not rendered by default.

Binary file not shown.
28 changes: 28 additions & 0 deletions 32_CoreAnimation/LayerPolynomials/Info.plist
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>com.yourcompany.Polynomials</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>NSMainNibFile</key>
<string>MainMenu</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
</dict>
</plist>
143 changes: 143 additions & 0 deletions 32_CoreAnimation/LayerPolynomials/Nu/main.nu
@@ -0,0 +1,143 @@
;; file main.nu
;; discussion Entry point for a Nu program.
;; copyright Copyright (c) 2008 Tim Burks, Neon Design Technology, Inc.

(import Cocoa) ;; bridgesupport
(load "console") ;; interactive console

(set MARGIN 10)

(global M_PI 3.1415927)
(global hypot (NuBridgedFunction functionWithName:"hypot" signature:"ddd"))
(global random (NuBridgedFunction functionWithName:"random" signature:"l"))
(global cos (NuBridgedFunction functionWithName:"cos" signature:"dd"))
(global sin (NuBridgedFunction functionWithName:"sin" signature:"dd"))

(class PolynomialView is NSView
(ivar (id) polynomials (BOOL) blasted)

(- (id)initWithFrame:(NSRect)frame is
(super initWithFrame:frame)
(set @polynomials (array))
(set @blasted NO)
self)

(- (void)resizeAndRedrawPolynomialLayers is
(set b ((self layer) bounds))
(set b (CGRectInset b MARGIN MARGIN))
(NSAnimationContext beginGrouping)
((NSAnimationContext currentContext) setDuration:0)
(set polynomialLayers ((self layer) sublayers))
(polynomialLayers each:
(do (layer)
(layer setFrame:(list ((layer frame) 0)
((layer frame) 1)
(b 2)
(b 3)))
(layer setNeedsDisplay)))
(NSAnimationContext endGrouping))

(- (void)setFrameSize:(NSSize)newSize is
(super setFrameSize:newSize)
(unless (self inLiveResize))
(self resizeAndRedrawPolynomialLayers))

(- (void)viewDidEndLiveResize is
(self resizeAndRedrawPolynomialLayers))

(- (void)blastem:(id)sender is
(NSAnimationContext beginGrouping)
((NSAnimationContext currentContext) setDuration:3.0)
(set polynomialLayers ((self layer) sublayers))
(polynomialLayers each:
(do (layer)
(if @blasted
(then (set p (list MARGIN MARGIN)))
(else (set p (self randomOffViewPosition))))
(layer setPosition:p)))
(NSAnimationContext endGrouping)
(self willChangeValueForKey:"blasted")
(set @blasted (not @blasted))
(self didChangeValueForKey:"blasted"))

(- (NSPoint)randomOffViewPosition is
(set bounds (self bounds))
(set radius (hypot (bounds third) (bounds fourth)))
(set angle (* 2.0 M_PI (/ (% (random) 360) 360.0)))
(list (* radius (cos angle)) (* radius (sin angle))))

(- (void)createNewPolynomial:(id)sender is
(set p ((Polynomial alloc) init))
(@polynomials addObject:p)
(set layer (CALayer layer))
(set b ((self layer) bounds))
(set b (CGRectInset b MARGIN MARGIN))
(layer setAnchorPoint:'(0 0))
(layer setFrame:b)
(layer setDelegate:p)
(layer setCornerRadius:12)
(layer setBorderColor:(p color))
(layer setBorderWidth:3.5)
((self layer) addSublayer:layer)
(layer display)
(set anim (CABasicAnimation animationWithKeyPath:"position"))
(anim setFromValue:(NSValue valueWithPoint:(self randomOffViewPosition)))
(anim setToValue:(NSValue valueWithPoint:(list MARGIN MARGIN)))
(anim setDuration:1.0)
(set f (CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear))
(anim setTimingFunction:f)
(layer addAnimation:anim forKey:"whatever"))

(- (void)deleteRandomPolynomial:(id)sender is
(set polynomialLayers ((self layer) sublayers))
(if (or (eq polynomialLayers nil) (eq (polynomialLayers count) 0))
(NSBeep)
(return))
(set i (% (random) (polynomialLayers count)))
(set toPoint (self randomOffViewPosition))
(set layerToPull (polynomialLayers objectAtIndex:i))
(set anim (CABasicAnimation animationWithKeyPath:"position"))
(anim setValue:layerToPull forKey:"representedPolynomialLayer")
(anim setFromValue:(NSValue valueWithPoint:(NSMakePoint MARGIN MARGIN)))
(anim setToValue:(NSValue valueWithPoint:toPoint))
(anim setDuration:1.0)
(set f (CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear))
(anim setTimingFunction:f)
(anim setDelegate:self)
(layerToPull addAnimation:anim forKey:"whatever")
(layerToPull setPosition:toPoint))

(- (void)animationDidStop:(id)anim finished:(BOOL)flag is
(NSLog "deleting polynomial")
;; FIXME: layer flashes at Position 0,0 before removal
(set layerToPull (anim valueForKey:"representedPolynomialLayer"))
(set p (layerToPull delegate))
(@polynomials removeObjectIdenticalTo:p)
(layerToPull removeFromSuperlayer))

(- (void)drawRect:(NSRect)rect is
(set bounds (self bounds))
((NSColor whiteColor) set)
(NSBezierPath fillRect:bounds)))

(set SHOW_CONSOLE_AT_STARTUP nil)

;; @class ApplicationDelegate
;; @discussion Methods of this class perform general-purpose tasks that are not appropriate methods of any other classes.
(class ApplicationDelegate is NSObject

;; This method is called after Cocoa has finished its basic application setup.
;; It instantiates application-specific components.
;; In this case, it constructs an interactive Nu console that can be activated from the application's Window menu.
(- (void) applicationDidFinishLaunching:(id) sender is
(set $console ((NuConsoleWindowController alloc) init))
(if SHOW_CONSOLE_AT_STARTUP ($console toggleConsole:self))))

;; install the delegate and keep a reference to it since the application won't retain it.
((NSApplication sharedApplication) setDelegate:(set $delegate ((ApplicationDelegate alloc) init)))

;; this makes the application window take focus when we've started it from the terminal (or with nuke)
((NSApplication sharedApplication) activateIgnoringOtherApps:YES)

;; run the main Cocoa event loop
(NSApplicationMain 0 nil)
21 changes: 21 additions & 0 deletions 32_CoreAnimation/LayerPolynomials/Polynomial.h
@@ -0,0 +1,21 @@
//
// Polynomial.h
// Polynomials
//
// Created by Aaron Hillegass on 11/27/07.
// Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import <Cocoa/Cocoa.h>

@interface Polynomial : NSObject {
__strong CGFloat * terms;
int termCount;
__strong CGColorRef color;
}
- (id)init;
- (float)valueAt:(float)x;
- (void)drawInRect:(CGRect)b
inContext:(CGContextRef)ctx;
- (CGColorRef)color;
@end
97 changes: 97 additions & 0 deletions 32_CoreAnimation/LayerPolynomials/Polynomial.m
@@ -0,0 +1,97 @@
//
// Polynomial.m
// Polynomials
//
// Created by Aaron Hillegass on 11/27/07.
// Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "Polynomial.h"
#import <QuartzCore/QuartzCore.h>

#define HOPS (100)
#define RANDFLOAT() (random() % 128 / 128.0)

static CGRect funcRect = {-20, -20, 40, 40};

@implementation Polynomial
- (id)init
{
[super init];
termCount = (random() % 3) + 2;
terms = NSAllocateCollectable(termCount * sizeof(CGFloat), NSScannedOption);
color = CGColorCreateGenericRGB(RANDFLOAT(), RANDFLOAT(), RANDFLOAT(), 0.7);
NSMakeCollectable(color);

int i;
for (i = 0; i < termCount; i++) {
terms[i] = 5.0 - (random() % 100) / 10.0;
}

return self;
}
- (float)valueAt:(float)x
{
float result = 0;
int i;
for (i = 0; i < termCount; i++) {
result = (result * x) + terms[i];
}
return result;
}

- (void)drawInRect:(CGRect)b inContext:(CGContextRef)ctx
{
NSLog(@"drawing");
CGAffineTransform tf;
tf = CGAffineTransformMake(b.size.width / funcRect.size.width, 0,
0, b.size.height / funcRect.size.height,
b.size.width/2, b.size.height/2);
CGContextSaveGState(ctx);
CGContextConcatCTM(ctx, tf);
CGContextSetStrokeColorWithColor(ctx, color);
CGContextSetLineWidth(ctx, 0.4);
float distance = funcRect.size.width / HOPS;
float currentX = funcRect.origin.x;
BOOL first = YES;
while (currentX <= funcRect.origin.x + funcRect.size.width) {
float currentY = [self valueAt:currentX];
if (first) {
CGContextMoveToPoint(ctx, currentX, currentY);
first = NO;
} else {
CGContextAddLineToPoint(ctx, currentX, currentY);
}
currentX += distance;
}
CGContextStrokePath(ctx);
CGContextRestoreGState(ctx);

}

- (void)drawLayer:(CALayer *)layer
inContext:(CGContextRef)ctx
{
CGRect cgb = [layer bounds];
[self drawInRect:cgb
inContext:ctx];
}
- (id<CAAction>)actionForLayer:(CALayer *)layer
forKey:(NSString *)event
{
NSLog(@"action = %@", event);
return nil;
}


- (CGColorRef)color
{
return color;
}
- (void)finalize
{
NSLog(@"finalizing");
[super finalize];
}

@end

0 comments on commit 9a28962

Please sign in to comment.