#!/usr/bin/env python
from vtkmodules.vtkCommonCore import (
    reference,
    vtkIdList
)
from vtkmodules.vtkCommonDataModel import vtkQuadric
from vtkmodules.vtkFiltersCore import (
    vtkExecutionTimer,
    vtkExtractEdges,
    vtkPointDataToCellData,
)
from vtkmodules.vtkImagingHybrid import vtkSampleFunction
from vtkmodules.vtkRenderingCore import (
    vtkActor,
    vtkPolyDataMapper,
    vtkRenderWindow,
    vtkRenderWindowInteractor,
    vtkRenderer,
)
import vtkmodules.vtkInteractionStyle
import vtkmodules.vtkRenderingFreeType
import vtkmodules.vtkRenderingOpenGL2

# Test edge extraction with cell data, and with original
# point numbering preserved.
#
# Due to issues rendering lots of lines, this test has been
# modified to perform procedural comparison of results.
res = 10
error = 0

# Test edge extraction for arbitrary datasets
#
# Quadric definition
quadric = vtkQuadric()
quadric.SetCoefficients([.5,1,.2,0,.1,0,0,.2,0,0])
sample = vtkSampleFunction()
sample.SetSampleDimensions(res,res,res)
sample.SetImplicitFunction(quadric)
sample.ComputeNormalsOff()
sample.Update()

# Create some cell data
pd2cd = vtkPointDataToCellData()
pd2cd.SetInputConnection(sample.GetOutputPort())
pd2cd.PassPointDataOn()
pd2cd.Update()

# Now extract the edges
extract = vtkExtractEdges()
extract.SetInputConnection(pd2cd.GetOutputPort())
extract.UseAllPointsOn()

timer = vtkExecutionTimer()
timer.SetFilter(extract)
extract.Update()
ET = timer.GetElapsedWallClockTime()
print ("vtkExtractEdges:", ET)

# Now compare attribute values of extracted points and edges with
# the input dataset.
if extract.GetOutput().GetNumberOfPoints() != 1000:
    print("Wrong number of points. Expected 1000 but got {0}.".format(extract.GetOutput().GetNumberOfPoints()))
    error = 1

numEdges = extract.GetOutput().GetNumberOfCells()
if numEdges != 2700:
    print("Wrong number of edges. Expected 2700 but got {0}.".format(numEdges))
    error = 1

qScalars = sample.GetOutput().GetPointData().GetScalars()
eScalars = extract.GetOutput().GetPointData().GetScalars()

# Compare selected attribute values with input dataset attributes.
edgeNum = 0
ePts = vtkIdList()
edges = extract.GetOutput().GetLines()
eIter = edges.NewIterator()
while not eIter.IsDoneWithTraversal():
    eIter.GetCurrentCell(ePts)
    v0 = ePts.GetId(0)
    v1 = ePts.GetId(1)
    s0 = eScalars.GetTuple1(v0)
    s1 = eScalars.GetTuple1(v1)
    q0 = qScalars.GetTuple1(v0)
    q1 = qScalars.GetTuple1(v1)
    if s0 != q0 or s1 != q1:
        error = 1
        print("Error in edge number: ", edgeNum)
    edgeNum += 1
    eIter.GoToNextCell()

# Return test results. If the assert is not true, then different results were
# generated by vtkStaticPointLocator and vtkPointLocator.
assert error == 0

# --- end of script --
