Method: Mittsu::Geometry#merge_vertices

Defined in:
lib/mittsu/core/geometry.rb

#merge_verticesObject



405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
# File 'lib/mittsu/core/geometry.rb', line 405

def merge_vertices
  vertices_map = {} # Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  unique = []; changes = []
  precision_points = 4 # number of decimal points, eg. 4 for epsilon of 0.0001
  precision = 10 ** precision_points
  @vertices.each_with_index do |v, i|
    key = "#{(v.x * precision).round}_#{(v.y * precision).round}_#{(v.z * precision).round}"
    if vertices_map[key].nil?
      vertices_map[key] = i
      unique << v
      changes[i] = unique.length - 1
    else
      #console.log('Duplicate vertex found. ', i, ' could be using ', vertices_map[key])
      changes[i] = changes[vertices_map[key]]
    end
  end
  # if faces are completely degenerate after merging vertices, we
  # have to remove them from the geometry.
  face_indices_to_remove = []
  @faces.each_with_index do |face, i|
    face.a = changes[face.a]
    face.b = changes[face.b]
    face.c = changes[face.c]
    indices = [face.a, face.b, face.c]
    dup_index = -1
    # if any duplicate vertices are found in a Face3
    # we have to remove the face as nothing can be saved
    3.times do |n|
      if indices[n] == indices[(n + 1) % 3]
        dup_index = n
        face_indices_to_remove << i
        break
      end
    end
  end
  face_indices_to_remove.reverse_each do |idx|
    idx = face_indices_to_remove[i]
    @faces.delete_at idx
    @face_vertex_uvs.each do |uv|
      uv.delete_at idx
    end
  end
  # Use unique set of vertices
  diff = @vertices.length - unique.length
  @vertices = unique
  diff
end