Skip to content

Instantly share code, notes, and snippets.

@moxuse
Last active February 13, 2022 21:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moxuse/7ec465abec5fec9de010 to your computer and use it in GitHub Desktop.
Save moxuse/7ec465abec5fec9de010 to your computer and use it in GitHub Desktop.
SCNShadable Shader Modifiers Test
import SceneKit
import QuartzCore
class GameViewController: NSViewController {
@IBOutlet weak var gameView: GameView!
override func awakeFromNib(){
let numSphere = 10
let camDistance:CGFloat = 5.0
// create a new scene
let scene = SCNScene()
// create and add a camera t the scene
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
scene.rootNode.addChildNode(cameraNode)
cameraNode.position = SCNVector3(x:0, y:0, z:camDistance)
// create and add Spheres to the scene
for x in 0..<numSphere {
let node = SCNNode()
let rdx = randomCGFloat() * camDistance - camDistance / 2
let rdy = randomCGFloat() * camDistance - camDistance / 2
let rdz = randomCGFloat() * camDistance - camDistance / 2
node.position = SCNVector3Make(rdx, rdy, rdz)
node.geometry = SCNSphere(radius: 1.0)
scene.rootNode.addChildNode(node)
// create and configure a material
let material = SCNMaterial()
material.specular.contents = NSColor.blueColor()
material.locksAmbientWithDiffuse = true
// set shaderModifiers properties
material.shaderModifiers = [
SCNShaderModifierEntryPointSurface:
"uniform float Scale = 12.0;\n" +
"uniform float Width = 0.5;\n" +
"uniform float Blend = 0.0;\n" +
"vec2 position = fract(_surface.diffuseTexcoord * Scale);" +
"float f1 = clamp(position.y / Blend, 0.0, 1.0);" +
"float f2 = clamp((position.y - Width) / Blend, 0.0, 1.0);" +
"f1 = f1 * (1.0 - f2);" +
"f1 = f1 * f1 * 2.0 * (3. * 2. * f1);" +
"_surface.diffuse = mix(vec4(1.0), vec4(0.0), f1);"
]
// set the material to the 3D object geometry
node.geometry?.firstMaterial = material
// animate the 3D object
let animation:CABasicAnimation = CABasicAnimation(keyPath:"rotation")
animation.toValue = NSValue(SCNVector4:SCNVector4(x:CGFloat(1.0), y:CGFloat(1.0), z:CGFloat(0.0), w:CGFloat(M_PI * 2)))
animation.duration = 5
animation.repeatCount = MAXFLOAT // repeat forever
node.addAnimation(animation, forKey:nil)
}
// set the scene to the view
self.gameView!.scene = scene
// allows the user to manipulate the camera
self.gameView!.allowsCameraControl = true
// show statistics such as fps and timing information
self.gameView!.showsStatistics = true
// configure the view
self.gameView!.backgroundColor = NSColor.blackColor()
}
func randomCGFloat() -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt32.max)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment