-
Notifications
You must be signed in to change notification settings - Fork 5
/
JSMatrixCodeRainView.swift
400 lines (340 loc) · 15.5 KB
/
JSMatrixCodeRainView.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
//
// JSMatrixCodeRainView.swift
// matrixCodeRain
//
// Created by Shuo Zhang on 2016/9/30.
// Copyright © 2016年 Jon Showing. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
//import CoreMotion
fileprivate class PingThread: Thread{
var pingTaskIsRunning = false
var semaphore = DispatchSemaphore(value: 0)
override func main(){
while !self.isCancelled{
pingTaskIsRunning = true
DispatchQueue.main.async {
self.pingTaskIsRunning = false
self.semaphore.signal()
}
Thread.sleep(forTimeInterval: 1/30.0)
if pingTaskIsRunning {
NSLog("Delayed!")
}
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
}
}
}
fileprivate struct JSMatrixConstants {
static let maxGlowLength: Int = 3 // Characters
static let minTrackLength: Int = 8 // Characters
static let maxTrackLength: Int = 40 // Characters
static let charactersSpacing: CGFloat = 0.0 // pixel
static let characterChangeRate = 0.9
static let firstDropShowTime = 2.0 // Time between the First drop and the later
// Configurable
static let speed: TimeInterval = 0.15 // Seconds that new character pop up
static let newTrackComingLap: TimeInterval = 0.4
static let tracksSpacing: Int = 5
}
fileprivate class JSMatrixTrack: Hashable, Equatable {
var glowLength: Int
var fadeLength: Int
var totalLength: Int
var positionY: Int{
didSet{
if positionY > totalLength {
topY += (positionY - oldValue)
}
}
}
var trackNum: Int
var positionX: CGFloat{
return CGFloat(trackNum) * (JSMatrixDataSource.characterSize.width + 2.0)
}
var hashValue: Int{
return trackNum
}
var topY: Int = 0
weak var layer: JSMatrixTrackLayer?
weak var datasource: JSMatrixDataSource?
var timer: Timer?
static func ==(lhs: JSMatrixTrack, rhs: JSMatrixTrack) -> Bool{
return lhs.trackNum == rhs.trackNum
}
func getBrightness(currentTopY: Int, currentBottomY: Int) -> CGFloat{
let index = currentBottomY - currentTopY - 1
let rawData = 1 - CGFloat(index) / CGFloat(totalLength) // index = 0 is the brightest case
if index < glowLength {
return rawData * 1.2
}else if index > totalLength - fadeLength{
return rawData * 0.4
}else{
return rawData
}
}
init(length: Int, trackNum _trackNum: Int) {
self.positionY = 0
self.totalLength = length
self.trackNum = _trackNum
glowLength = Int(arc4random_uniform(UInt32(min(JSMatrixConstants.maxGlowLength, length))))
let fadeLengthRange = length - glowLength
fadeLength = Int(arc4random_uniform(UInt32(fadeLengthRange)))
timer = Timer.scheduledTimer(timeInterval: JSMatrixDataSource.sharedDataSource.speed, target: self, selector: #selector(self.drop), userInfo: nil, repeats: true)
}
@objc func drop(){
self.positionY += 1
if self.topY >= JSMatrixDataSource.maxNum{
self.layer?.removeFromSuperlayer()
timer?.invalidate()
}else{
self.layer?.drawAsync()
}
}
}
fileprivate class JSMatrixDataSource{
static let sharedDataSource: JSMatrixDataSource = JSMatrixDataSource()
static let trackNum: Int = Int(ceilf(Float(UIScreen.main.bounds.width / JSMatrixDataSource.characterSize.width)))
static let maxNum: Int = Int(ceilf(Float(UIScreen.main.bounds.height / JSMatrixDataSource.characterSize.height)))
static let characterSet = "abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890"
static let characterSize = "T".size(attributes: JSMatrixDataSource.getBrightnessAttributes(brightness: 1.0))
static func getCharacter() -> String{
let randomNum = Int(arc4random_uniform(UInt32(characterSet.characters.count)))
let randomIndex = characterSet.index(characterSet.startIndex, offsetBy: randomNum)
return String(characterSet[randomIndex])
}
static func getBrightnessAttributes(brightness: CGFloat) -> [String: Any]{
return [NSForegroundColorAttributeName: UIColor.init(hue: 127.0/360.0, saturation: 97.0/100.0, brightness: brightness, alpha: 1.0),
NSFontAttributeName: UIFont(name: "Matrix Code NFI", size: 17)!,
NSShadowAttributeName: {
let shadow = NSShadow()
shadow.shadowBlurRadius = 2.0
shadow.shadowColor = UIColor.init(white: 1.0, alpha: brightness)
shadow.shadowOffset = CGSize.zero
return shadow
}()]
}
var characters: [[String]] = []
var currentTracks: Set<JSMatrixTrack> = Set()
var speed: TimeInterval = JSMatrixConstants.speed
var newTrackComingLap: TimeInterval = JSMatrixConstants.newTrackComingLap
var trackSpacing: Int = JSMatrixConstants.tracksSpacing
init() {
for _ in 0..<JSMatrixDataSource.trackNum{
var track: [String] = []
for _ in 0..<JSMatrixDataSource.maxNum{
track.append(JSMatrixDataSource.getCharacter())
}
characters.append(track)
}
Timer.scheduledTimer(timeInterval: 0.02, target: self, selector: #selector(self.changeCharacter), userInfo: nil, repeats: true)
}
public func addTrack(track: JSMatrixTrack){
currentTracks.insert(track)
}
public func removeTrack(track: JSMatrixTrack){
currentTracks.remove(track)
}
public func getAvailiableTracks() -> [Int]{
var availiableTracks: [Int] = [Int](0...JSMatrixDataSource.trackNum)
for track in currentTracks{
if track.topY > JSMatrixDataSource.sharedDataSource.trackSpacing{ // All the track have been shown(and the gap is enough), new ones is free to go from above
continue
}else{
availiableTracks = availiableTracks.filter({ (trackNum) -> Bool in
if trackNum == track.trackNum{
return false
}
return true
})
}
}
return availiableTracks
}
@objc func changeCharacter(){
for track in 0..<JSMatrixDataSource.trackNum{
if arc4random_uniform(10) < UInt32(JSMatrixConstants.characterChangeRate * 10){
let randomNum = Int(arc4random_uniform(UInt32(JSMatrixDataSource.maxNum)))
let randomIndex = characters.index(0, offsetBy: randomNum)
characters[track][randomIndex] = JSMatrixDataSource.getCharacter()
}
}
}
}
fileprivate protocol JSMatrixTrackGeneratorDataSource: class{
func availiableTracks() -> [Int]
}
fileprivate protocol JSMatrixTrackGeneratorDelegate: class {
func didGeneratedNewTrack(newTrack: JSMatrixTrack)
}
fileprivate class JSMatrixTrackGenerator{
weak var delegate: JSMatrixTrackGeneratorDelegate?
weak var datasource: JSMatrixTrackGeneratorDataSource?
func getTrack() -> JSMatrixTrack{
if let availableTracks = datasource?.availiableTracks(){
let randomNum = Int(arc4random_uniform(UInt32(availableTracks.count - 1)))
let track = JSMatrixTrack(length: Int(arc4random_uniform(UInt32(JSMatrixDataSource.maxNum - JSMatrixConstants.minTrackLength))) + JSMatrixConstants.minTrackLength,
trackNum: availableTracks[randomNum])
return track
}else{
return JSMatrixTrack(length: Int(arc4random_uniform(UInt32(JSMatrixDataSource.maxNum - JSMatrixConstants.minTrackLength))) + JSMatrixConstants.minTrackLength,
trackNum: 0)
}
}
func getTrack(trackNumber: Int) -> JSMatrixTrack {
return JSMatrixTrack(length: Int(arc4random_uniform(UInt32(JSMatrixDataSource.maxNum - JSMatrixConstants.minTrackLength))) + JSMatrixConstants.minTrackLength,
trackNum: trackNumber)
}
func begin(){
Timer.scheduledTimer(timeInterval: JSMatrixDataSource.sharedDataSource.newTrackComingLap, target: self, selector: #selector(self.produceTrack), userInfo: nil, repeats: true)
}
@objc func produceTrack(){
self.delegate?.didGeneratedNewTrack(newTrack: self.getTrack())
}
}
fileprivate class JSMatrixTrackLayer: CALayer {
var track: JSMatrixTrack
init(track _track: JSMatrixTrack) {
track = _track
super.init()
self.contentsScale = UIScreen.main.scale
self.drawsAsynchronously = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func drawAsync() {
let track = self.track
DispatchQueue.global().async {
let size = self.bounds.size
UIGraphicsBeginImageContext(size)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let createdContext = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
if let context = createdContext{
context.saveGState()
let positionY: Int = track.positionY
var topY: Int = track.topY
if let col = track.datasource?.characters[track.trackNum]{
var range = 0..<positionY // track have not fully shown
if positionY > track.totalLength {
if positionY < JSMatrixDataSource.maxNum{ // track have fully shown
range = topY..<min(topY + track.totalLength, JSMatrixDataSource.maxNum)
}else{ // track is truncted at bottom
range = topY..<JSMatrixDataSource.maxNum
}
}
for characterIndex in range{
let character = col[characterIndex]
character.draw(in: CGRect(origin: CGPoint(x:0, y: CGFloat(topY) * JSMatrixDataSource.characterSize.height), size: JSMatrixDataSource.characterSize),
withAttributes: JSMatrixDataSource.getBrightnessAttributes(brightness: track.getBrightness(currentTopY: topY, currentBottomY: positionY)))
topY += 1
}
}
context.restoreGState()
self.render(in: context)
let resultImage = UIGraphicsGetImageFromCurrentImageContext();
DispatchQueue.main.async {
if let image = resultImage{
self.contents = image.cgImage
}
}
}
UIGraphicsEndImageContext()
}
}
}
class JSMatrixCodeRainView: UIView, JSMatrixTrackGeneratorDataSource, JSMatrixTrackGeneratorDelegate {
fileprivate lazy var datasource: JSMatrixDataSource = JSMatrixDataSource.sharedDataSource
fileprivate lazy var generator: JSMatrixTrackGenerator = {
$0.delegate = self
$0.datasource = self
return $0
}(JSMatrixTrackGenerator())
fileprivate lazy var containerLayer: CALayer = {
$0.frame = self.bounds//.insetBy(dx: -200, dy: -200)
$0.zPosition = -CGFloat.greatestFiniteMagnitude + 1
$0.drawsAsynchronously = true
return $0
}(CALayer())
// fileprivate let pingThread = PingThread()
@IBInspectable var speed: CGFloat = CGFloat(JSMatrixConstants.speed){
didSet{
datasource.speed = TimeInterval(speed)
}
}
@IBInspectable var newTrackComingLap: CGFloat = CGFloat(JSMatrixConstants.newTrackComingLap){
didSet{
datasource.newTrackComingLap = TimeInterval(newTrackComingLap)
}
}
@IBInspectable var trackSpacing: Int = JSMatrixConstants.tracksSpacing{
didSet{
datasource.trackSpacing = trackSpacing
}
}
// lazy var displayLink: CADisplayLink = CADisplayLink(target: self, selector: #selector(self.update))
// lazy var motionManager = CMMotionManager()
// var originRad: CGFloat?
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.black
self.layer.addSublayer(containerLayer)
// pingThread.start()
// displayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
//
// if motionManager.isDeviceMotionAvailable{
// motionManager.startDeviceMotionUpdates(using: CMAttitudeReferenceFrame.xArbitraryZVertical)
// }
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = UIColor.black
self.layer.addSublayer(containerLayer)
// pingThread.start()
// displayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
// if motionManager.isDeviceMotionAvailable{
// motionManager.startDeviceMotionUpdates(using: CMAttitudeReferenceFrame.xArbitraryZVertical)
// }
}
// @objc func update(){
// if let quat = motionManager.deviceMotion?.attitude.quaternion{
// let realRoll = atan2(2 * (quat.x * quat.y + quat.z * quat.w), 1 - 2 * (pow(quat.y, 2.0) + pow(quat.z, 2.0)))
// // let realPitch = atan2(2 * (quat.x * quat.w + quat.y * quat.z), 1 - 2 * (pow(quat.z, 2.0) + pow(quat.w, 2.0)))
// // if originRad == nil{
// // originRad = CGFloat(realPitch)
// // }
//
// var rollTransform = CATransform3DIdentity
// rollTransform.m43 = (-1) / 500
// rollTransform = CATransform3DRotate(rollTransform, CGFloat(realRoll), 0, 1, 0)
// // var pitchTransform = CATransform3DIdentity
// // pitchTransform.m43 = (-1) / 500
// // pitchTransform = CATransform3DRotate(pitchTransform, originRad! - CGFloat(realPitch), 1, 0, 0)
// // let concatTransform = CATransform3DConcat(rollTransform, pitchTransform)
// self.containerLayer.transform = rollTransform
// }
// }
override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
let track = generator.getTrack(trackNumber: JSMatrixDataSource.trackNum / 2)
self.didGeneratedNewTrack(newTrack: track)
DispatchQueue.main.asyncAfter(deadline: .now() + JSMatrixConstants.firstDropShowTime) {
self.generator.begin()
}
}
fileprivate func availiableTracks() -> [Int] {
return datasource.getAvailiableTracks()
}
fileprivate func didGeneratedNewTrack(newTrack: JSMatrixTrack) {
newTrack.datasource = datasource
datasource.addTrack(track: newTrack)
let layer = JSMatrixTrackLayer(track: newTrack)
layer.frame = CGRect(origin: CGPoint(x: newTrack.positionX, y: 0),
size: CGSize(width: JSMatrixDataSource.characterSize.width, height: UIScreen.main.bounds.height))
containerLayer.addSublayer(layer)
layer.drawAsync()
newTrack.layer = layer
}
}