Removing SceneKit emission material? - scenekit

In an effort to highlight hit items in my scene, I'm doing something like this:
func
highlight(note inNote: Int, highlight inHighlight: Bool)
{
let scene = self.scene as! MainEditorScene
let node = scene.noteNodes[inNote]
let geom = node.geometry!
if inHighlight
{
geom.firstMaterial?.emission.contents = NSColor(calibratedRed: 1.0, green: 1.0, blue: 1.0, alpha: 0.3)
}
else
{
geom.firstMaterial?.emission.contents = nil
}
}
Unfortunately, the objects turn white but never back to their original color. Can I not remove the emission contents like this? What should I do?

Make it transparent:
geom.firstMaterial?.emission.contents = UIColor.clear
Instead of:
geom.firstMaterial?.emission.contents = nil

in SceneKit a black color, i.e.(0.0, 0.0, 0.0), is often the default value for "nothing" (that is a contribution of 0 in the lighting equation)
geom.firstMaterial?.emission.contents = NSColor.black

Related

How to change colors of a cell of collection view on scrolling swift5

i want to change color of the cell of my collectionview on scrolling in swift.
here is an image of my viewcontroller. i want to change background color of the specific cell to white on scroll. and i used animatedcollectionViewLayout for animation.
This may help you, call it in scrollViewDidScroll. Don't use indexPathsForVisibleItems、visibleCells, they have a few issues.
func updateCellsApperance() {
let visibleRect = CGRect(origin: modesCollectionView.contentOffset, size: modesCollectionView.frame.size)
let center = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
var indexPaths: Set<IndexPath> = []
let step = 10.0
var x = center.x
while x > visibleRect.minX {
if let indexPath = modesCollectionView.indexPathForItem(at: CGPoint(x: x, y: center.y)) {
indexPaths.insert(indexPath)
}
x -= step
}
x = center.x + step
while x < visibleRect.maxX {
if let indexPath = modesCollectionView.indexPathForItem(at: CGPoint(x: x, y: center.y)) {
indexPaths.insert(indexPath)
}
x += step
}
indexPaths.forEach { indexPath in
if let cell = modesCollectionView.cellForItem(at: indexPath),
let attrs = modesCollectionView.layoutAttributesForItem(at: indexPath) {
let distanceX = visibleRect.midX - attrs.center.x
// >= 0.0
let ratio = abs(distanceX) * (1.0 / attrs.frame.width)
cell.xxx.color = UIColor(red: 0.0, green: max(0.0, 1.0 - ratio), blue: 0, alpha: 1.0)
}
}
}

Graphic Points are not working outside of viewDidLoad

I've created a Graphic Class to show for user a graphic points choose accordingly with user information.
If I use the graphicView object and add points at viewDidLoad, the graphic is presented correctly, if not there, the graphic presents no data.
See below the code for the Graphics and the code when I am requesting to mark the points.
class GraphView: UIView {
private struct Constants {
static let cornerRadiusSize = CGSize(width: 8.0, height: 8.0)
static let margin: CGFloat = 40.0
static let topBorder: CGFloat = 30
static let bottomBorder: CGFloat = 40
static let colorAlpha: CGFloat = 0.3
static let circleDiameter: CGFloat = 5.0
}
//1 - the properties for the gradient
var startColor: UIColor = UIColor.rgb(red: 14, green: 40, blue: 80)
var endColor: UIColor = UIColor.rgb(red: 14, green: 40, blue: 80)
//Weekly sample data
var graphPoints: [Int] = [0]
override func draw(_ rect: CGRect) {
let width = rect.width
let height = rect.height
let path = UIBezierPath(roundedRect: rect,
byRoundingCorners: UIRectCorner.allCorners,
cornerRadii: Constants.cornerRadiusSize)
path.addClip()
//2 - get the current context
let context = UIGraphicsGetCurrentContext()!
let colors = [startColor.cgColor, endColor.cgColor]
//3 - set up the color space
let colorSpace = CGColorSpaceCreateDeviceRGB()
//4 - set up the color stops
let colorLocations: [CGFloat] = [0.0, 1.0]
//5 - create the gradient
let gradient = CGGradient(colorsSpace: colorSpace,
colors: colors as CFArray,
locations: colorLocations)!
//6 - draw the gradient
var startPoint = CGPoint.zero
var endPoint = CGPoint(x: 0, y: self.bounds.height)
context.drawLinearGradient(gradient,
start: startPoint,
end: endPoint,
options: CGGradientDrawingOptions(rawValue: 0))
//calculate the x point
let margin = Constants.margin
let columnXPoint = { (column:Int) -> CGFloat in
//Calculate gap between points
let spacer = (width - margin * 2 - 4) / CGFloat((self.graphPoints.count - 1))
var x: CGFloat = CGFloat(column) * spacer
x += margin + 2
return x
}
// calculate the y point
let topBorder: CGFloat = Constants.topBorder
let bottomBorder: CGFloat = Constants.bottomBorder
let graphHeight = height - topBorder - bottomBorder
let maxValue = graphPoints.max()!
let columnYPoint = { (graphPoint:Int) -> CGFloat in
var y:CGFloat = CGFloat(graphPoint) / CGFloat(maxValue) * graphHeight
y = graphHeight + topBorder - y // Flip the graph
return y
}
// draw the line graph
UIColor.white.setFill()
UIColor.white.setStroke()
//set up the points line
let graphPath = UIBezierPath()
//go to start of line
graphPath.move(to: CGPoint(x:columnXPoint(0), y:columnYPoint(graphPoints[0])))
//add points for each item in the graphPoints array
//at the correct (x, y) for the point
for i in 1..<graphPoints.count {
let nextPoint = CGPoint(x:columnXPoint(i), y:columnYPoint(graphPoints[i]))
graphPath.addLine(to: nextPoint)
}
//Create the clipping path for the graph gradient
//1 - save the state of the context (commented out for now)
context.saveGState()
//2 - make a copy of the path
let clippingPath = graphPath.copy() as! UIBezierPath
//3 - add lines to the copied path to complete the clip area
clippingPath.addLine(to: CGPoint(x: columnXPoint(graphPoints.count - 1), y:height))
clippingPath.addLine(to: CGPoint(x:columnXPoint(0), y:height))
clippingPath.close()
//4 - add the clipping path to the context
clippingPath.addClip()
let highestYPoint = columnYPoint(maxValue)
startPoint = CGPoint(x:margin, y: highestYPoint)
endPoint = CGPoint(x:margin, y:self.bounds.height)
context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: 0))
context.restoreGState()
//draw the line on top of the clipped gradient
graphPath.lineWidth = 3.0
graphPath.stroke()
//Draw the circles on top of graph stroke
for i in 0..<graphPoints.count {
var point = CGPoint(x:columnXPoint(i), y:columnYPoint(graphPoints[i]))
point.x -= Constants.circleDiameter / 2
point.y -= Constants.circleDiameter / 2
let circle = UIBezierPath(ovalIn: CGRect(origin: point, size: CGSize(width: Constants.circleDiameter, height: Constants.circleDiameter)))
circle.fill()
}
//Draw horizontal graph lines on the top of everything
let linePath = UIBezierPath()
//top line
linePath.move(to: CGPoint(x:margin, y: topBorder))
linePath.addLine(to: CGPoint(x: width - margin, y:topBorder))
//center line
linePath.move(to: CGPoint(x:margin, y: graphHeight/2 + topBorder))
linePath.addLine(to: CGPoint(x:width - margin, y:graphHeight/2 + topBorder))
//bottom line
linePath.move(to: CGPoint(x:margin, y:height - bottomBorder))
linePath.addLine(to: CGPoint(x:width - margin, y:height - bottomBorder))
let color = UIColor(white: 1.0, alpha: Constants.colorAlpha)
color.setStroke()
linePath.lineWidth = 1.0
linePath.stroke()
}
}
I am trying to mark the points accordingly with the user input - see below:
func budgetAvailableCalculationFunction() {
let bankValue = (userSalary as NSString).integerValue
let bankPorcentage: Int = 100
let expenses = (userExpenses as NSString).integerValue
let calculation1: Int = expenses * bankPorcentage
let calculation2: Int = calculation1 / bankValue
let cashPorcentageAvailable = calculation2
let value: [Int] = [expenses]
self.setupGraphy(points: value)
progressView.progress = 0.0
progress.completedUnitCount = Int64(cashPorcentageAvailable)
progressView.setProgress(Float(self.progress.fractionCompleted), animated: true)
progressView.progressTintColor = UIColor.rgb(red: 239, green: 75, blue: 92)
progressView.backgroundColor = UIColor.rgb(red: 239, green: 75, blue: 92)
progressView.trackTintColor = .white
progressView.clipsToBounds = false
progressView.translatesAutoresizingMaskIntoConstraints = false
progressView.layer.cornerRadius = 0
porcentageLabelForMonth.text = "\(Int(self.progress.fractionCompleted * 100)) %"
}
The setupGraphy is just a function that returns an array of indexes that the user adds it.
Please note that using the same function at the viewDidLoad works:
self.setupGraphy(points: [100, 400, 200, 250])
enter image description here
Anyone?
Code for viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.rgb(red: 245, green: 246, blue: 250)
tableView.delegate = self
tableView.dataSource = self
tableView.register(LastTransactionsCell.self, forCellReuseIdentifier: "LastTransactionsCell")
tableView.backgroundColor = .clear
let now = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy - LLLL"
let nameOfMonth = dateFormatter.string(from: now)
currentMonthLabel.text = nameOfMonth
setupUIXViews()
fetchUserInfo()
//static data for now
*self.setupGraphy(points: [100, 400, 200, 250])*
DispatchQueue.main.asyncAfter(deadline: .now() + 2){
self.budgetAvailableCalculationFunction()
}
}
The way I managed to fix (seems like a temporary fix) is by creating a new Int variable at the top of the project and passing the fetch data from the DB to these variables. That way I can use them at viewDidLoad instead of inside the fetch function.

Is it possible to draw a clear SCNSphere with a bright red SCNSpotlight?

The last few days I am struggling a bit with SceneKit. I am trying to plot a clear/transparent SCNSphere, with a red spotlight. It appears that my red spotlight is becoming transparant as well if I set my SCNSphere to transpararent / clear colour. Is it possible to unlink the SCNLight Node to the SCNSphereNode, so that the bright red colour of the spot remains if the SCNSphere is transparant? Images of both spheres are below the code.
My code:
func setupView() {
scene = SCNScene()
caliView.scene = scene
caliView.allowsCameraControl = true
caliView.backgroundColor = UIColor.clearColor()
let clearMaterial = SCNMaterial()
clearMaterial.diffuse.contents = UIColor(white: 0.9, alpha: 0.5)
clearMaterial.locksAmbientWithDiffuse = true
let shape = SCNSphere(radius: 5)
shape.materials = [clearMaterial]
let shapeNode = SCNNode(geometry: shape)
let spotLight = SCNLight()
spotLight.type = SCNLightTypeSpot
spotLight.color = UIColor.init(colorLiteralRed: 180, green: 0, blue: 0, alpha: 0.0)
let lightNode = SCNNode()
lightNode.light = spotLight
lightNode.position = SCNVector3(x: 0.0, y:0.0, z:15.0)
lightNode.orientation = SCNQuaternion(x: 0.0, y:0, z:30, w:0.0)
let ambientLight = SCNLight()
ambientLight.type = SCNLightTypeAmbient
ambientLight.color = UIColor(white: 0.8, alpha: 0.2)
let ambientNode = SCNNode()
ambientNode.light = ambientLight
shapeNode.position = SCNVector3(x: 0.0, y: 0.0, z: 0.0)
scene.rootNode.addChildNode(ambientNode)
scene.rootNode.addChildNode(shapeNode)
shapeNode.addChildNode(lightNode)
}
Darker sphere with bright red spotlight:
More transparent sphere with soft red spotlight:
In this line...
shapeNode.addChildNode(lightNode)
...you added the light node to the sphere node.
If you want to un-link them while still having them move together, you can create an empty SCNNode and add the other two SCNNode instances to it as children (the one for the light and the one for the sphere):
func setupView() {
scene = SCNScene()
caliView.scene = scene
caliView.allowsCameraControl = true
caliView.backgroundColor = UIColor.clearColor()
let clearMaterial = SCNMaterial()
clearMaterial.diffuse.contents = UIColor(white: 0.9, alpha: 0.5)
clearMaterial.locksAmbientWithDiffuse = true
let emptyNode = SCNNode()
let shape = SCNSphere(radius: 5)
shape.materials = [clearMaterial]
let shapeNode = SCNNode(geometry: shape)
let spotLight = SCNLight()
spotLight.type = SCNLightTypeSpot
spotLight.color = UIColor.init(colorLiteralRed: 180, green: 0, blue: 0, alpha: 0.0)
let lightNode = SCNNode()
lightNode.light = spotLight
lightNode.position = SCNVector3(x: 0.0, y:0.0, z:15.0)
lightNode.orientation = SCNQuaternion(x: 0.0, y:0, z:30, w:0.0)
let ambientLight = SCNLight()
ambientLight.type = SCNLightTypeAmbient
ambientLight.color = UIColor(white: 0.8, alpha: 0.2)
let ambientNode = SCNNode()
ambientNode.light = ambientLight
shapeNode.position = SCNVector3(x: 0.0, y: 0.0, z: 0.0)
emptyNode.addChild(shapeNode)
emptyNode.addChild(lightNode)
scene.rootNode.addChildNode(emptyNode)
scene.rootNode.addChildNode(ambientNode)
}

saving array of images with UIImagePNGRepresentation memory warning swift

I'm capturing randomly-sized/shaped sections of a UIView and saving to disk using UIImagePNGRepresentation. The files save as expected, but when I run on a device, I get the dreaded "Received memory warning", even though all I'm doing is saving files in a loop and not displaying them:
UIGraphicsBeginImageContextWithOptions(bbox.size, false, 0)
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 0.25).CGColor)
CGContextAddRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, bbox.width, bbox.height))
CGContextFillPath(UIGraphicsGetCurrentContext())
let strokeImage = UIGraphicsGetImageFromCurrentImageContext()
let strokeFile = "stroke_\(strokeBezierArrayMemory.count).png"
let dataPng = UIImagePNGRepresentation(strokeImage)
let fileURL = folderURL!.URLByAppendingPathComponent(strokeFile) //println("\(fileURL)")
if (dataPng.writeToURL(fileURL, options: .AtomicWrite, error: &error) ) {
//println ("WROTE \(fileURL)")
} else {
print (error)
}
I've seen similar posts, but no answers that solve my problem. This post suggests using AVFoundation, but I'm hoping I can stick to UIImagePNGRepresentation.
I also tried wrapping the NSData part of the code in an autoreleasepool closure to no avail:
autoreleasepool({ () -> () in
let strokeFile = "stroke_\(strokeBezierArrayMemory.count).png"
let data = UIImagePNGRepresentation(strokeImage)
let fileURL = folderURL!.URLByAppendingPathComponent(strokeFile) //println("\(fileURL)")
if (data.writeToURL(fileURL, options: .AtomicWrite, error: &error) ) {
//println ("WROTE \(fileURL)")
} else {
print (error)
}
})
Is there a way to force NSData to release each dataPng once written to disk?

Get size of dae node

Suppose I have a collada file which has a box in it and I import the dae file into the scene. Now after importing in the scene I know the dae object is a box. How can I get the dimensions of the box in scenekit after adding it to the scene
If I import the node as a SCNBox i get errors saying that SNCBox is not a subtype of SCNNode.
floorNode = scene.rootNode.childNodeWithName("floor", recursively: false) as SCNBox
floorNode?.physicsBody = SCNPhysicsBody.staticBody()
floorNode?.physicsBody?.categoryBitMask = 2
let floorGeo: SCNBox = floorNode.geometry! as SCNBox
How do I get the dimensions if SCNNode is the only way to import nodes?
SCNBox is just helper subclass of SCNGeometry for box geometry creation. When you import Collada into a scene, you get scene graph of SCNNodes with SCNGeometries, not SCNBox'es or SCNCones etc doesn't matter how they look. If you want to get dimensions of any node you should use SCNBoundingVolume protocol, which is implemented by both SCNNode and SCNGeometry classes:
func getBoundingBoxMin(_ min: UnsafeMutablePointer,
max max: UnsafeMutablePointer) -> Bool
With this method you will get bounding box corners.
For box-shaped geometry, dimensions will match bounding box.
Example:
var v1 = SCNVector3(x:0, y:0, z:0)
var v2 = SCNVector3(x:0, y:0, z:0)
node.getBoundingBoxMin(&v1, max:&v2)
Where node is node you want to get bounding box of.
Results will be in v1 and v2.
Swift 3
Using Swift 3 you can simply use node.boundingBox.min and node.boundingBox.max respectively.
Example Swift code on how to use boundingBox:
var min = shipNode.boundingBox.min
var max = shipNode.boundingBox.max
let w = CGFloat(max.x - min.x)
let h = CGFloat(max.y - min.y)
let l = CGFloat(max.z - min.z)
let boxShape = SCNBox (width: w , height: h , length: l, chamferRadius: 0.0)
let shape = SCNPhysicsShape(geometry: boxShape, options: nil)
shipNode.physicsBody!.physicsShape = SCNPhysicsShape(geometry: boxShape, options: nil)
shipNode.physicsBody = SCNPhysicsBody.dynamic()
Swift 5.4.
import ARKit
extension SCNNode {
var height: CGFloat { CGFloat(self.boundingBox.max.y - self.boundingBox.min.y) }
var width: CGFloat { CGFloat(self.boundingBox.max.x - self.boundingBox.min.x) }
var length: CGFloat { CGFloat(self.boundingBox.max.z - self.boundingBox.min.z) }
var halfCGHeight: CGFloat { height / 2.0 }
var halfHeight: Float { Float(height / 2.0) }
var halfScaledHeight: Float { halfHeight * self.scale.y }
}
// Usage:
let node = SCNNode()
node.height
node.width
node.lenght

Resources