Group Group Group Group Group Group Group Group Group

How to access to a float4 position?

Hi! I’m trying to build a cylinder using triangles, but first, I want to make a circle with points to do the base of that cylinder using a for loop from 0 to 360, by 360/number_of_divisions, using the sin and cos of the angle, but i need to change the different coordinates of every point (float4). How can I access to them?

Thanks in advance

I don’t know exactly what you are trying to do or where the coordinates are stored.

But you can access the contents of an MTLBuffer, if you know the format with something like this:

var pointer = particleBuffer.contents().bindMemory(
  to: Particle.self,
  capacity: particleCount)
for _ in 0..<particleCount {
  let width = random(Int(size.width) / 2) + Float(size.width) / Float(4)
  let height = random(Int(size.height) / 2) + Float(size.height) / Float(4)
  let position = float2(width, height)
  pointer.pointee.position = position
  let velocity = float2(random(10), random(10))
  pointer.pointee.velocity = velocity
  pointer.pointee.threshold = [0, 0]
  pointer = pointer.advanced(by: 1)
}

This is accessing particles in an MTLBuffer called particleBuffer, and is code from the Particles chapter.

Once you have access to the coordinate, you can work out its position in a circle with something like this:

  static func position(_ index: Int) -> CGPoint {
    var position = CGPoint.zero
    let current = CGFloat(index) / CGFloat(Self.pointCount)
    position.x = Self.radius * cos(2 * .pi * current)
    position.y = Self.radius * sin(2 * .pi * current)
    return position
  }

This code is a SwiftUI example of distributing 2D points in a circle:

Circle.zip (29.7 KB)

This code is an example of a Metal shader that takes 50 points and puts it into a circle (not using an MTLBuffer):

Vertex.zip (75.9 KB)

1 Like

Also, if you just want to make a cylinder, you can use Metal’s built in primitive described here:

You could then access the vertices in the generated MTLBuffer if you need to do anything else with them.

1 Like