From 357db9a248183e70c02423564ef8df0b2c920147 Mon Sep 17 00:00:00 2001 From: Eryn Wells Date: Sun, 6 Aug 2017 08:24:50 -0700 Subject: [PATCH] [all] Add a ball on click; regenerate the field on right click --- Metaballs/ViewController.swift | 23 +++++++++++++++++++++-- MetaballsKit/Metaballs.swift | 4 ++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/Metaballs/ViewController.swift b/Metaballs/ViewController.swift index 1d1febf..35521da 100644 --- a/Metaballs/ViewController.swift +++ b/Metaballs/ViewController.swift @@ -41,17 +41,36 @@ class ViewController: NSViewController, RendererDelegate { super.viewWillAppear() renderer.mtkView(metalView, drawableSizeWillChange: metalView.drawableSize) for _ in 1...10 { - let r = Float(20 + arc4random_uniform(50)) - field.add(ballWithRadius: r) + addBallWithRandomRadius() } } + override func mouseDown(with event: NSEvent) { + addBallWithRandomRadius() + } + + override func rightMouseDown(with event: NSEvent) { + field.clear() + for _ in 1...10 { + addBallWithRandomRadius() + } + } + + // MARK: - Private + private func newErrorView() -> NSView { let view = NSView() view.layer?.backgroundColor = NSColor.red.cgColor return view } + private func addBallWithRandomRadius() { + let base = UInt32(view.bounds.width * 0.05) + let variance = UInt32(base * 2) + let r = Float(base + arc4random_uniform(variance)) + field.add(ballWithRadius: r) + } + // MARK: - RendererDelegate var renderSize: CGSize { diff --git a/MetaballsKit/Metaballs.swift b/MetaballsKit/Metaballs.swift index f229ec8..a4e201d 100644 --- a/MetaballsKit/Metaballs.swift +++ b/MetaballsKit/Metaballs.swift @@ -110,6 +110,10 @@ public class Field { populateBallBuffer() } + public func clear() { + balls.removeAll(keepingCapacity: true) + } + // MARK: - Metal Configuration private var device: MTLDevice?