 		
 		ownerHash = hash
 		name = debugName
+		drawMode = mode
 		
 		guard !indices.isEmpty else {
 			fatalError("Do not create render primitive for empty meshes")
 		}
 		
-		let vertexBufLen = MemoryLayout<VertexType>.stride * vertices.count
-		let indexBufLen = MemoryLayout<UInt16>.stride * indices.count
+		// Concatenate all vertex rings into one buffer
+		var allVertices: [VertexType] = []
+		var allIndices: [UInt32] = []
+		var polyRanges: [Int] = []
+		for (p, i) in zip(polygons, indices) {
+			guard !p.isEmpty else { continue }
+			allVertices.append(contentsOf: p)
+			allIndices.append(contentsOf: i.map { UInt32($0) })
+			polyRanges.append(i.count)
+		}
+		elementCounts = polyRanges
 		
-		guard let newVertBuffer = device.makeBuffer(bytes: vertices, length: vertexBufLen, options: .storageModeShared),
-					let	newIndexBuffer = device.makeBuffer(bytes: indices, length: indexBufLen, options: .storageModeShared) else {
+		let vertexBufLen = MemoryLayout<VertexType>.stride * allVertices.count
+		let indexBufLen = MemoryLayout<UInt32>.stride * allIndices.count
+		
+		guard let newVertBuffer = device.makeBuffer(bytes: allVertices, length: vertexBufLen, options: .storageModeShared),
+					let	newIndexBuffer = device.makeBuffer(bytes: allIndices, length: indexBufLen, options: .storageModeShared) else {
 				fatalError("Could not create buffers for \(debugName)")
 		}
 		

class IndexedRenderPrimitive<VertexType> {
	let ownerHash: Int
	
	let vertexBuffer: MTLBuffer
	let elementCount: Int
	let indexBuffer: MTLBuffer
	
	let color: Color
	let name: String
	
	// Indexed draw mode
	init(vertices: [VertexType],
			 indices: [UInt16],
			 device: MTLDevice,
			 color c: Color,
			 ownerHash hash: Int, debugName: String) {

		
		self.indexBuffer = newIndexBuffer
		self.indexBuffer.label = "\(debugName) index buffer"
	}
}


func render<T>(primitive: IndexedRenderPrimitive<T>, into encoder: MTLRenderCommandEncoder) {
	encoder.setVertexBuffer(primitive.vertexBuffer, offset: 0, index: 0)
	
	var cursor = 0
	for range in primitive.elementCounts {
		encoder.drawIndexedPrimitives(type: primitive.drawMode,
																	indexCount: range,
																	indexType: .uint32,
																	indexBuffer: primitive.indexBuffer,
																	indexBufferOffset: cursor)
		cursor += range * MemoryLayout<UInt32>.stride
	}
}
