Commit 44743723 authored by charras's avatar charras

removed GPC library due to its unacceptable license. Using the great and...

removed GPC library due to its unacceptable license. Using the great and powerfull kbool library insteed
parent e3b63f83
......@@ -101,6 +101,7 @@ add_subdirectory(gerbview)
add_subdirectory(kicad)
add_subdirectory(pcbnew)
add_subdirectory(polygon)
add_subdirectory(polygon/kbool/src)
# Resources.
add_subdirectory(demos)
add_subdirectory(internat)
......
# Generate a static library target named "libbitmaps.a"
# Copy the *.xmp files to *.cpp, on change only.
# Compile those *.cpp files and put them into the library, then done.
OBJECTS = \
3d.o\
Add_Arc.o\
......@@ -287,5 +283,88 @@ OBJECTS = \
Zoom_Page.o\
Zoom_Selected.o\
Zoom_Select.o\
zoom.o
zoom.o\
axis3d_back.o\
axis3d_bottom.o\
axis3d_front.o\
axis3d_left.o\
axis3d_right.o\
axis3d_top.o\
axis3d.o\
import3d.o\
rotate-x.o\
rotate+x.o\
rotate-y.o\
rotate+y.o\
rotate-z.o\
rotate+z.o\
zoomoins3d.o\
zoompage3d.o\
zoomplus3d.o\
zoomrefr3d.o\
Lang_Catalan.o\
Lang_chinese.o\
Lang_Default.o\
Lang_De.o\
Lang_En.o\
Lang_Es.o\
Lang_Fr.o\
Lang_Hu.o\
Lang_It.o\
Lang_Ko.o\
Lang_Nl.o\
Lang_Pl.o\
Lang_Pt.o\
Lang_Ru.o\
Lang_Sl.o\
Language.o\
delete_association.o\
module_filtered_list.o\
module_full_list.o\
Break_Bus.o\
cvpcb.o\
Delete_Bus.o\
Delete_Connection.o\
Delete_GLabel.o\
Delete_Pinsheet.o\
Delete_Pin.o\
Delete_Sheet.o\
Edit_Comp_Footprint.o\
Edit_Component.o\
Edit_Comp_Ref.o\
Edit_Comp_Value.o\
Edit_Part.o\
Edit_Sheet.o\
Enter_Sheet.o\
GLabel2Label.o\
GLabel2Text.o\
GL_Change.o\
Hidden_Pin.o\
Hierarchy_cursor.o\
Hierarchy_Nav.o\
Label2GLabel.o\
Label2Text.o\
Leave_Sheet.o\
libedit_icon.o\
libedit.o\
Lib_next.o\
Lib_previous.o\
library_browse.o\
Lines90.o\
Move_GLabel.o\
Move_Pinsheet.o\
Move_Sheet.o\
new_component.o\
Normal.o\
Options_Pinsheet.o\
Options_Pin.o\
part_properties.o\
pin2pin.o\
Pin_Name_to.o\
Pin_Number_to.o\
Pin_Size_to.o\
Pin_to.o\
Resize_Sheet.o\
Rotate_GLabel.o\
Rotate_Pin.o\
viewlibs_icon.o
......@@ -5,6 +5,14 @@ Started 2007-June-11
Please add newer entries at the top, list the date and your name with
email address.
2008-May-30 UPDATE Jean-Pierre Charras <jean-pierre.charras@inpg.fr>
================================================================================
+pcbnew
removed GPC library due to its unacceptable (and stupid) license
using the powerfull kbool library insteed (see polygon/kbool)
+all:
minor changes
2008-May-22 UPDATE Martin Kajdas <kajdas@cox.com>
================================================================================
......
......@@ -244,7 +244,7 @@ void WinEDA_BasicFrame::GetKicadHelp( wxCommandEvent& event )
void WinEDA_BasicFrame::GetKicadAbout( wxCommandEvent& event )
/**********************************************************/
{
Print_Kicad_Infos( this, m_AboutTitle );
Print_Kicad_Infos( this, m_AboutTitle, wxEmptyString );
}
......
/************************************************************************/
/* MODULE edamenu.cpp */
/************************************************************************/
/****************************/
/* INCLUDES SYSTEMES */
/****************************/
#include "fctsys.h"
#include "wxstruct.h"
#include "gr_basic.h"
#include "macros.h"
#include "common.h"
#include "worksheet.h"
/* Pour imprimer / lire en unites utilisateur ( INCHES / MM ) */
/* Retourne la valeur en inch ou mm de la valeur val en units internes
*/
double To_User_Unit(bool is_metric, int val,int internal_unit_value)
{
double value;
if (is_metric)
value = (double) (val) * 25.4 / internal_unit_value;
else value = (double) (val) / internal_unit_value;
return value;
}
/* Retourne la valeur en units internes de la valeur val exprime en inch ou mm
*/
int From_User_Unit(bool is_metric, double val,int internal_unit_value)
{
double value;
if (is_metric) value = val * internal_unit_value / 25.4 ;
else value = val * internal_unit_value;
return (int) round(value);
}
/**********************/
wxString GenDate()
/**********************/
/* Retourne la chaine de caractere donnant la date */
{
static char * mois[12] =
{
"jan", "feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"
};
time_t buftime;
struct tm * Date;
wxString string_date;
char Line[1024];
time(&buftime);
Date = gmtime(&buftime);
sprintf(Line,"%d %s %d", Date->tm_mday,
mois[Date->tm_mon],
Date->tm_year + 1900);
string_date = Line;
return(string_date);
}
/***********************************/
void * MyMalloc (size_t nb_octets)
/***********************************/
/* Routine d'allocation memoire */
{
void * pt_mem;
char txt[60];
if (nb_octets == 0)
{
DisplayError(NULL, "Allocate 0 bytes !!");
return(NULL);
}
pt_mem = malloc(nb_octets);
if (pt_mem == NULL)
{
sprintf(txt,"Out of memory: allocation %d bytes", nb_octets);
DisplayError(NULL, txt);
}
return(pt_mem);
}
/************************************/
void * MyZMalloc (size_t nb_octets)
/************************************/
/* Routine d'allocation memoire, avec remise a zero de la zone allouee */
{
void * pt_mem = MyMalloc (nb_octets);
if ( pt_mem) memset(pt_mem, 0, nb_octets);
return(pt_mem);
}
/*******************************/
void MyFree (void * pt_mem)
/*******************************/
{
if( pt_mem ) free(pt_mem);
}
/****************************************************/
/* Display a generic info about kikac (copyright..) */
/* Common tp CVPCB, EESCHEMA, PCBNEW and GERBVIEW */
/****************************************************/
/****************************************************/
/* Display a generic info about kikac (copyright..) */
/* Common tp CVPCB, EESCHEMA, PCBNEW and GERBVIEW */
/****************************************************/
#include "fctsys.h"
#include "gr_basic.h"
......@@ -14,53 +14,52 @@
// Import:
extern wxString g_Main_Title;
/* Program title strings used in about dialog. They are kept hear to make
/* Program title strings used in about dialog. They are kept here to make
* it easy to update the copyright dates. */
wxString g_KicadAboutTitle = wxT("** KICAD (jul 2000 .. 2008) **");
wxString g_CvpcbAboutTitle = wxT("** CVPCB (sept 1992 .. 2008) **");
wxString g_EeschemaAboutTitle = wxT("** EESCHEMA (sept 1994 .. 2008) **");
wxString g_PcbnewAboutTitle = wxT("** PCBNEW (sept 1992 .. 2008) **");
wxString g_GerbviewAboutTitle = wxT("** GERBVIEW (jul 2001 .. 2008) **");
wxString g_KicadAboutTitle = wxT( "** KICAD (jul 2000 .. 2008) **" );
wxString g_CvpcbAboutTitle = wxT( "** CVPCB (sept 1992 .. 2008) **" );
wxString g_EeschemaAboutTitle = wxT( "** EESCHEMA (sept 1994 .. 2008) **" );
wxString g_PcbnewAboutTitle = wxT( "** PCBNEW (sept 1992 .. 2008) **" );
wxString g_GerbviewAboutTitle = wxT( "** GERBVIEW (jul 2001 .. 2008) **" );
// Routines Locales
/*******************************************/
void Print_Kicad_Infos(wxWindow * frame, const wxString& title)
/*******************************************/
/**************************************************************/
void Print_Kicad_Infos( wxWindow* frame, const wxString& title,
const wxString& aExtra_infos )
/**************************************************************/
{
wxString AboutCaption = wxT("About ");
wxString AboutCaption = wxT( "About " );
wxString Msg = title;
Msg << wxT("\n\n") << _("Build Version:") << wxT("\n") ;
Msg << wxT( "\n\n" ) << _( "Build Version:" ) << wxT( "\n" );
Msg << g_Main_Title << wxT(" ") << GetBuildVersion();
Msg << g_Main_Title << wxT( " " ) << GetBuildVersion();
#if wxUSE_UNICODE
Msg << wxT(" - Unicode version");
Msg << wxT( " - Unicode version" );
#else
Msg << wxT(" - Ansi version");
Msg << wxT( " - Ansi version" );
#endif
#ifdef KICAD_PYTHON
Msg << wxT("\n");
Msg << wxT( "python : " );
Msg << wxString::FromAscii( PyHandler::GetInstance()->GetVersion() );
Msg << wxT( "\n" );
Msg << wxT( "python : " );
Msg << wxString::FromAscii( PyHandler::GetInstance()->GetVersion() );
#endif
Msg << wxT("\n\n") << _("Author:");
Msg << wxT(" JP CHARRAS\n\n") << _("Based on wxWidgets ");
Msg << wxMAJOR_VERSION << wxT(".") <<
wxMINOR_VERSION << wxT(".") << wxRELEASE_NUMBER;
if( wxSUBRELEASE_NUMBER )
Msg << wxT(".") << wxSUBRELEASE_NUMBER;
Msg << _("\n\nGPL License");
Msg << _("\n\nAuthor's sites:\n");
Msg << wxT("http://iut-tice.ujf-grenoble.fr/kicad/\n");
Msg << wxT("http://www.gipsa-lab.inpg.fr/realise_au_lis/kicad/");
Msg << _("\n\nInternational wiki:\n");
Msg << wxT("http://kicad.sourceforge.net/\n");
Msg << wxT( "\n\n" ) << _( "Author:" );
Msg << wxT( " JP CHARRAS\n\n" ) << _( "Based on wxWidgets " );
Msg << wxMAJOR_VERSION << wxT( "." ) <<
wxMINOR_VERSION << wxT( "." ) << wxRELEASE_NUMBER;
if( wxSUBRELEASE_NUMBER )
Msg << wxT( "." ) << wxSUBRELEASE_NUMBER;
Msg << _( "\n\nGPL License" );
Msg << _( "\n\nAuthor's sites:\n" );
Msg << wxT( "http://iut-tice.ujf-grenoble.fr/kicad/\n" );
Msg << wxT( "http://www.gipsa-lab.inpg.fr/realise_au_lis/kicad/" );
Msg << _( "\n\nInternational wiki:\n" );
Msg << wxT( "http://kicad.sourceforge.net/\n" );
Msg << aExtra_infos;
AboutCaption << g_Main_Title << wxT(" ") << GetBuildVersion();
AboutCaption << g_Main_Title << wxT( " " ) << GetBuildVersion();
wxMessageBox(Msg, AboutCaption, wxICON_INFORMATION, frame);
wxMessageBox( Msg, AboutCaption, wxICON_INFORMATION, frame );
}
......@@ -71,7 +71,7 @@ endif(APPLE)
add_executable(cvpcb WIN32 MACOSX_BUNDLE ${CVPCB_SRCS} ${CVPCB_EXTRA_SRCS} ${CVPCB_RESOURCES})
target_link_libraries(cvpcb 3d-viewer common polygon bitmaps ${wxWidgets_LIBRARIES} ${OPENGL_LIBRARIES})
target_link_libraries(cvpcb 3d-viewer common polygon kbool bitmaps ${wxWidgets_LIBRARIES} ${OPENGL_LIBRARIES})
install(TARGETS cvpcb RUNTIME DESTINATION ${KICAD_BIN}
COMPONENT binary)
......@@ -3,10 +3,12 @@ OBJSUFF = o
EXTRACPPFLAGS += -DCVPCB -fno-strict-aliasing\
-I./ -I../cvpcb -I../include -Ibitmaps\
-I../pcbnew -I../3d-viewer\
-I../polygon
-I../pcbnew -I../3d-viewer -I ../polygon
EXTRALIBS = ../common/common.a ../bitmaps/libbitmaps.a\
../polygon/lib_polygon.a\
../polygon/kbool/src/libkbool.a
EXTRALIBS = ../common/common.a ../bitmaps/libbitmaps.a ../polygon/lib_polygon.a
LIBVIEWER3D = ../3d-viewer/3d-viewer.a
......
......@@ -73,7 +73,7 @@ endif(APPLE)
add_executable(gerbview WIN32 MACOSX_BUNDLE ${GERBVIEW_SRCS} ${GERBVIEW_EXTRA_SRCS} ${GERBVIEW_RESOURCES})
target_link_libraries(gerbview 3d-viewer common polygon bitmaps ${wxWidgets_LIBRARIES})
target_link_libraries(gerbview 3d-viewer common polygon kbool bitmaps ${wxWidgets_LIBRARIES})
install(TARGETS gerbview RUNTIME DESTINATION ${KICAD_BIN}
COMPONENT binary)
......@@ -9,7 +9,7 @@ COMMON_GLOBL wxString g_BuildVersion
# include "config.h"
(wxT(KICAD_SVN_VERSION))
# else
(wxT("(20080429-r1010)"))
(wxT("(20080530-r1107)"))
# endif
#endif
;
......
......@@ -48,10 +48,10 @@ enum pseudokeys {
#define EESCHEMA_EXE wxT( "eeschema" )
#define GERBVIEW_EXE wxT( "gerbview" )
#else
#define CVPCB_EXE wxT("cvpcb.app/Contents/MacOS/cvpcb")
#define PCBNEW_EXE wxT("pcbnew.app/Contents/MacOS/pcbnew")
#define EESCHEMA_EXE wxT("eeschema.app/Contents/MacOS/eeschema")
#define GERBVIEW_EXE wxT("gerbview.app/Contents/MacOS/gerbview")
#define CVPCB_EXE wxT( "cvpcb.app/Contents/MacOS/cvpcb" )
#define PCBNEW_EXE wxT( "pcbnew.app/Contents/MacOS/pcbnew" )
#define EESCHEMA_EXE wxT( "eeschema.app/Contents/MacOS/eeschema" )
#define GERBVIEW_EXE wxT( "gerbview.app/Contents/MacOS/gerbview" )
#endif
#endif
......@@ -97,7 +97,7 @@ public:
bool m_Setup; /* TRUE -> inscription en setup (registration base)*/
public:
PARAM_CFG_BASE( const wxChar * ident, const paramcfg_id type, const wxChar * group = NULL );
PARAM_CFG_BASE( const wxChar* ident, const paramcfg_id type, const wxChar* group = NULL );
~PARAM_CFG_BASE() { };
};
......@@ -109,12 +109,12 @@ public:
int m_Default; /* valeur par defaut */
public:
PARAM_CFG_INT( const wxChar * ident, int* ptparam,
PARAM_CFG_INT( const wxChar* ident, int* ptparam,
int default_val = 0, int min = INT_MINVAL, int max = INT_MAXVAL,
const wxChar * group = NULL );
PARAM_CFG_INT( bool Insetup, const wxChar * ident, int* ptparam,
const wxChar* group = NULL );
PARAM_CFG_INT( bool Insetup, const wxChar* ident, int* ptparam,
int default_val = 0, int min = INT_MINVAL, int max = INT_MAXVAL,
const wxChar * group = NULL );
const wxChar* group = NULL );
};
class PARAM_CFG_SETCOLOR : public PARAM_CFG_BASE
......@@ -124,10 +124,10 @@ public:
int m_Default; /* valeur par defaut */
public:
PARAM_CFG_SETCOLOR( const wxChar * ident, int* ptparam,
int default_val, const wxChar * group = NULL );
PARAM_CFG_SETCOLOR( bool Insetup, const wxChar * ident, int* ptparam,
int default_val, const wxChar * group = NULL );
PARAM_CFG_SETCOLOR( const wxChar* ident, int* ptparam,
int default_val, const wxChar* group = NULL );
PARAM_CFG_SETCOLOR( bool Insetup, const wxChar* ident, int* ptparam,
int default_val, const wxChar* group = NULL );
};
class PARAM_CFG_DOUBLE : public PARAM_CFG_BASE
......@@ -138,12 +138,12 @@ public:
double m_Min, m_Max; /* valeurs extremes du parametre */
public:
PARAM_CFG_DOUBLE( const wxChar * ident, double* ptparam,
PARAM_CFG_DOUBLE( const wxChar* ident, double* ptparam,
double default_val = 0.0, double min = 0.0, double max = 10000.0,
const wxChar * group = NULL );
PARAM_CFG_DOUBLE( bool Insetup, const wxChar * ident, double* ptparam,
const wxChar* group = NULL );
PARAM_CFG_DOUBLE( bool Insetup, const wxChar* ident, double* ptparam,
double default_val = 0.0, double min = 0.0, double max = 10000.0,
const wxChar * group = NULL );
const wxChar* group = NULL );
};
class PARAM_CFG_BOOL : public PARAM_CFG_BASE
......@@ -153,10 +153,10 @@ public:
int m_Default; /* valeur par defaut */
public:
PARAM_CFG_BOOL( const wxChar * ident, bool * ptparam,
int default_val = FALSE, const wxChar * group = NULL );
PARAM_CFG_BOOL( bool Insetup, const wxChar * ident, bool * ptparam,
int default_val = FALSE, const wxChar * group = NULL );
PARAM_CFG_BOOL( const wxChar* ident, bool* ptparam,
int default_val = FALSE, const wxChar* group = NULL );
PARAM_CFG_BOOL( bool Insetup, const wxChar* ident, bool* ptparam,
int default_val = FALSE, const wxChar* group = NULL );
};
......@@ -166,11 +166,11 @@ public:
wxString* m_Pt_param; /* pointeur sur le parametre a configurer */
public:
PARAM_CFG_WXSTRING( const wxChar * ident, wxString * ptparam, const wxChar * group = NULL );
PARAM_CFG_WXSTRING( bool Insetup,
const wxChar * ident,
wxString * ptparam,
const wxChar * group = NULL );
PARAM_CFG_WXSTRING( const wxChar* ident, wxString* ptparam, const wxChar* group = NULL );
PARAM_CFG_WXSTRING( bool Insetup,
const wxChar* ident,
wxString* ptparam,
const wxChar* group = NULL );
};
class PARAM_CFG_LIBNAME_LIST : public PARAM_CFG_BASE
......@@ -179,9 +179,9 @@ public:
wxArrayString* m_Pt_param; /* pointeur sur le parametre a configurer */
public:
PARAM_CFG_LIBNAME_LIST( const wxChar * ident,
wxArrayString * ptparam,
const wxChar * group = NULL );
PARAM_CFG_LIBNAME_LIST( const wxChar* ident,
wxArrayString* ptparam,
const wxChar* group = NULL );
};
......@@ -195,7 +195,7 @@ private:
wxListBox* m_List;
public:
WinEDA_TextFrame( wxWindow * parent, const wxString &title );
WinEDA_TextFrame( wxWindow* parent, const wxString& title );
void Append( const wxString& text );
private:
......@@ -221,24 +221,24 @@ public:
int m_BottomMargin;
public:
Ki_PageDescr( const wxSize &size, const wxPoint &offset, const wxString &name );
Ki_PageDescr( const wxSize& size, const wxPoint& offset, const wxString& name );
};
/* Standard page sizes in 1/1000 inch */
#if defined EDA_BASE
Ki_PageDescr g_Sheet_A4( wxSize( 11700, 8267 ), wxPoint( 0, 0 ), wxT( "A4" ) );
Ki_PageDescr g_Sheet_A3( wxSize( 16535, 11700 ), wxPoint( 0, 0 ), wxT( "A3" ) );
Ki_PageDescr g_Sheet_A2( wxSize( 23400, 16535 ), wxPoint( 0, 0 ), wxT( "A2" ) );
Ki_PageDescr g_Sheet_A1( wxSize( 33070, 23400 ), wxPoint( 0, 0 ), wxT( "A1" ) );
Ki_PageDescr g_Sheet_A0( wxSize( 46800, 33070 ), wxPoint( 0, 0 ), wxT( "A0" ) );
Ki_PageDescr g_Sheet_A( wxSize( 11000, 8500 ), wxPoint( 0, 0 ), wxT( "A" ) );
Ki_PageDescr g_Sheet_B( wxSize( 17000, 11000 ), wxPoint( 0, 0 ), wxT( "B" ) );
Ki_PageDescr g_Sheet_C( wxSize( 22000, 17000 ), wxPoint( 0, 0 ), wxT( "C" ) );
Ki_PageDescr g_Sheet_D( wxSize( 34000, 22000 ), wxPoint( 0, 0 ), wxT( "D" ) );
Ki_PageDescr g_Sheet_E( wxSize( 44000, 34000 ), wxPoint( 0, 0 ), wxT( "E" ) );
Ki_PageDescr g_Sheet_GERBER( wxSize( 32000, 32000 ), wxPoint( 0, 0 ), wxT( "GERBER" ) );
Ki_PageDescr g_Sheet_user( wxSize( 17000, 11000 ), wxPoint( 0, 0 ), wxT( "User" ) );
Ki_PageDescr g_Sheet_A4( wxSize( 11700, 8267 ), wxPoint( 0, 0 ), wxT( "A4" ) );
Ki_PageDescr g_Sheet_A3( wxSize( 16535, 11700 ), wxPoint( 0, 0 ), wxT( "A3" ) );
Ki_PageDescr g_Sheet_A2( wxSize( 23400, 16535 ), wxPoint( 0, 0 ), wxT( "A2" ) );
Ki_PageDescr g_Sheet_A1( wxSize( 33070, 23400 ), wxPoint( 0, 0 ), wxT( "A1" ) );
Ki_PageDescr g_Sheet_A0( wxSize( 46800, 33070 ), wxPoint( 0, 0 ), wxT( "A0" ) );
Ki_PageDescr g_Sheet_A( wxSize( 11000, 8500 ), wxPoint( 0, 0 ), wxT( "A" ) );
Ki_PageDescr g_Sheet_B( wxSize( 17000, 11000 ), wxPoint( 0, 0 ), wxT( "B" ) );
Ki_PageDescr g_Sheet_C( wxSize( 22000, 17000 ), wxPoint( 0, 0 ), wxT( "C" ) );
Ki_PageDescr g_Sheet_D( wxSize( 34000, 22000 ), wxPoint( 0, 0 ), wxT( "D" ) );
Ki_PageDescr g_Sheet_E( wxSize( 44000, 34000 ), wxPoint( 0, 0 ), wxT( "E" ) );
Ki_PageDescr g_Sheet_GERBER( wxSize( 32000, 32000 ), wxPoint( 0, 0 ), wxT( "GERBER" ) );
Ki_PageDescr g_Sheet_user( wxSize( 17000, 11000 ), wxPoint( 0, 0 ), wxT( "User" ) );
#else
extern Ki_PageDescr g_Sheet_A4;
......@@ -316,7 +316,7 @@ COMMON_GLOBL wxString g_EditorName;
// Gestion de la grille "utilisateur" (User Grid)
#ifdef EDA_BASE
wxRealPoint g_UserGrid( 0.01, 0.01 );
wxRealPoint g_UserGrid( 0.01, 0.01 );
int g_UserGrid_Unit = INCHES;
#else
......@@ -364,7 +364,7 @@ class WinEDA_DrawPanel;
* @param aPoint The point to output.
* @return wxString& - the input string
*/
wxString& operator << ( wxString& aString, const wxPoint& aPoint );
wxString& operator <<( wxString& aString, const wxPoint& aPoint );
/**
......@@ -374,10 +374,10 @@ wxString& operator << ( wxString& aString, const wxPoint& aPoint );
* @param aFlags The same args as allowed for wxExecute()
* @return bool - true if success, else false
*/
bool ProcessExecute( const wxString& aCommandLine, int aFlags = wxEXEC_ASYNC );
bool ProcessExecute( const wxString& aCommandLine, int aFlags = wxEXEC_ASYNC );
wxString ReturnPcbLayerName( int layer_number, bool is_filename = FALSE );
wxString ReturnPcbLayerName( int layer_number, bool is_filename = FALSE );
/* Return the name of the layer number "layer_number".
* if "is_filename" == TRUE, the name can be used for a file name
......@@ -431,19 +431,19 @@ void OpenFile( const wxString& file );
bool EDA_DirectorySelector( const wxString& Title, /* Titre de la fenetre */
wxString& Path, /* Chemin par defaut */
int flag, /* reserve */
wxWindow* Frame, /* parent frame */
const wxPoint& Pos );
wxString EDA_FileSelector( const wxString& Title, /* Window title */
const wxString& Path, /* default path */
const wxString& FileName, /* default filename */
const wxString& Ext, /* default extension */
const wxString& Mask, /* Display filename mask */
wxWindow* Frame, /* parent frame */
int flag, /* wxSAVE, wxOPEN ..*/
const bool keep_working_directory, /* true = do not change the C.W.D. */
wxString& Path, /* Chemin par defaut */
int flag, /* reserve */
wxWindow* Frame, /* parent frame */
const wxPoint& Pos );
wxString EDA_FileSelector( const wxString &Title, /* Window title */
const wxString &Path, /* default path */
const wxString &FileName, /* default filename */
const wxString &Ext, /* default extension */
const wxString &Mask, /* Display filename mask */
wxWindow * Frame, /* parent frame */
int flag, /* wxSAVE, wxOPEN ..*/
const bool keep_working_directory, /* true = do not change the C.W.D. */
const wxPoint& Pos = wxPoint( -1, -1 )
);
......@@ -461,8 +461,8 @@ wxString MakeFileName( const wxString& dir,
* retourne la chaine calculee */
wxString MakeReducedFileName( const wxString& fullfilename,
const wxString& default_path,
const wxString& default_ext );
const wxString& default_path,
const wxString& default_ext );
/* Calcule le nom "reduit" d'un file d'apres les chaines
* fullfilename = nom complet
......@@ -488,14 +488,14 @@ int ExecuteFile( wxWindow* frame, const wxString& ExecFile,
const wxString& param = wxEmptyString );
void AddDelimiterString( wxString& string );
void SetRealLibraryPath( const wxString& shortlibname );/* met a jour
* le chemin des librairies RealLibDirBuffer (global)
* a partir de UserLibDirBuffer (global):
* Si UserLibDirBuffer non vide RealLibDirBuffer = UserLibDirBuffer.
* Sinon si variable d'environnement KICAD definie (KICAD = chemin pour kicad),
* UserLibDirBuffer = <KICAD>/shortlibname;
* Sinon UserLibDirBuffer = <Chemin des binaires>../shortlibname/
*/
void SetRealLibraryPath( const wxString& shortlibname ); /* met a jour
* le chemin des librairies RealLibDirBuffer (global)
* a partir de UserLibDirBuffer (global):
* Si UserLibDirBuffer non vide RealLibDirBuffer = UserLibDirBuffer.
* Sinon si variable d'environnement KICAD definie (KICAD = chemin pour kicad),
* UserLibDirBuffer = <KICAD>/shortlibname;
* Sinon UserLibDirBuffer = <Chemin des binaires>../shortlibname/
*/
wxString FindKicadHelpPath();
/* Find absolute path for kicad/help (or kicad/help/<language>) */
......@@ -564,26 +564,28 @@ bool WildCompareString( const wxString& pattern, const wxString& string_t
bool case_sensitive = TRUE );
/* compare 2 noms de composants, selon regles usuelles
* ( Jokers * , ? , autoriss).
* ( Jokers * , ? , autorises).
* la chaine de reference est "pattern"
* si case_sensitive == TRUE (default), comparaison exacte
* retourne TRUE si match FALSE si differences */
char* to_point( char* Text );
/* convertit les , en . dans une chaine. utilis pour compenser la fct printf
/* convertit les , en . dans une chaine. utilise pour compenser la fct printf
* qui genere les flottants avec une virgule au lieu du point en mode international */
/****************/
/* infospgm.cpp */
/****************/
extern wxString g_KicadAboutTitle;
extern wxString g_CvpcbAboutTitle;
extern wxString g_EeschemaAboutTitle;
extern wxString g_PcbnewAboutTitle;
extern wxString g_GerbviewAboutTitle;
extern wxString g_KicadAboutTitle;
extern wxString g_CvpcbAboutTitle;
extern wxString g_EeschemaAboutTitle;
extern wxString g_PcbnewAboutTitle;
extern wxString g_GerbviewAboutTitle;
void Print_Kicad_Infos( wxWindow* frame, const wxString& title );
void Print_Kicad_Infos( wxWindow* frame,
const wxString& title,
const wxString& aExtra_infos );
/**************/
/* common.cpp */
......@@ -591,10 +593,10 @@ void Print_Kicad_Infos( wxWindow* frame, const wxString& title );
wxString GetBuildVersion(); /* Return the build date */
void Affiche_1_Parametre( WinEDA_DrawFrame* frame,
int pos_X,
const wxString& texte_H,
const wxString& texte_L,
int color );
int pos_X,
const wxString& texte_H,
const wxString& texte_L,
int color );
/*
* Routine d'affichage d'un parametre.
......@@ -608,16 +610,16 @@ void Affiche_1_Parametre( WinEDA_DrawFrame* frame,
* color = couleur d'affichage
*/
void AfficheDoc( WinEDA_DrawFrame* frame, const wxString& Doc, const wxString& KeyW );
void AfficheDoc( WinEDA_DrawFrame* frame, const wxString& Doc, const wxString& KeyW );
/* Routine d'affichage de la documentation associee a un composant */
int GetTimeStamp();
int GetTimeStamp();
/* Retoure une identification temporelle (Time stamp) differente a chaque appel */
int DisplayColorFrame( wxWindow* parent, int OldColor );
int GetCommandOptions( const int argc, const char** argv, const char* stringtst,
const char** optarg, int* optind );
int DisplayColorFrame( wxWindow* parent, int OldColor );
int GetCommandOptions( const int argc, const char** argv, const char* stringtst,
const char** optarg, int* optind );
const wxString& valeur_param( int valeur, wxString& buf_texte );
......@@ -628,28 +630,28 @@ const wxString& valeur_param( int valeur, wxString& buf_texte );
* suivie de " ou mm
*/
wxString ReturnUnitSymbol( int Units = g_UnitMetric );
int ReturnValueFromString( int Units, const wxString& TextValue, int Internal_Unit );
wxString ReturnStringFromValue( int Units, int Value, int Internal_Unit );
void AddUnitSymbol( wxStaticText& Stext, int Units = g_UnitMetric );
wxString ReturnUnitSymbol( int Units = g_UnitMetric );
int ReturnValueFromString( int Units, const wxString& TextValue, int Internal_Unit );
wxString ReturnStringFromValue( int Units, int Value, int Internal_Unit );
void AddUnitSymbol( wxStaticText& Stext, int Units = g_UnitMetric );
/* Add string " (mm):" or " ("):" to the static text Stext.
* Used in dialog boxes for entering values depending on selected units */
void PutValueInLocalUnits( wxTextCtrl& TextCtr, int Value, int Internal_Unit );
void PutValueInLocalUnits( wxTextCtrl& TextCtr, int Value, int Internal_Unit );
/* Convert the number Value in a string according to the internal units
* and the selected unit (g_UnitMetric) and put it in the wxTextCtrl TextCtrl */
int ReturnValueFromTextCtrl( const wxTextCtrl& TextCtr, int Internal_Unit );
int ReturnValueFromTextCtrl( const wxTextCtrl& TextCtr, int Internal_Unit );
/* Convert the Value in the wxTextCtrl TextCtrl in an integer,
* according to the internal units and the selected unit (g_UnitMetric) */
double To_User_Unit( bool is_metric, int val, int internal_unit_value );
int From_User_Unit( bool is_metric, double val, int internal_unit_value );
wxString GenDate();
void MyFree( void* pt_mem );
void* MyZMalloc( size_t nb_octets );
void* MyMalloc( size_t nb_octets );
double To_User_Unit( bool is_metric, int val, int internal_unit_value );
int From_User_Unit( bool is_metric, double val, int internal_unit_value );
wxString GenDate();
void MyFree( void* pt_mem );
void* MyZMalloc( size_t nb_octets );
void* MyMalloc( size_t nb_octets );
/****************/
......@@ -671,9 +673,9 @@ bool GetAssociatedDocument( wxFrame* frame, const wxString& LibPath,
/****************************/
/* get_component_dialog.cpp */
/****************************/
wxString GetComponentName( WinEDA_DrawFrame* frame,
wxArrayString& HistoryList, const wxString& Title,
wxString (* AuxTool)(WinEDA_DrawFrame* parent) );
wxString GetComponentName( WinEDA_DrawFrame * frame,
wxArrayString & HistoryList, const wxString &Title,
wxString (*AuxTool)( WinEDA_DrawFrame * parent ) );
/* Dialog frame to choose a component name */
void AddHistoryComponentName( wxArrayString& HistoryList, const wxString& Name );
......
......@@ -329,6 +329,8 @@ public:
~WinEDA_PcbFrame();
void GetKicadAbout( wxCommandEvent& event );
// Configurations:
void InstallConfigFrame( const wxPoint& pos );
void Process_Config( wxCommandEvent& event );
......
No preview for this file type
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -27,6 +27,24 @@
// UnComment this to load subdirs files in the tree project
#define ADD_FILES_IN_SUBDIRS
// list of files extensions listed in the tree project window
// *.sch files are always allowed, do not add here
// Add extensions in a compatible regex format to see others files types
const wxChar * s_AllowedExtensionsToList[] =
{
wxT( "^.*\\.pro$" ),
wxT( "^.*\\.pdf$" ),
wxT( "^[^$].*\\.brd$" ),
wxT( "^.*\\.net$" ),
wxT( "^.*\\.txt$" ),
wxT( "^.*\\.pho$" ),
wxT( "^.*\\.odt$" ),
wxT( "^.*\\.sxw$" ),
wxT( "^.*\\.htm$" ),
wxT( "^.*\\.html$" ),
NULL // end of list
};
/******************************************************************/
WinEDA_PrjFrame::WinEDA_PrjFrame( WinEDA_MainFrame* parent,
const wxPoint& pos,
......@@ -44,12 +62,10 @@ WinEDA_PrjFrame::WinEDA_PrjFrame( WinEDA_MainFrame* parent,
* for a given file type.
*/
m_Filters.push_back( wxT( "^.*\\.sch$" ) ); // note: sch filter must be first because of a test in AddFile() below
m_Filters.push_back( wxT( "^.*\\.pro$" ) );
m_Filters.push_back( wxT( "^.*\\.pdf$" ) );
m_Filters.push_back( wxT( "^[^$].*\\.brd$" ) );
m_Filters.push_back( wxT( "^.*\\.net$" ) );
m_Filters.push_back( wxT( "^.*\\.txt$" ) );
m_Filters.push_back( wxT( "^.*\\.pho$" ) );
for ( int ii = 0; s_AllowedExtensionsToList[ii] != NULL; ii++ )
{
m_Filters.push_back( s_AllowedExtensionsToList[ii] );
}
m_Filters.push_back( wxT( "^no kicad files found" ) );
#ifdef KICAD_PYTHON
......
KICAD_SUBDIRS = common bitmaps 3d-viewer polygon eeschema eeschema/plugins pcbnew kicad cvpcb gerbview
KICAD_SUBDIRS = common bitmaps 3d-viewer polygon polygon/kbool/src eeschema eeschema/plugins pcbnew kicad cvpcb gerbview
KICAD_SUBDIRS_BIN = eeschema eeschema/plugins pcbnew cvpcb kicad gerbview
# How to invoke make:
MAKE = make -k -f makefile.g95
......
......@@ -163,7 +163,7 @@ endif(APPLE)
add_executable(pcbnew WIN32 MACOSX_BUNDLE ${PCBNEW_SRCS} ${PCBNEW_EXTRA_SRCS} ${PCBNEW_RESOURCES})
target_link_libraries(pcbnew 3d-viewer common polygon bitmaps ${wxWidgets_LIBRARIES} ${OPENGL_LIBRARIES} )
target_link_libraries(pcbnew 3d-viewer common polygon kbool bitmaps ${wxWidgets_LIBRARIES} ${OPENGL_LIBRARIES} )
install(TARGETS pcbnew RUNTIME DESTINATION ${KICAD_BIN}
COMPONENT binary)
......
EXTRALIBS = ../common/common.a ../bitmaps/libbitmaps.a ../polygon/lib_polygon.a
EXTRALIBS = ../common/common.a ../bitmaps/libbitmaps.a\
../polygon/lib_polygon.a\
../polygon/kbool/src/libkbool.a
EXTRACPPFLAGS += -DPCBNEW -fno-strict-aliasing -I./ -Ibitmaps -I../include -I../share\
-I../pcbnew -I../3d-viewer -I../polygon
......
......@@ -478,7 +478,7 @@ void WinEDA_PcbFrame::createPopupMenuForTracks( TRACK* Track, wxMenu* PopMenu )
wxMenu* via_mnu = new wxMenu();
ADD_MENUITEM_WITH_SUBMENU( PopMenu, via_mnu,
ID_POPUP_PCB_VIA_EDITING, _( "Edit Via" ), edit_xpm );
ID_POPUP_PCB_VIA_EDITING, _( "Edit Via Drill" ), edit_xpm );
ADD_MENUITEM( via_mnu, ID_POPUP_PCB_VIA_HOLE_TO_DEFAULT,
_( "Set via hole to Default" ), apply_xpm );
msg = _( "Set via hole to a specific value. This specfic value is currently" );
......@@ -486,7 +486,7 @@ void WinEDA_PcbFrame::createPopupMenuForTracks( TRACK* Track, wxMenu* PopMenu )
ADD_MENUITEM_WITH_HELP( via_mnu, ID_POPUP_PCB_VIA_HOLE_TO_VALUE,
_( "Set via hole to alt value" ), msg,
options_new_pad_xpm );
msg = _( "Set alt via hole value. This value is currently" );
msg = _( "Set a specific via hole value. This value is currently" );
msg << wxT(" ") << ReturnStringFromValue( g_UnitMetric, g_DesignSettings.m_ViaDrillCustomValue, m_InternalUnits );
ADD_MENUITEM_WITH_HELP( via_mnu, ID_POPUP_PCB_VIA_HOLE_ENTER_VALUE,
_( "Set the via hole alt value" ), msg, edit_xpm );
......@@ -559,18 +559,18 @@ void WinEDA_PcbFrame::createPopupMenuForTracks( TRACK* Track, wxMenu* PopMenu )
ADD_MENUITEM_WITH_SUBMENU( PopMenu, track_mnu,
ID_POPUP_PCB_EDIT_TRACK_MNU, _( "Change Width" ), width_track_xpm );
ADD_MENUITEM( track_mnu, ID_POPUP_PCB_EDIT_TRACKSEG,
Track->Type()==TYPEVIA ? _( "Edit Via" ) : _( "Edit Segment" ), width_segment_xpm );
Track->Type()==TYPEVIA ? _( "Change Via Size" ) : _( "Change Segment Width" ), width_segment_xpm );
ADD_MENUITEM( track_mnu, ID_POPUP_PCB_EDIT_TRACK,
_( "Edit Track" ), width_track_xpm );
_( "Change Track Width" ), width_track_xpm );
ADD_MENUITEM( track_mnu, ID_POPUP_PCB_EDIT_NET,
_( "Edit Net" ), width_net_xpm );
_( "Change Net" ), width_net_xpm );
ADD_MENUITEM( track_mnu, ID_POPUP_PCB_EDIT_ALL_VIAS_AND_TRACK_SIZE,
_( "Edit ALL Tracks and Vias" ), width_track_via_xpm );
_( "Change ALL Tracks and Vias" ), width_track_via_xpm );
ADD_MENUITEM( track_mnu, ID_POPUP_PCB_EDIT_ALL_VIAS_SIZE,
_( "Edit ALL Vias (no track)" ), width_vias_xpm );
_( "Change ALL Vias (no track)" ), width_vias_xpm );
ADD_MENUITEM( track_mnu, ID_POPUP_PCB_EDIT_ALL_TRACK_SIZE,
_( "Edit ALL Tracks (no via)" ), width_track_xpm );
_( "Change ALL Tracks (no via)" ), width_track_xpm );
}
// Delete control:
......
......@@ -12,7 +12,7 @@
#include "protos.h"
#include "id.h"
#include "drc_stuff.h"
#include "kbool/include/booleng.h"
/*******************************/
/* class WinEDA_PcbFrame */
......@@ -99,7 +99,7 @@ BEGIN_EVENT_TABLE( WinEDA_PcbFrame, WinEDA_BasePcbFrame )
// Menu Help
EVT_MENU( ID_GENERAL_HELP, WinEDA_DrawFrame::GetKicadHelp )
EVT_MENU( ID_KICAD_ABOUT, WinEDA_DrawFrame::GetKicadAbout )
EVT_MENU( ID_KICAD_ABOUT, WinEDA_PcbFrame::GetKicadAbout )
// Menu 3D Frame
EVT_MENU( ID_MENU_PCB_SHOW_3D_FRAME, WinEDA_PcbFrame::Show3D_Frame )
......@@ -245,8 +245,9 @@ WinEDA_PcbFrame::WinEDA_PcbFrame( wxWindow* father, WinEDA_App* parent,
ReCreateOptToolbar();
}
/************************************/
WinEDA_PcbFrame::~WinEDA_PcbFrame()
/************************************/
{
m_Parent->m_PcbFrame = NULL;
SetBaseScreen( ScreenPcb );
......@@ -566,3 +567,15 @@ void WinEDA_PcbFrame::SetToolbars()
DisplayUnitsMsg();
}
/***********************************************************/
void WinEDA_PcbFrame::GetKicadAbout( wxCommandEvent& event )
/**********************************************************/
{
wxString extra_message =
wxT("\nPcbnew uses the kbool library (boolean operations on sets of 2d polygons)\n");
extra_message << wxT("version ") << wxT(KBOOL_VERSION)
<< wxT("\nsee http://boolean.klaasholwerda.nl/bool.html\n");
Print_Kicad_Infos( this, m_AboutTitle, extra_message );
}
......@@ -291,7 +291,7 @@ int BOARD::ClipAreaPolygon( ZONE_CONTAINER* CurrArea,
NewArea = AddArea( CurrArea->GetNet(), CurrArea->GetLayer(), 0, 0, 0 );
// remove the poly that was automatically created for the new area
// and replace it with a poly from NormalizeWithGpc
// and replace it with a poly from NormalizeWithKbool
delete NewArea->m_Poly;
NewArea->m_Poly = new_p;
NewArea->m_Poly->Draw();
......@@ -694,183 +694,109 @@ int BOARD::CombineAreas( ZONE_CONTAINER* area_ref, ZONE_CONTAINER* area_to_combi
#endif
// polygons intersect, combine them
CPolyLine* poly1 = area_ref->m_Poly;
CPolyLine* poly2 = area_to_combine->m_Poly;
std::vector<CArc> arc_array1;
std::vector<CArc> arc_array2;
bool keep_area_to_combine = false;
poly1->MakePolygonFromAreaOutlines( -1, &arc_array1 );
poly2->MakePolygonFromAreaOutlines( -1, &arc_array2 );
Bool_Engine* booleng = new Bool_Engine();
ArmBoolEng( booleng );
#ifdef USE_GPC_POLY_LIB
int n_ext_cont1 = 0;
for( int ic = 0; ic<poly1->GetGpcPoly()->num_contours; ic++ )
if( !( (poly1->GetGpcPoly()->hole)[ic] ) )
n_ext_cont1++;
area_ref->m_Poly->AddPolygonsToBoolEng( booleng, GROUP_A, -1, -1 );
area_to_combine->m_Poly->AddPolygonsToBoolEng( booleng, GROUP_B, -1, -1 );
booleng->Do_Operation( BOOL_OR );
int n_ext_cont2 = 0;
for( int ic = 0; ic<poly2->GetGpcPoly()->num_contours; ic++ )
if( !( (poly2->GetGpcPoly()->hole)[ic] ) )
n_ext_cont2++;
gpc_polygon* union_gpc = new gpc_polygon;
gpc_polygon_clip( GPC_UNION, poly1->GetGpcPoly(), poly2->GetGpcPoly(), union_gpc );
// get number of outside contours
int n_union_ext_cont = 0;
for( int ic = 0; ic<union_gpc->num_contours; ic++ )
if( !( (union_gpc->hole)[ic] ) )
n_union_ext_cont++;
// if no intersection, free new gpc and return
if( n_union_ext_cont == n_ext_cont1 + n_ext_cont2 )
// create area with external contour: Recreate only area edges, NOT holes
if( booleng->StartPolygonGet() )
{
gpc_free_polygon( union_gpc );
delete union_gpc;
return 0;
}
// intersection, replace area_ref->m_Poly with combined areas and remove area_to_combine
RemoveArea( area_to_combine );
area_ref->m_Poly->RemoveAllContours();
// create area with external contour
for( int ic = 0; ic<union_gpc->num_contours; ic++ )
{
if( !(union_gpc->hole)[ic] )
if( booleng->GetPolygonPointEdgeType() == KB_INSIDE_EDGE )
{
// external contour, replace this poly
for( int i = 0; i<union_gpc->contour[ic].num_vertices; i++ )
{
int x = (int) ( (union_gpc->contour)[ic].vertex )[i].x;
int y = (int) ( (union_gpc->contour)[ic].vertex )[i].y;
if( i==0 )
{
area_ref->m_Poly->Start( area_ref->GetLayer(
), x, y, area_ref->m_Poly->GetHatchStyle() );
}
else
area_ref->m_Poly->AppendCorner( x, y );
}
area_ref->m_Poly->Close();
DisplayError( NULL, wxT( "BOARD::CombineAreas() error: unexpected hole descriptor" ) );
}
}
// add holes
for( int ic = 0; ic<union_gpc->num_contours; ic++ )
{
if( (union_gpc->hole)[ic] )
area_ref->m_Poly->RemoveAllContours();
// foreach point in the polygon
bool first = true;
while( booleng->PolygonHasMorePoints() )
{
// hole
for( int i = 0; i<union_gpc->contour[ic].num_vertices; i++ )
int x = booleng->GetPolygonXPoint();
int y = booleng->GetPolygonYPoint();
if( first )
{
int x = (int) ( (union_gpc->contour)[ic].vertex )[i].x;
int y = (int) ( (union_gpc->contour)[ic].vertex )[i].y;
area_ref->m_Poly->AppendCorner( x, y );
first = false;
area_ref->m_Poly->Start( area_ref->GetLayer(
), x, y, area_ref->m_Poly->GetHatchStyle() );
}
area_ref->m_Poly->Close();
else
area_ref->m_Poly->AppendCorner( x, y );
}
}
area_ref->utility = 1;
area_ref->m_Poly->RestoreArcs( &arc_array1 );
area_ref->m_Poly->RestoreArcs( &arc_array2 );
area_ref->m_Poly->Draw();
gpc_free_polygon( union_gpc );
delete union_gpc;
return 1;
#endif
#ifdef USE_GPL_POLY_LIB
//@todo
#warning work in progress
wxString msg;
int n_ext_cont1 = poly1->GetPhpPoly()->m_cnt;
int n_ext_cont2 = poly2->GetPhpPoly()->m_cnt;
polygon* union_polygon = NULL;
union_polygon = poly1->GetPhpPoly()->boolean( poly2->GetPhpPoly(), A_OR_B );
if ( union_polygon == NULL )
return 0;
// get number of outside contours
int n_union_ext_cont = union_polygon->m_cnt;
msg.Printf(wxT("cnt res = %d, pts1,2 = %d,%d"), n_union_ext_cont , n_ext_cont1, n_ext_cont2);
wxMessageBox(msg);
// if no intersection, free new gpc and return
#if 0
if( n_union_ext_cont == n_ext_cont1 + n_ext_cont2 )
{
wxMessageBox(wxT("no change polys"));
delete union_polygon;
return 0;
booleng->EndPolygonGet();
area_ref->m_Poly->Close();
}
#endif
wxMessageBox(wxT("merge areas"));
// intersection, replace area_ref->m_Poly with combined areas and remove area_to_combine
RemoveArea( area_to_combine );
area_ref->m_Poly->RemoveAllContours();
// create area with external contour
// for( int ic = 0; ic < union_polygon->m_cnt; ic++ )
// Recreate the area_to_combine if a second polygon exists
// if not exists , the first poly contains the 2 initial polygons
#if 0 // TestAreaIntersection must be called before combine areas, so
// 2 intersecting areas are expected, and only one outline contour after combining areas
else
{
// if( !(union_gpc->hole)[ic] ) // Recreate only area edges, NOT holes (todo..)
area_to_combine->m_Poly->RemoveAllContours();
keep_area_to_combine = true;
// create area with external contour: Recreate only area edges, NOT holes (todo..)
{
// external contour, replace this poly
vertex * curr_vertex = union_polygon->getFirst();
for( int ii = 0; ii < union_polygon->m_cnt; ii++ )
// foreach point in the polygon
bool first = true;
while( booleng->PolygonHasMorePoints() )
{
int x = (int) curr_vertex->X();
int y = (int) curr_vertex->Y();
msg.Printf(wxT("ii = %d, pts = %d,%d, wid = %d"), ii , x, y, curr_vertex->id());
wxMessageBox(msg);
if( ii==0 )
int x = booleng->GetPolygonXPoint();
int y = booleng->GetPolygonYPoint();
if( first )
{
area_ref->m_Poly->Start( area_ref->GetLayer(
), x, y, area_ref->m_Poly->GetHatchStyle() );
first = false;
area_to_combine->m_Poly->Start( area_ref->GetLayer(
), x, y, area_ref->m_Poly->GetHatchStyle() );
}
else
area_ref->m_Poly->AppendCorner( x, y );
curr_vertex = curr_vertex->Next();
// if( curr_vertex->id() == union_polygon->getFirst()->id() ) break;
area_to_combine->m_Poly->AppendCorner( x, y );
}
area_ref->m_Poly->Close();
booleng->EndPolygonGet();
area_to_combine->m_Poly->Close();
}
}
#endif
// add holes
#if 0
for( int ic = 0; ic<union_gpc->num_contours; ic++ )
while( booleng->StartPolygonGet() )
{
if( (union_gpc->hole)[ic] )
if( booleng->GetPolygonPointEdgeType() != KB_INSIDE_EDGE )
{
// hole
for( int i = 0; i<union_gpc->contour[ic].num_vertices; i++ )
{
int x = (int) ( (union_gpc->contour)[ic].vertex )[i].x;
int y = (int) ( (union_gpc->contour)[ic].vertex )[i].y;
area_ref->m_Poly->AppendCorner( x, y );
}
area_ref->m_Poly->Close();
DisplayError( NULL,
wxT( "BOARD::CombineAreas() error: unexpected outside contour descriptor" ) );
continue;
}
while( booleng->PolygonHasMorePoints() )
{
int x = booleng->GetPolygonXPoint();
int y = booleng->GetPolygonYPoint();
area_ref->m_Poly->AppendCorner( x, y );
}
area_ref->m_Poly->Close();
booleng->EndPolygonGet();
}
#endif
if( !keep_area_to_combine )
RemoveArea( area_to_combine );
area_ref->utility = 1;
area_ref->m_Poly->RestoreArcs( &arc_array1 );
area_ref->m_Poly->RestoreArcs( &arc_array2 );
area_ref->m_Poly->Draw();
delete union_polygon;
return 0;
#endif
delete booleng;
return 1;
}
......@@ -1098,31 +1024,32 @@ int BOARD::Test_Drc_Areas_Outlines_To_Areas_Outlines( ZONE_CONTAINER* aArea_To_E
* @return bool - false if DRC error or true if OK
*/
bool DRC::doEdgeZoneDrc( ZONE_CONTAINER * aArea, int aCornerIndex )
bool DRC::doEdgeZoneDrc( ZONE_CONTAINER* aArea, int aCornerIndex )
{
wxString str;
wxPoint start = aArea->GetCornerPosition(aCornerIndex);
wxPoint end;
// Search the end point of the edge starting at aCornerIndex
if( aArea->m_Poly->corner[aCornerIndex].end_contour == FALSE &&
aCornerIndex < (aArea->GetNumCorners() - 1) )
{
end = aArea->GetCornerPosition(aCornerIndex+1);
}
else // aCornerIndex is the last corner of an outline.
// the corresponding end point of the segment is the first corner of the outline
{
int ii = aCornerIndex-1;
end = aArea->GetCornerPosition(ii);
while ( ii >= 0 )
{
if ( aArea->m_Poly->corner[ii].end_contour )
break;
end = aArea->GetCornerPosition(ii);
ii--;
}
}
wxPoint start = aArea->GetCornerPosition( aCornerIndex );
wxPoint end;
// Search the end point of the edge starting at aCornerIndex
if( aArea->m_Poly->corner[aCornerIndex].end_contour == FALSE
&& aCornerIndex < (aArea->GetNumCorners() - 1) )
{
end = aArea->GetCornerPosition( aCornerIndex + 1 );
}
else // aCornerIndex is the last corner of an outline.
// the corresponding end point of the segment is the first corner of the outline
{
int ii = aCornerIndex - 1;
end = aArea->GetCornerPosition( ii );
while( ii >= 0 )
{
if( aArea->m_Poly->corner[ii].end_contour )
break;
end = aArea->GetCornerPosition( ii );
ii--;
}
}
// iterate through all areas
for( int ia2 = 0; ia2 < m_pcb->GetAreaCount(); ia2++ )
......@@ -1134,7 +1061,7 @@ bool DRC::doEdgeZoneDrc( ZONE_CONTAINER * aArea, int aCornerIndex )
continue;
// Test for same net
if( (aArea->GetNet() == Area_To_Test->GetNet()) && (aArea->GetNet() > 0) )
if( ( aArea->GetNet() == Area_To_Test->GetNet() ) && (aArea->GetNet() > 0) )
continue;
// test for ending line inside Area_To_Test
......@@ -1188,11 +1115,11 @@ bool DRC::doEdgeZoneDrc( ZONE_CONTAINER * aArea, int aCornerIndex )
m_currentMarker = fillMarker( aArea, wxPoint( x, y ),
COPPERAREA_CLOSE_TO_COPPERAREA,
m_currentMarker );
return false;
return false;
}
}
}
}
return true;
return true;
}
set(POLYGON_SRCS
GenericPolygonClipperLibrary.cpp
math_for_graphics.cpp
php_polygon.cpp
php_polygon_vertex.cpp
PolyLine.cpp)
add_library(polygon ${POLYGON_SRCS})
/*
===========================================================================
Project: Generic Polygon Clipper
A new algorithm for calculating the difference, intersection,
exclusive-or or union of arbitrary polygon sets.
File: gpc.c
Author: Alan Murta (email: gpc@cs.man.ac.uk)
Version: 2.32
Date: 17th December 2004
Copyright: (C) Advanced Interfaces Group,
University of Manchester.
This software is free for non-commercial use. It may be copied,
modified, and redistributed provided that this copyright notice
is preserved on all copies. The intellectual property rights of
the algorithms used reside with the University of Manchester
Advanced Interfaces Group.
You may not use this software, in whole or in part, in support
of any commercial product without the express consent of the
author.
There is no warranty or other guarantee of fitness of this
software for any purpose. It is provided solely "as is".
===========================================================================
*/
/*
===========================================================================
Includes
===========================================================================
*/
#include "GenericPolygonClipperLibrary.h"
#include <stdlib.h>
#include <float.h>
#include <math.h>
/*
===========================================================================
Constants
===========================================================================
*/
#ifndef TRUE
#define FALSE 0
#define TRUE 1
#endif
#define LEFT 0
#define RIGHT 1
#define ABOVE 0
#define BELOW 1
#define CLIP 0
#define SUBJ 1
#define INVERT_TRISTRIPS FALSE
/*
===========================================================================
Macros
===========================================================================
*/
#define EQ(a, b) (fabs((a) - (b)) <= GPC_EPSILON)
#define PREV_INDEX(i, n) ((i - 1 + n) % n)
#define NEXT_INDEX(i, n) ((i + 1 ) % n)
#define OPTIMAL(v, i, n) ((v[PREV_INDEX(i, n)].y != v[i].y) || \
(v[NEXT_INDEX(i, n)].y != v[i].y))
#define FWD_MIN(v, i, n) ((v[PREV_INDEX(i, n)].vertex.y >= v[i].vertex.y) \
&& (v[NEXT_INDEX(i, n)].vertex.y > v[i].vertex.y))
#define NOT_FMAX(v, i, n) (v[NEXT_INDEX(i, n)].vertex.y > v[i].vertex.y)
#define REV_MIN(v, i, n) ((v[PREV_INDEX(i, n)].vertex.y > v[i].vertex.y) \
&& (v[NEXT_INDEX(i, n)].vertex.y >= v[i].vertex.y))
#define NOT_RMAX(v, i, n) (v[PREV_INDEX(i, n)].vertex.y > v[i].vertex.y)
#define VERTEX(e,p,s,x,y) {add_vertex(&((e)->outp[(p)]->v[(s)]), x, y); \
(e)->outp[(p)]->active++;}
#define P_EDGE(d,e,p,i,j) {(d)= (e); \
do {(d)= (d)->prev;} while (!(d)->outp[(p)]); \
(i)= (d)->bot.x + (d)->dx * ((j)-(d)->bot.y);}
#define N_EDGE(d,e,p,i,j) {(d)= (e); \
do {(d)= (d)->next;} while (!(d)->outp[(p)]); \
(i)= (d)->bot.x + (d)->dx * ((j)-(d)->bot.y);}
#define MALLOC(p, b, s, t) {if ((b) > 0) { \
p= (t*)malloc(b); if (!(p)) { \
fprintf(stderr, "gpc malloc failure: %s\n", s); \
exit(0);}} else p= NULL;}
#define FREE(p) {if (p) {free(p); (p)= NULL;}}
/*
===========================================================================
Private Data Types
===========================================================================
*/
typedef enum /* Edge intersection classes */
{
NUL, /* Empty non-intersection */
EMX, /* External maximum */
ELI, /* External left intermediate */
TED, /* Top edge */
ERI, /* External right intermediate */
RED, /* Right edge */
IMM, /* Internal maximum and minimum */
IMN, /* Internal minimum */
EMN, /* External minimum */
EMM, /* External maximum and minimum */
LED, /* Left edge */
ILI, /* Internal left intermediate */
BED, /* Bottom edge */
IRI, /* Internal right intermediate */
IMX, /* Internal maximum */
FUL /* Full non-intersection */
} vertex_type;
typedef enum /* Horizontal edge states */
{
NH, /* No horizontal edge */
BH, /* Bottom horizontal edge */
TH /* Top horizontal edge */
} h_state;
typedef enum /* Edge bundle state */
{
UNBUNDLED, /* Isolated edge not within a bundle */
BUNDLE_HEAD, /* Bundle head node */
BUNDLE_TAIL /* Passive bundle tail node */
} bundle_state;
typedef struct v_shape /* Internal vertex list datatype */
{
double x; /* X coordinate component */
double y; /* Y coordinate component */
struct v_shape *next; /* Pointer to next vertex in list */
} vertex_node;
typedef struct p_shape /* Internal contour / tristrip type */
{
int active; /* Active flag / vertex count */
int hole; /* Hole / external contour flag */
vertex_node *v[2]; /* Left and right vertex list ptrs */
struct p_shape *next; /* Pointer to next polygon contour */
struct p_shape *proxy; /* Pointer to actual structure used */
} polygon_node;
typedef struct edge_shape
{
gpc_vertex vertex; /* Piggy-backed contour vertex data */
gpc_vertex bot; /* Edge lower (x, y) coordinate */
gpc_vertex top; /* Edge upper (x, y) coordinate */
double xb; /* Scanbeam bottom x coordinate */
double xt; /* Scanbeam top x coordinate */
double dx; /* Change in x for a unit y increase */
int type; /* Clip / subject edge flag */
int bundle[2][2]; /* Bundle edge flags */
int bside[2]; /* Bundle left / right indicators */
bundle_state bstate[2]; /* Edge bundle state */
polygon_node *outp[2]; /* Output polygon / tristrip pointer */
struct edge_shape *prev; /* Previous edge in the AET */
struct edge_shape *next; /* Next edge in the AET */
struct edge_shape *pred; /* Edge connected at the lower end */
struct edge_shape *succ; /* Edge connected at the upper end */
struct edge_shape *next_bound; /* Pointer to next bound in LMT */
} edge_node;
typedef struct lmt_shape /* Local minima table */
{
double y; /* Y coordinate at local minimum */
edge_node *first_bound; /* Pointer to bound list */
struct lmt_shape *next; /* Pointer to next local minimum */
} lmt_node;
typedef struct sbt_t_shape /* Scanbeam tree */
{
double y; /* Scanbeam node y value */
struct sbt_t_shape *less; /* Pointer to nodes with lower y */
struct sbt_t_shape *more; /* Pointer to nodes with higher y */
} sb_tree;
typedef struct it_shape /* Intersection table */
{
edge_node *ie[2]; /* Intersecting edge (bundle) pair */
gpc_vertex point; /* Point of intersection */
struct it_shape *next; /* The next intersection table node */
} it_node;
typedef struct st_shape /* Sorted edge table */
{
edge_node *edge; /* Pointer to AET edge */
double xb; /* Scanbeam bottom x coordinate */
double xt; /* Scanbeam top x coordinate */
double dx; /* Change in x for a unit y increase */
struct st_shape *prev; /* Previous edge in sorted list */
} st_node;
typedef struct bbox_shape /* Contour axis-aligned bounding box */
{
double xmin; /* Minimum x coordinate */
double ymin; /* Minimum y coordinate */
double xmax; /* Maximum x coordinate */
double ymax; /* Maximum y coordinate */
} bbox;
/*
===========================================================================
Global Data
===========================================================================
*/
/* Horizontal edge state transitions within scanbeam boundary */
const h_state next_h_state[3][6]=
{
/* ABOVE BELOW CROSS */
/* L R L R L R */
/* NH */ {BH, TH, TH, BH, NH, NH},
/* BH */ {NH, NH, NH, NH, TH, TH},
/* TH */ {NH, NH, NH, NH, BH, BH}
};
/*
===========================================================================
Private Functions
===========================================================================
*/
static void reset_it(it_node **it)
{
it_node *itn;
while (*it)
{
itn= (*it)->next;
FREE(*it);
*it= itn;
}
}
static void reset_lmt(lmt_node **lmt)
{
lmt_node *lmtn;
while (*lmt)
{
lmtn= (*lmt)->next;
FREE(*lmt);
*lmt= lmtn;
}
}
static void insert_bound(edge_node **b, edge_node *e)
{
edge_node *existing_bound;
if (!*b)
{
/* Link node e to the tail of the list */
*b= e;
}
else
{
/* Do primary sort on the x field */
if (e[0].bot.x < (*b)[0].bot.x)
{
/* Insert a new node mid-list */
existing_bound= *b;
*b= e;
(*b)->next_bound= existing_bound;
}
else
{
if (e[0].bot.x == (*b)[0].bot.x)
{
/* Do secondary sort on the dx field */
if (e[0].dx < (*b)[0].dx)
{
/* Insert a new node mid-list */
existing_bound= *b;
*b= e;
(*b)->next_bound= existing_bound;
}
else
{
/* Head further down the list */
insert_bound(&((*b)->next_bound), e);
}
}
else
{
/* Head further down the list */
insert_bound(&((*b)->next_bound), e);
}
}
}
}
static edge_node **bound_list(lmt_node **lmt, double y)
{
lmt_node *existing_node;
if (!*lmt)
{
/* Add node onto the tail end of the LMT */
MALLOC(*lmt, sizeof(lmt_node), "LMT insertion", lmt_node);
(*lmt)->y= y;
(*lmt)->first_bound= NULL;
(*lmt)->next= NULL;
return &((*lmt)->first_bound);
}
else
if (y < (*lmt)->y)
{
/* Insert a new LMT node before the current node */
existing_node= *lmt;
MALLOC(*lmt, sizeof(lmt_node), "LMT insertion", lmt_node);
(*lmt)->y= y;
(*lmt)->first_bound= NULL;
(*lmt)->next= existing_node;
return &((*lmt)->first_bound);
}
else
if (y > (*lmt)->y)
/* Head further up the LMT */
return bound_list(&((*lmt)->next), y);
else
/* Use this existing LMT node */
return &((*lmt)->first_bound);
}
static void add_to_sbtree(int *entries, sb_tree **sbtree, double y)
{
if (!*sbtree)
{
/* Add a new tree node here */
MALLOC(*sbtree, sizeof(sb_tree), "scanbeam tree insertion", sb_tree);
(*sbtree)->y= y;
(*sbtree)->less= NULL;
(*sbtree)->more= NULL;
(*entries)++;
}
else
{
if ((*sbtree)->y > y)
{
/* Head into the 'less' sub-tree */
add_to_sbtree(entries, &((*sbtree)->less), y);
}
else
{
if ((*sbtree)->y < y)
{
/* Head into the 'more' sub-tree */
add_to_sbtree(entries, &((*sbtree)->more), y);
}
}
}
}
static void build_sbt(int *entries, double *sbt, sb_tree *sbtree)
{
if (sbtree->less)
build_sbt(entries, sbt, sbtree->less);
sbt[*entries]= sbtree->y;
(*entries)++;
if (sbtree->more)
build_sbt(entries, sbt, sbtree->more);
}
static void free_sbtree(sb_tree **sbtree)
{
if (*sbtree)
{
free_sbtree(&((*sbtree)->less));
free_sbtree(&((*sbtree)->more));
FREE(*sbtree);
}
}
static int count_optimal_vertices(gpc_vertex_list c)
{
int result= 0, i;
/* Ignore non-contributing contours */
if (c.num_vertices > 0)
{
for (i= 0; i < c.num_vertices; i++)
/* Ignore superfluous vertices embedded in horizontal edges */
if (OPTIMAL(c.vertex, i, c.num_vertices))
result++;
}
return result;
}
static edge_node *build_lmt(lmt_node **lmt, sb_tree **sbtree,
int *sbt_entries, gpc_polygon *p, int type,
gpc_op op)
{
int c, i, min, max, num_edges, v, num_vertices;
int total_vertices= 0, e_index=0;
edge_node *e, *edge_table;
for (c= 0; c < p->num_contours; c++)
total_vertices+= count_optimal_vertices(p->contour[c]);
/* Create the entire input polygon edge table in one go */
MALLOC(edge_table, total_vertices * sizeof(edge_node),
"edge table creation", edge_node);
for (c= 0; c < p->num_contours; c++)
{
if (p->contour[c].num_vertices < 0)
{
/* Ignore the non-contributing contour and repair the vertex count */
p->contour[c].num_vertices= -p->contour[c].num_vertices;
}
else
{
/* Perform contour optimisation */
num_vertices= 0;
for (i= 0; i < p->contour[c].num_vertices; i++)
if (OPTIMAL(p->contour[c].vertex, i, p->contour[c].num_vertices))
{
edge_table[num_vertices].vertex.x= p->contour[c].vertex[i].x;
edge_table[num_vertices].vertex.y= p->contour[c].vertex[i].y;
/* Record vertex in the scanbeam table */
add_to_sbtree(sbt_entries, sbtree,
edge_table[num_vertices].vertex.y);
num_vertices++;
}
/* Do the contour forward pass */
for (min= 0; min < num_vertices; min++)
{
/* If a forward local minimum... */
if (FWD_MIN(edge_table, min, num_vertices))
{
/* Search for the next local maximum... */
num_edges= 1;
max= NEXT_INDEX(min, num_vertices);
while (NOT_FMAX(edge_table, max, num_vertices))
{
num_edges++;
max= NEXT_INDEX(max, num_vertices);
}
/* Build the next edge list */
e= &edge_table[e_index];
e_index+= num_edges;
v= min;
e[0].bstate[BELOW]= UNBUNDLED;
e[0].bundle[BELOW][CLIP]= FALSE;
e[0].bundle[BELOW][SUBJ]= FALSE;
for (i= 0; i < num_edges; i++)
{
e[i].xb= edge_table[v].vertex.x;
e[i].bot.x= edge_table[v].vertex.x;
e[i].bot.y= edge_table[v].vertex.y;
v= NEXT_INDEX(v, num_vertices);
e[i].top.x= edge_table[v].vertex.x;
e[i].top.y= edge_table[v].vertex.y;
e[i].dx= (edge_table[v].vertex.x - e[i].bot.x) /
(e[i].top.y - e[i].bot.y);
e[i].type= type;
e[i].outp[ABOVE]= NULL;
e[i].outp[BELOW]= NULL;
e[i].next= NULL;
e[i].prev= NULL;
e[i].succ= ((num_edges > 1) && (i < (num_edges - 1))) ?
&(e[i + 1]) : NULL;
e[i].pred= ((num_edges > 1) && (i > 0)) ? &(e[i - 1]) : NULL;
e[i].next_bound= NULL;
e[i].bside[CLIP]= (op == GPC_DIFF) ? RIGHT : LEFT;
e[i].bside[SUBJ]= LEFT;
}
insert_bound(bound_list(lmt, edge_table[min].vertex.y), e);
}
}
/* Do the contour reverse pass */
for (min= 0; min < num_vertices; min++)
{
/* If a reverse local minimum... */
if (REV_MIN(edge_table, min, num_vertices))
{
/* Search for the previous local maximum... */
num_edges= 1;
max= PREV_INDEX(min, num_vertices);
while (NOT_RMAX(edge_table, max, num_vertices))
{
num_edges++;
max= PREV_INDEX(max, num_vertices);
}
/* Build the previous edge list */
e= &edge_table[e_index];
e_index+= num_edges;
v= min;
e[0].bstate[BELOW]= UNBUNDLED;
e[0].bundle[BELOW][CLIP]= FALSE;
e[0].bundle[BELOW][SUBJ]= FALSE;
for (i= 0; i < num_edges; i++)
{
e[i].xb= edge_table[v].vertex.x;
e[i].bot.x= edge_table[v].vertex.x;
e[i].bot.y= edge_table[v].vertex.y;
v= PREV_INDEX(v, num_vertices);
e[i].top.x= edge_table[v].vertex.x;
e[i].top.y= edge_table[v].vertex.y;
e[i].dx= (edge_table[v].vertex.x - e[i].bot.x) /
(e[i].top.y - e[i].bot.y);
e[i].type= type;
e[i].outp[ABOVE]= NULL;
e[i].outp[BELOW]= NULL;
e[i].next= NULL;
e[i].prev= NULL;
e[i].succ= ((num_edges > 1) && (i < (num_edges - 1))) ?
&(e[i + 1]) : NULL;
e[i].pred= ((num_edges > 1) && (i > 0)) ? &(e[i - 1]) : NULL;
e[i].next_bound= NULL;
e[i].bside[CLIP]= (op == GPC_DIFF) ? RIGHT : LEFT;
e[i].bside[SUBJ]= LEFT;
}
insert_bound(bound_list(lmt, edge_table[min].vertex.y), e);
}
}
}
}
return edge_table;
}
static void add_edge_to_aet(edge_node **aet, edge_node *edge, edge_node *prev)
{
if (!*aet)
{
/* Append edge onto the tail end of the AET */
*aet= edge;
edge->prev= prev;
edge->next= NULL;
}
else
{
/* Do primary sort on the xb field */
if (edge->xb < (*aet)->xb)
{
/* Insert edge here (before the AET edge) */
edge->prev= prev;
edge->next= *aet;
(*aet)->prev= edge;
*aet= edge;
}
else
{
if (edge->xb == (*aet)->xb)
{
/* Do secondary sort on the dx field */
if (edge->dx < (*aet)->dx)
{
/* Insert edge here (before the AET edge) */
edge->prev= prev;
edge->next= *aet;
(*aet)->prev= edge;
*aet= edge;
}
else
{
/* Head further into the AET */
add_edge_to_aet(&((*aet)->next), edge, *aet);
}
}
else
{
/* Head further into the AET */
add_edge_to_aet(&((*aet)->next), edge, *aet);
}
}
}
}
static void add_intersection(it_node **it, edge_node *edge0, edge_node *edge1,
double x, double y)
{
it_node *existing_node;
if (!*it)
{
/* Append a new node to the tail of the list */
MALLOC(*it, sizeof(it_node), "IT insertion", it_node);
(*it)->ie[0]= edge0;
(*it)->ie[1]= edge1;
(*it)->point.x= x;
(*it)->point.y= y;
(*it)->next= NULL;
}
else
{
if ((*it)->point.y > y)
{
/* Insert a new node mid-list */
existing_node= *it;
MALLOC(*it, sizeof(it_node), "IT insertion", it_node);
(*it)->ie[0]= edge0;
(*it)->ie[1]= edge1;
(*it)->point.x= x;
(*it)->point.y= y;
(*it)->next= existing_node;
}
else
/* Head further down the list */
add_intersection(&((*it)->next), edge0, edge1, x, y);
}
}
static void add_st_edge(st_node **st, it_node **it, edge_node *edge,
double dy)
{
st_node *existing_node;
double den, r, x, y;
if (!*st)
{
/* Append edge onto the tail end of the ST */
MALLOC(*st, sizeof(st_node), "ST insertion", st_node);
(*st)->edge= edge;
(*st)->xb= edge->xb;
(*st)->xt= edge->xt;
(*st)->dx= edge->dx;
(*st)->prev= NULL;
}
else
{
den= ((*st)->xt - (*st)->xb) - (edge->xt - edge->xb);
/* If new edge and ST edge don't cross */
if ((edge->xt >= (*st)->xt) || (edge->dx == (*st)->dx) ||
(fabs(den) <= DBL_EPSILON))
{
/* No intersection - insert edge here (before the ST edge) */
existing_node= *st;
MALLOC(*st, sizeof(st_node), "ST insertion", st_node);
(*st)->edge= edge;
(*st)->xb= edge->xb;
(*st)->xt= edge->xt;
(*st)->dx= edge->dx;
(*st)->prev= existing_node;
}
else
{
/* Compute intersection between new edge and ST edge */
r= (edge->xb - (*st)->xb) / den;
x= (*st)->xb + r * ((*st)->xt - (*st)->xb);
y= r * dy;
/* Insert the edge pointers and the intersection point in the IT */
add_intersection(it, (*st)->edge, edge, x, y);
/* Head further into the ST */
add_st_edge(&((*st)->prev), it, edge, dy);
}
}
}
static void build_intersection_table(it_node **it, edge_node *aet, double dy)
{
st_node *st, *stp;
edge_node *edge;
/* Build intersection table for the current scanbeam */
reset_it(it);
st= NULL;
/* Process each AET edge */
for (edge= aet; edge; edge= edge->next)
{
if ((edge->bstate[ABOVE] == BUNDLE_HEAD) ||
edge->bundle[ABOVE][CLIP] || edge->bundle[ABOVE][SUBJ])
add_st_edge(&st, it, edge, dy);
}
/* Free the sorted edge table */
while (st)
{
stp= st->prev;
FREE(st);
st= stp;
}
}
static int count_contours(polygon_node *polygon)
{
int nc, nv;
vertex_node *v, *nextv;
for (nc= 0; polygon; polygon= polygon->next)
if (polygon->active)
{
/* Count the vertices in the current contour */
nv= 0;
for (v= polygon->proxy->v[LEFT]; v; v= v->next)
nv++;
/* Record valid vertex counts in the active field */
if (nv > 2)
{
polygon->active= nv;
nc++;
}
else
{
/* Invalid contour: just free the heap */
for (v= polygon->proxy->v[LEFT]; v; v= nextv)
{
nextv= v->next;
FREE(v);
}
polygon->active= 0;
}
}
return nc;
}
static void add_left(polygon_node *p, double x, double y)
{
vertex_node *nv;
/* Create a new vertex node and set its fields */
MALLOC(nv, sizeof(vertex_node), "vertex node creation", vertex_node);
nv->x= x;
nv->y= y;
/* Add vertex nv to the left end of the polygon's vertex list */
nv->next= p->proxy->v[LEFT];
/* Update proxy->[LEFT] to point to nv */
p->proxy->v[LEFT]= nv;
}
static void merge_left(polygon_node *p, polygon_node *q, polygon_node *list)
{
polygon_node *target;
/* Label contour as a hole */
q->proxy->hole= TRUE;
if (p->proxy != q->proxy)
{
/* Assign p's vertex list to the left end of q's list */
p->proxy->v[RIGHT]->next= q->proxy->v[LEFT];
q->proxy->v[LEFT]= p->proxy->v[LEFT];
/* Redirect any p->proxy references to q->proxy */
for (target= p->proxy; list; list= list->next)
{
if (list->proxy == target)
{
list->active= FALSE;
list->proxy= q->proxy;
}
}
}
}
static void add_right(polygon_node *p, double x, double y)
{
vertex_node *nv;
/* Create a new vertex node and set its fields */
MALLOC(nv, sizeof(vertex_node), "vertex node creation", vertex_node);
nv->x= x;
nv->y= y;
nv->next= NULL;
/* Add vertex nv to the right end of the polygon's vertex list */
p->proxy->v[RIGHT]->next= nv;
/* Update proxy->v[RIGHT] to point to nv */
p->proxy->v[RIGHT]= nv;
}
static void merge_right(polygon_node *p, polygon_node *q, polygon_node *list)
{
polygon_node *target;
/* Label contour as external */
q->proxy->hole= FALSE;
if (p->proxy != q->proxy)
{
/* Assign p's vertex list to the right end of q's list */
q->proxy->v[RIGHT]->next= p->proxy->v[LEFT];
q->proxy->v[RIGHT]= p->proxy->v[RIGHT];
/* Redirect any p->proxy references to q->proxy */
for (target= p->proxy; list; list= list->next)
{
if (list->proxy == target)
{
list->active= FALSE;
list->proxy= q->proxy;
}
}
}
}
static void add_local_min(polygon_node **p, edge_node *edge,
double x, double y)
{
polygon_node *existing_min;
vertex_node *nv;
existing_min= *p;
MALLOC(*p, sizeof(polygon_node), "polygon node creation", polygon_node);
/* Create a new vertex node and set its fields */
MALLOC(nv, sizeof(vertex_node), "vertex node creation", vertex_node);
nv->x= x;
nv->y= y;
nv->next= NULL;
/* Initialise proxy to point to p itself */
(*p)->proxy= (*p);
(*p)->active= TRUE;
(*p)->next= existing_min;
/* Make v[LEFT] and v[RIGHT] point to new vertex nv */
(*p)->v[LEFT]= nv;
(*p)->v[RIGHT]= nv;
/* Assign polygon p to the edge */
edge->outp[ABOVE]= *p;
}
static int count_tristrips(polygon_node *tn)
{
int total;
for (total= 0; tn; tn= tn->next)
if (tn->active > 2)
total++;
return total;
}
static void add_vertex(vertex_node **t, double x, double y)
{
if (!(*t))
{
MALLOC(*t, sizeof(vertex_node), "tristrip vertex creation", vertex_node);
(*t)->x= x;
(*t)->y= y;
(*t)->next= NULL;
}
else
/* Head further down the list */
add_vertex(&((*t)->next), x, y);
}
static void new_tristrip(polygon_node **tn, edge_node *edge,
double x, double y)
{
if (!(*tn))
{
MALLOC(*tn, sizeof(polygon_node), "tristrip node creation", polygon_node);
(*tn)->next= NULL;
(*tn)->v[LEFT]= NULL;
(*tn)->v[RIGHT]= NULL;
(*tn)->active= 1;
add_vertex(&((*tn)->v[LEFT]), x, y);
edge->outp[ABOVE]= *tn;
}
else
/* Head further down the list */
new_tristrip(&((*tn)->next), edge, x, y);
}
static bbox *create_contour_bboxes(gpc_polygon *p)
{
bbox *box;
int c, v;
MALLOC(box, p->num_contours * sizeof(bbox), "Bounding box creation", bbox);
/* Construct contour bounding boxes */
for (c= 0; c < p->num_contours; c++)
{
/* Initialise bounding box extent */
box[c].xmin= DBL_MAX;
box[c].ymin= DBL_MAX;
box[c].xmax= -DBL_MAX;
box[c].ymax= -DBL_MAX;
for (v= 0; v < p->contour[c].num_vertices; v++)
{
/* Adjust bounding box */
if (p->contour[c].vertex[v].x < box[c].xmin)
box[c].xmin= p->contour[c].vertex[v].x;
if (p->contour[c].vertex[v].y < box[c].ymin)
box[c].ymin= p->contour[c].vertex[v].y;
if (p->contour[c].vertex[v].x > box[c].xmax)
box[c].xmax= p->contour[c].vertex[v].x;
if (p->contour[c].vertex[v].y > box[c].ymax)
box[c].ymax= p->contour[c].vertex[v].y;
}
}
return box;
}
static void minimax_test(gpc_polygon *subj, gpc_polygon *clip, gpc_op op)
{
bbox *s_bbox, *c_bbox;
int s, c, *o_table, overlap;
s_bbox= create_contour_bboxes(subj);
c_bbox= create_contour_bboxes(clip);
MALLOC(o_table, subj->num_contours * clip->num_contours * sizeof(int),
"overlap table creation", int);
/* Check all subject contour bounding boxes against clip boxes */
for (s= 0; s < subj->num_contours; s++)
for (c= 0; c < clip->num_contours; c++)
o_table[c * subj->num_contours + s]=
(!((s_bbox[s].xmax < c_bbox[c].xmin) ||
(s_bbox[s].xmin > c_bbox[c].xmax))) &&
(!((s_bbox[s].ymax < c_bbox[c].ymin) ||
(s_bbox[s].ymin > c_bbox[c].ymax)));
/* For each clip contour, search for any subject contour overlaps */
for (c= 0; c < clip->num_contours; c++)
{
overlap= 0;
for (s= 0; (!overlap) && (s < subj->num_contours); s++)
overlap= o_table[c * subj->num_contours + s];
if (!overlap)
/* Flag non contributing status by negating vertex count */
clip->contour[c].num_vertices = -clip->contour[c].num_vertices;
}
if (op == GPC_INT)
{
/* For each subject contour, search for any clip contour overlaps */
for (s= 0; s < subj->num_contours; s++)
{
overlap= 0;
for (c= 0; (!overlap) && (c < clip->num_contours); c++)
overlap= o_table[c * subj->num_contours + s];
if (!overlap)
/* Flag non contributing status by negating vertex count */
subj->contour[s].num_vertices = -subj->contour[s].num_vertices;
}
}
FREE(s_bbox);
FREE(c_bbox);
FREE(o_table);
}
/*
===========================================================================
Public Functions
===========================================================================
*/
void gpc_free_polygon(gpc_polygon *p)
{
int c;
for (c= 0; c < p->num_contours; c++)
FREE(p->contour[c].vertex);
FREE(p->hole);
FREE(p->contour);
p->num_contours= 0;
}
void gpc_read_polygon(FILE *fp, int read_hole_flags, gpc_polygon *p)
{
int c, v;
fscanf(fp, "%d", &(p->num_contours));
MALLOC(p->hole, p->num_contours * sizeof(int),
"hole flag array creation", int);
MALLOC(p->contour, p->num_contours
* sizeof(gpc_vertex_list), "contour creation", gpc_vertex_list);
for (c= 0; c < p->num_contours; c++)
{
fscanf(fp, "%d", &(p->contour[c].num_vertices));
if (read_hole_flags)
fscanf(fp, "%d", &(p->hole[c]));
else
p->hole[c]= FALSE; /* Assume all contours to be external */
MALLOC(p->contour[c].vertex, p->contour[c].num_vertices
* sizeof(gpc_vertex), "vertex creation", gpc_vertex);
for (v= 0; v < p->contour[c].num_vertices; v++)
fscanf(fp, "%lf %lf", &(p->contour[c].vertex[v].x),
&(p->contour[c].vertex[v].y));
}
}
void gpc_write_polygon(FILE *fp, int write_hole_flags, gpc_polygon *p)
{
int c, v;
fprintf(fp, "%d\n", p->num_contours);
for (c= 0; c < p->num_contours; c++)
{
fprintf(fp, "%d\n", p->contour[c].num_vertices);
if (write_hole_flags)
fprintf(fp, "%d\n", p->hole[c]);
for (v= 0; v < p->contour[c].num_vertices; v++)
fprintf(fp, "% .*lf % .*lf\n",
DBL_DIG, p->contour[c].vertex[v].x,
DBL_DIG, p->contour[c].vertex[v].y);
}
}
void gpc_add_contour(gpc_polygon *p, gpc_vertex_list *new_contour, int hole)
{
int *extended_hole, c, v;
gpc_vertex_list *extended_contour;
/* Create an extended hole array */
MALLOC(extended_hole, (p->num_contours + 1)
* sizeof(int), "contour hole addition", int);
/* Create an extended contour array */
MALLOC(extended_contour, (p->num_contours + 1)
* sizeof(gpc_vertex_list), "contour addition", gpc_vertex_list);
/* Copy the old contour and hole data into the extended arrays */
for (c= 0; c < p->num_contours; c++)
{
extended_hole[c]= p->hole[c];
extended_contour[c]= p->contour[c];
}
/* Copy the new contour and hole onto the end of the extended arrays */
c= p->num_contours;
extended_hole[c]= hole;
extended_contour[c].num_vertices= new_contour->num_vertices;
MALLOC(extended_contour[c].vertex, new_contour->num_vertices
* sizeof(gpc_vertex), "contour addition", gpc_vertex);
for (v= 0; v < new_contour->num_vertices; v++)
extended_contour[c].vertex[v]= new_contour->vertex[v];
/* Dispose of the old contour */
FREE(p->contour);
FREE(p->hole);
/* Update the polygon information */
p->num_contours++;
p->hole= extended_hole;
p->contour= extended_contour;
}
void gpc_polygon_clip(gpc_op op, gpc_polygon *subj, gpc_polygon *clip,
gpc_polygon *result)
{
sb_tree *sbtree= NULL;
it_node *it= NULL, *intersect;
edge_node *edge, *prev_edge, *next_edge, *succ_edge, *e0, *e1;
edge_node *aet= NULL, *c_heap= NULL, *s_heap= NULL;
lmt_node *lmt= NULL, *local_min;
polygon_node *out_poly= NULL, *p, *q, *poly, *npoly, *cf= NULL;
vertex_node *vtx, *nv;
h_state horiz[2];
int in[2], exists[2], parity[2]= {LEFT, LEFT};
int c, v, contributing, search, scanbeam= 0, sbt_entries= 0;
int vclass, bl, br, tl, tr;
double *sbt= NULL, xb, px, yb, yt, dy, ix, iy;
contributing = bl = br = tl = tr = 0;
yt = dy = 0;
/* Test for trivial NULL result cases */
if (((subj->num_contours == 0) && (clip->num_contours == 0))
|| ((subj->num_contours == 0) && ((op == GPC_INT) || (op == GPC_DIFF)))
|| ((clip->num_contours == 0) && (op == GPC_INT)))
{
result->num_contours= 0;
result->hole= NULL;
result->contour= NULL;
return;
}
/* Identify potentialy contributing contours */
if (((op == GPC_INT) || (op == GPC_DIFF))
&& (subj->num_contours > 0) && (clip->num_contours > 0))
minimax_test(subj, clip, op);
/* Build LMT */
if (subj->num_contours > 0)
s_heap= build_lmt(&lmt, &sbtree, &sbt_entries, subj, SUBJ, op);
if (clip->num_contours > 0)
c_heap= build_lmt(&lmt, &sbtree, &sbt_entries, clip, CLIP, op);
/* Return a NULL result if no contours contribute */
if (lmt == NULL)
{
result->num_contours= 0;
result->hole= NULL;
result->contour= NULL;
reset_lmt(&lmt);
FREE(s_heap);
FREE(c_heap);
return;
}
/* Build scanbeam table from scanbeam tree */
MALLOC(sbt, sbt_entries * sizeof(double), "sbt creation", double);
build_sbt(&scanbeam, sbt, sbtree);
scanbeam= 0;
free_sbtree(&sbtree);
/* Allow pointer re-use without causing memory leak */
if (subj == result)
gpc_free_polygon(subj);
if (clip == result)
gpc_free_polygon(clip);
/* Invert clip polygon for difference operation */
if (op == GPC_DIFF)
parity[CLIP]= RIGHT;
local_min= lmt;
/* Process each scanbeam */
while (scanbeam < sbt_entries)
{
/* Set yb and yt to the bottom and top of the scanbeam */
yb= sbt[scanbeam++];
if (scanbeam < sbt_entries)
{
yt= sbt[scanbeam];
dy= yt - yb;
}
/* === SCANBEAM BOUNDARY PROCESSING ================================ */
/* If LMT node corresponding to yb exists */
if (local_min)
{
if (local_min->y == yb)
{
/* Add edges starting at this local minimum to the AET */
for (edge= local_min->first_bound; edge; edge= edge->next_bound)
add_edge_to_aet(&aet, edge, NULL);
local_min= local_min->next;
}
}
/* Set dummy previous x value */
px= -DBL_MAX;
/* Create bundles within AET */
e0= aet;
e1= aet;
/* Set up bundle fields of first edge */
aet->bundle[ABOVE][ aet->type]= (aet->top.y != yb);
aet->bundle[ABOVE][!aet->type]= FALSE;
aet->bstate[ABOVE]= UNBUNDLED;
for (next_edge= aet->next; next_edge; next_edge= next_edge->next)
{
/* Set up bundle fields of next edge */
next_edge->bundle[ABOVE][ next_edge->type]= (next_edge->top.y != yb);
next_edge->bundle[ABOVE][!next_edge->type]= FALSE;
next_edge->bstate[ABOVE]= UNBUNDLED;
/* Bundle edges above the scanbeam boundary if they coincide */
if (next_edge->bundle[ABOVE][next_edge->type])
{
if (EQ(e0->xb, next_edge->xb) && EQ(e0->dx, next_edge->dx)
&& (e0->top.y != yb))
{
next_edge->bundle[ABOVE][ next_edge->type]^=
e0->bundle[ABOVE][ next_edge->type];
next_edge->bundle[ABOVE][!next_edge->type]=
e0->bundle[ABOVE][!next_edge->type];
next_edge->bstate[ABOVE]= BUNDLE_HEAD;
e0->bundle[ABOVE][CLIP]= FALSE;
e0->bundle[ABOVE][SUBJ]= FALSE;
e0->bstate[ABOVE]= BUNDLE_TAIL;
}
e0= next_edge;
}
}
horiz[CLIP]= NH;
horiz[SUBJ]= NH;
/* Process each edge at this scanbeam boundary */
for (edge= aet; edge; edge= edge->next)
{
exists[CLIP]= edge->bundle[ABOVE][CLIP] +
(edge->bundle[BELOW][CLIP] << 1);
exists[SUBJ]= edge->bundle[ABOVE][SUBJ] +
(edge->bundle[BELOW][SUBJ] << 1);
if (exists[CLIP] || exists[SUBJ])
{
/* Set bundle side */
edge->bside[CLIP]= parity[CLIP];
edge->bside[SUBJ]= parity[SUBJ];
/* Determine contributing status and quadrant occupancies */
switch (op)
{
case GPC_DIFF:
case GPC_INT:
contributing= (exists[CLIP] && (parity[SUBJ] || horiz[SUBJ]))
|| (exists[SUBJ] && (parity[CLIP] || horiz[CLIP]))
|| (exists[CLIP] && exists[SUBJ]
&& (parity[CLIP] == parity[SUBJ]));
br= (parity[CLIP])
&& (parity[SUBJ]);
bl= (parity[CLIP] ^ edge->bundle[ABOVE][CLIP])
&& (parity[SUBJ] ^ edge->bundle[ABOVE][SUBJ]);
tr= (parity[CLIP] ^ (horiz[CLIP]!=NH))
&& (parity[SUBJ] ^ (horiz[SUBJ]!=NH));
tl= (parity[CLIP] ^ (horiz[CLIP]!=NH) ^ edge->bundle[BELOW][CLIP])
&& (parity[SUBJ] ^ (horiz[SUBJ]!=NH) ^ edge->bundle[BELOW][SUBJ]);
break;
case GPC_XOR:
contributing= exists[CLIP] || exists[SUBJ];
br= (parity[CLIP])
^ (parity[SUBJ]);
bl= (parity[CLIP] ^ edge->bundle[ABOVE][CLIP])
^ (parity[SUBJ] ^ edge->bundle[ABOVE][SUBJ]);
tr= (parity[CLIP] ^ (horiz[CLIP]!=NH))
^ (parity[SUBJ] ^ (horiz[SUBJ]!=NH));
tl= (parity[CLIP] ^ (horiz[CLIP]!=NH) ^ edge->bundle[BELOW][CLIP])
^ (parity[SUBJ] ^ (horiz[SUBJ]!=NH) ^ edge->bundle[BELOW][SUBJ]);
break;
case GPC_UNION:
contributing= (exists[CLIP] && (!parity[SUBJ] || horiz[SUBJ]))
|| (exists[SUBJ] && (!parity[CLIP] || horiz[CLIP]))
|| (exists[CLIP] && exists[SUBJ]
&& (parity[CLIP] == parity[SUBJ]));
br= (parity[CLIP])
|| (parity[SUBJ]);
bl= (parity[CLIP] ^ edge->bundle[ABOVE][CLIP])
|| (parity[SUBJ] ^ edge->bundle[ABOVE][SUBJ]);
tr= (parity[CLIP] ^ (horiz[CLIP]!=NH))
|| (parity[SUBJ] ^ (horiz[SUBJ]!=NH));
tl= (parity[CLIP] ^ (horiz[CLIP]!=NH) ^ edge->bundle[BELOW][CLIP])
|| (parity[SUBJ] ^ (horiz[SUBJ]!=NH) ^ edge->bundle[BELOW][SUBJ]);
break;
}
/* Update parity */
parity[CLIP]^= edge->bundle[ABOVE][CLIP];
parity[SUBJ]^= edge->bundle[ABOVE][SUBJ];
/* Update horizontal state */
if (exists[CLIP])
horiz[CLIP]=
next_h_state[horiz[CLIP]]
[((exists[CLIP] - 1) << 1) + parity[CLIP]];
if (exists[SUBJ])
horiz[SUBJ]=
next_h_state[horiz[SUBJ]]
[((exists[SUBJ] - 1) << 1) + parity[SUBJ]];
vclass= tr + (tl << 1) + (br << 2) + (bl << 3);
if (contributing)
{
xb= edge->xb;
switch (vclass)
{
case EMN:
case IMN:
add_local_min(&out_poly, edge, xb, yb);
px= xb;
cf= edge->outp[ABOVE];
break;
case ERI:
if (xb != px)
{
add_right(cf, xb, yb);
px= xb;
}
edge->outp[ABOVE]= cf;
cf= NULL;
break;
case ELI:
add_left(edge->outp[BELOW], xb, yb);
px= xb;
cf= edge->outp[BELOW];
break;
case EMX:
if (xb != px)
{
add_left(cf, xb, yb);
px= xb;
}
merge_right(cf, edge->outp[BELOW], out_poly);
cf= NULL;
break;
case ILI:
if (xb != px)
{
add_left(cf, xb, yb);
px= xb;
}
edge->outp[ABOVE]= cf;
cf= NULL;
break;
case IRI:
add_right(edge->outp[BELOW], xb, yb);
px= xb;
cf= edge->outp[BELOW];
edge->outp[BELOW]= NULL;
break;
case IMX:
if (xb != px)
{
add_right(cf, xb, yb);
px= xb;
}
merge_left(cf, edge->outp[BELOW], out_poly);
cf= NULL;
edge->outp[BELOW]= NULL;
break;
case IMM:
if (xb != px)
{
add_right(cf, xb, yb);
px= xb;
}
merge_left(cf, edge->outp[BELOW], out_poly);
edge->outp[BELOW]= NULL;
add_local_min(&out_poly, edge, xb, yb);
cf= edge->outp[ABOVE];
break;
case EMM:
if (xb != px)
{
add_left(cf, xb, yb);
px= xb;
}
merge_right(cf, edge->outp[BELOW], out_poly);
edge->outp[BELOW]= NULL;
add_local_min(&out_poly, edge, xb, yb);
cf= edge->outp[ABOVE];
break;
case LED:
if (edge->bot.y == yb)
add_left(edge->outp[BELOW], xb, yb);
edge->outp[ABOVE]= edge->outp[BELOW];
px= xb;
break;
case RED:
if (edge->bot.y == yb)
add_right(edge->outp[BELOW], xb, yb);
edge->outp[ABOVE]= edge->outp[BELOW];
px= xb;
break;
default:
break;
} /* End of switch */
} /* End of contributing conditional */
} /* End of edge exists conditional */
} /* End of AET loop */
/* Delete terminating edges from the AET, otherwise compute xt */
for (edge= aet; edge; edge= edge->next)
{
if (edge->top.y == yb)
{
prev_edge= edge->prev;
next_edge= edge->next;
if (prev_edge)
prev_edge->next= next_edge;
else
aet= next_edge;
if (next_edge)
next_edge->prev= prev_edge;
/* Copy bundle head state to the adjacent tail edge if required */
if ((edge->bstate[BELOW] == BUNDLE_HEAD) && prev_edge)
{
if (prev_edge->bstate[BELOW] == BUNDLE_TAIL)
{
prev_edge->outp[BELOW]= edge->outp[BELOW];
prev_edge->bstate[BELOW]= UNBUNDLED;
if (prev_edge->prev)
if (prev_edge->prev->bstate[BELOW] == BUNDLE_TAIL)
prev_edge->bstate[BELOW]= BUNDLE_HEAD;
}
}
}
else
{
if (edge->top.y == yt)
edge->xt= edge->top.x;
else
edge->xt= edge->bot.x + edge->dx * (yt - edge->bot.y);
}
}
if (scanbeam < sbt_entries)
{
/* === SCANBEAM INTERIOR PROCESSING ============================== */
build_intersection_table(&it, aet, dy);
/* Process each node in the intersection table */
for (intersect= it; intersect; intersect= intersect->next)
{
e0= intersect->ie[0];
e1= intersect->ie[1];
/* Only generate output for contributing intersections */
if ((e0->bundle[ABOVE][CLIP] || e0->bundle[ABOVE][SUBJ])
&& (e1->bundle[ABOVE][CLIP] || e1->bundle[ABOVE][SUBJ]))
{
p= e0->outp[ABOVE];
q= e1->outp[ABOVE];
ix= intersect->point.x;
iy= intersect->point.y + yb;
in[CLIP]= ( e0->bundle[ABOVE][CLIP] && !e0->bside[CLIP])
|| ( e1->bundle[ABOVE][CLIP] && e1->bside[CLIP])
|| (!e0->bundle[ABOVE][CLIP] && !e1->bundle[ABOVE][CLIP]
&& e0->bside[CLIP] && e1->bside[CLIP]);
in[SUBJ]= ( e0->bundle[ABOVE][SUBJ] && !e0->bside[SUBJ])
|| ( e1->bundle[ABOVE][SUBJ] && e1->bside[SUBJ])
|| (!e0->bundle[ABOVE][SUBJ] && !e1->bundle[ABOVE][SUBJ]
&& e0->bside[SUBJ] && e1->bside[SUBJ]);
/* Determine quadrant occupancies */
switch (op)
{
case GPC_DIFF:
case GPC_INT:
tr= (in[CLIP])
&& (in[SUBJ]);
tl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP])
&& (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ]);
br= (in[CLIP] ^ e0->bundle[ABOVE][CLIP])
&& (in[SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
bl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP] ^ e0->bundle[ABOVE][CLIP])
&& (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
break;
case GPC_XOR:
tr= (in[CLIP])
^ (in[SUBJ]);
tl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP])
^ (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ]);
br= (in[CLIP] ^ e0->bundle[ABOVE][CLIP])
^ (in[SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
bl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP] ^ e0->bundle[ABOVE][CLIP])
^ (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
break;
case GPC_UNION:
tr= (in[CLIP])
|| (in[SUBJ]);
tl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP])
|| (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ]);
br= (in[CLIP] ^ e0->bundle[ABOVE][CLIP])
|| (in[SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
bl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP] ^ e0->bundle[ABOVE][CLIP])
|| (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
break;
}
vclass= tr + (tl << 1) + (br << 2) + (bl << 3);
switch (vclass)
{
case EMN:
add_local_min(&out_poly, e0, ix, iy);
e1->outp[ABOVE]= e0->outp[ABOVE];
break;
case ERI:
if (p)
{
add_right(p, ix, iy);
e1->outp[ABOVE]= p;
e0->outp[ABOVE]= NULL;
}
break;
case ELI:
if (q)
{
add_left(q, ix, iy);
e0->outp[ABOVE]= q;
e1->outp[ABOVE]= NULL;
}
break;
case EMX:
if (p && q)
{
add_left(p, ix, iy);
merge_right(p, q, out_poly);
e0->outp[ABOVE]= NULL;
e1->outp[ABOVE]= NULL;
}
break;
case IMN:
add_local_min(&out_poly, e0, ix, iy);
e1->outp[ABOVE]= e0->outp[ABOVE];
break;
case ILI:
if (p)
{
add_left(p, ix, iy);
e1->outp[ABOVE]= p;
e0->outp[ABOVE]= NULL;
}
break;
case IRI:
if (q)
{
add_right(q, ix, iy);
e0->outp[ABOVE]= q;
e1->outp[ABOVE]= NULL;
}
break;
case IMX:
if (p && q)
{
add_right(p, ix, iy);
merge_left(p, q, out_poly);
e0->outp[ABOVE]= NULL;
e1->outp[ABOVE]= NULL;
}
break;
case IMM:
if (p && q)
{
add_right(p, ix, iy);
merge_left(p, q, out_poly);
add_local_min(&out_poly, e0, ix, iy);
e1->outp[ABOVE]= e0->outp[ABOVE];
}
break;
case EMM:
if (p && q)
{
add_left(p, ix, iy);
merge_right(p, q, out_poly);
add_local_min(&out_poly, e0, ix, iy);
e1->outp[ABOVE]= e0->outp[ABOVE];
}
break;
default:
break;
} /* End of switch */
} /* End of contributing intersection conditional */
/* Swap bundle sides in response to edge crossing */
if (e0->bundle[ABOVE][CLIP])
e1->bside[CLIP]= !e1->bside[CLIP];
if (e1->bundle[ABOVE][CLIP])
e0->bside[CLIP]= !e0->bside[CLIP];
if (e0->bundle[ABOVE][SUBJ])
e1->bside[SUBJ]= !e1->bside[SUBJ];
if (e1->bundle[ABOVE][SUBJ])
e0->bside[SUBJ]= !e0->bside[SUBJ];
/* Swap e0 and e1 bundles in the AET */
prev_edge= e0->prev;
next_edge= e1->next;
if (next_edge)
next_edge->prev= e0;
if (e0->bstate[ABOVE] == BUNDLE_HEAD)
{
search= TRUE;
while (search)
{
prev_edge= prev_edge->prev;
if (prev_edge)
{
if (prev_edge->bstate[ABOVE] != BUNDLE_TAIL)
search= FALSE;
}
else
search= FALSE;
}
}
if (!prev_edge)
{
aet->prev= e1;
e1->next= aet;
aet= e0->next;
}
else
{
prev_edge->next->prev= e1;
e1->next= prev_edge->next;
prev_edge->next= e0->next;
}
e0->next->prev= prev_edge;
e1->next->prev= e1;
e0->next= next_edge;
} /* End of IT loop*/
/* Prepare for next scanbeam */
for (edge= aet; edge; edge= next_edge)
{
next_edge= edge->next;
succ_edge= edge->succ;
if ((edge->top.y == yt) && succ_edge)
{
/* Replace AET edge by its successor */
succ_edge->outp[BELOW]= edge->outp[ABOVE];
succ_edge->bstate[BELOW]= edge->bstate[ABOVE];
succ_edge->bundle[BELOW][CLIP]= edge->bundle[ABOVE][CLIP];
succ_edge->bundle[BELOW][SUBJ]= edge->bundle[ABOVE][SUBJ];
prev_edge= edge->prev;
if (prev_edge)
prev_edge->next= succ_edge;
else
aet= succ_edge;
if (next_edge)
next_edge->prev= succ_edge;
succ_edge->prev= prev_edge;
succ_edge->next= next_edge;
}
else
{
/* Update this edge */
edge->outp[BELOW]= edge->outp[ABOVE];
edge->bstate[BELOW]= edge->bstate[ABOVE];
edge->bundle[BELOW][CLIP]= edge->bundle[ABOVE][CLIP];
edge->bundle[BELOW][SUBJ]= edge->bundle[ABOVE][SUBJ];
edge->xb= edge->xt;
}
edge->outp[ABOVE]= NULL;
}
}
} /* === END OF SCANBEAM PROCESSING ================================== */
/* Generate result polygon from out_poly */
result->contour= NULL;
result->hole= NULL;
result->num_contours= count_contours(out_poly);
if (result->num_contours > 0)
{
MALLOC(result->hole, result->num_contours
* sizeof(int), "hole flag table creation", int);
MALLOC(result->contour, result->num_contours
* sizeof(gpc_vertex_list), "contour creation", gpc_vertex_list);
c= 0;
for (poly= out_poly; poly; poly= npoly)
{
npoly= poly->next;
if (poly->active)
{
result->hole[c]= poly->proxy->hole;
result->contour[c].num_vertices= poly->active;
MALLOC(result->contour[c].vertex,
result->contour[c].num_vertices * sizeof(gpc_vertex),
"vertex creation", gpc_vertex);
v= result->contour[c].num_vertices - 1;
for (vtx= poly->proxy->v[LEFT]; vtx; vtx= nv)
{
nv= vtx->next;
result->contour[c].vertex[v].x= vtx->x;
result->contour[c].vertex[v].y= vtx->y;
FREE(vtx);
v--;
}
c++;
}
FREE(poly);
}
}
else
{
for (poly= out_poly; poly; poly= npoly)
{
npoly= poly->next;
FREE(poly);
}
}
/* Tidy up */
reset_it(&it);
reset_lmt(&lmt);
FREE(c_heap);
FREE(s_heap);
FREE(sbt);
}
void gpc_free_tristrip(gpc_tristrip *t)
{
int s;
for (s= 0; s < t->num_strips; s++)
FREE(t->strip[s].vertex);
FREE(t->strip);
t->num_strips= 0;
}
void gpc_polygon_to_tristrip(gpc_polygon *s, gpc_tristrip *t)
{
gpc_polygon c;
c.num_contours= 0;
c.hole= NULL;
c.contour= NULL;
gpc_tristrip_clip(GPC_DIFF, s, &c, t);
}
void gpc_tristrip_clip(gpc_op op, gpc_polygon *subj, gpc_polygon *clip,
gpc_tristrip *result)
{
sb_tree *sbtree= NULL;
it_node *it= NULL, *intersect;
edge_node *edge, *prev_edge, *next_edge, *succ_edge, *e0, *e1;
edge_node *aet= NULL, *c_heap= NULL, *s_heap= NULL, *cf;
lmt_node *lmt= NULL, *local_min;
polygon_node *tlist= NULL, *tn, *tnn, *p, *q;
vertex_node *lt, *ltn, *rt, *rtn;
h_state horiz[2];
vertex_type cft = vertex_type(-1);
int in[2], exists[2], parity[2]= {LEFT, LEFT};
int s, v, contributing, search, scanbeam= 0, sbt_entries= 0;
int vclass, bl, br, tl, tr;
double *sbt= NULL, xb, px, nx, yb, yt, dy, ix, iy;
cf = NULL;
contributing = bl = br = tl = tr = 0;
yt = dy = 0;
/* Test for trivial NULL result cases */
if (((subj->num_contours == 0) && (clip->num_contours == 0))
|| ((subj->num_contours == 0) && ((op == GPC_INT) || (op == GPC_DIFF)))
|| ((clip->num_contours == 0) && (op == GPC_INT)))
{
result->num_strips= 0;
result->strip= NULL;
return;
}
/* Identify potentialy contributing contours */
if (((op == GPC_INT) || (op == GPC_DIFF))
&& (subj->num_contours > 0) && (clip->num_contours > 0))
minimax_test(subj, clip, op);
/* Build LMT */
if (subj->num_contours > 0)
s_heap= build_lmt(&lmt, &sbtree, &sbt_entries, subj, SUBJ, op);
if (clip->num_contours > 0)
c_heap= build_lmt(&lmt, &sbtree, &sbt_entries, clip, CLIP, op);
/* Return a NULL result if no contours contribute */
if (lmt == NULL)
{
result->num_strips= 0;
result->strip= NULL;
reset_lmt(&lmt);
FREE(s_heap);
FREE(c_heap);
return;
}
/* Build scanbeam table from scanbeam tree */
MALLOC(sbt, sbt_entries * sizeof(double), "sbt creation", double);
build_sbt(&scanbeam, sbt, sbtree);
scanbeam= 0;
free_sbtree(&sbtree);
/* Invert clip polygon for difference operation */
if (op == GPC_DIFF)
parity[CLIP]= RIGHT;
local_min= lmt;
/* Process each scanbeam */
while (scanbeam < sbt_entries)
{
/* Set yb and yt to the bottom and top of the scanbeam */
yb= sbt[scanbeam++];
if (scanbeam < sbt_entries)
{
yt= sbt[scanbeam];
dy= yt - yb;
}
/* === SCANBEAM BOUNDARY PROCESSING ================================ */
/* If LMT node corresponding to yb exists */
if (local_min)
{
if (local_min->y == yb)
{
/* Add edges starting at this local minimum to the AET */
for (edge= local_min->first_bound; edge; edge= edge->next_bound)
add_edge_to_aet(&aet, edge, NULL);
local_min= local_min->next;
}
}
/* Set dummy previous x value */
px= -DBL_MAX;
/* Create bundles within AET */
e0= aet;
e1= aet;
/* Set up bundle fields of first edge */
aet->bundle[ABOVE][ aet->type]= (aet->top.y != yb);
aet->bundle[ABOVE][!aet->type]= FALSE;
aet->bstate[ABOVE]= UNBUNDLED;
for (next_edge= aet->next; next_edge; next_edge= next_edge->next)
{
/* Set up bundle fields of next edge */
next_edge->bundle[ABOVE][ next_edge->type]= (next_edge->top.y != yb);
next_edge->bundle[ABOVE][!next_edge->type]= FALSE;
next_edge->bstate[ABOVE]= UNBUNDLED;
/* Bundle edges above the scanbeam boundary if they coincide */
if (next_edge->bundle[ABOVE][next_edge->type])
{
if (EQ(e0->xb, next_edge->xb) && EQ(e0->dx, next_edge->dx)
&& (e0->top.y != yb))
{
next_edge->bundle[ABOVE][ next_edge->type]^=
e0->bundle[ABOVE][ next_edge->type];
next_edge->bundle[ABOVE][!next_edge->type]=
e0->bundle[ABOVE][!next_edge->type];
next_edge->bstate[ABOVE]= BUNDLE_HEAD;
e0->bundle[ABOVE][CLIP]= FALSE;
e0->bundle[ABOVE][SUBJ]= FALSE;
e0->bstate[ABOVE]= BUNDLE_TAIL;
}
e0= next_edge;
}
}
horiz[CLIP]= NH;
horiz[SUBJ]= NH;
/* Process each edge at this scanbeam boundary */
for (edge= aet; edge; edge= edge->next)
{
exists[CLIP]= edge->bundle[ABOVE][CLIP] +
(edge->bundle[BELOW][CLIP] << 1);
exists[SUBJ]= edge->bundle[ABOVE][SUBJ] +
(edge->bundle[BELOW][SUBJ] << 1);
if (exists[CLIP] || exists[SUBJ])
{
/* Set bundle side */
edge->bside[CLIP]= parity[CLIP];
edge->bside[SUBJ]= parity[SUBJ];
/* Determine contributing status and quadrant occupancies */
switch (op)
{
case GPC_DIFF:
case GPC_INT:
contributing= (exists[CLIP] && (parity[SUBJ] || horiz[SUBJ]))
|| (exists[SUBJ] && (parity[CLIP] || horiz[CLIP]))
|| (exists[CLIP] && exists[SUBJ]
&& (parity[CLIP] == parity[SUBJ]));
br= (parity[CLIP])
&& (parity[SUBJ]);
bl= (parity[CLIP] ^ edge->bundle[ABOVE][CLIP])
&& (parity[SUBJ] ^ edge->bundle[ABOVE][SUBJ]);
tr= (parity[CLIP] ^ (horiz[CLIP]!=NH))
&& (parity[SUBJ] ^ (horiz[SUBJ]!=NH));
tl= (parity[CLIP] ^ (horiz[CLIP]!=NH) ^ edge->bundle[BELOW][CLIP])
&& (parity[SUBJ] ^ (horiz[SUBJ]!=NH) ^ edge->bundle[BELOW][SUBJ]);
break;
case GPC_XOR:
contributing= exists[CLIP] || exists[SUBJ];
br= (parity[CLIP])
^ (parity[SUBJ]);
bl= (parity[CLIP] ^ edge->bundle[ABOVE][CLIP])
^ (parity[SUBJ] ^ edge->bundle[ABOVE][SUBJ]);
tr= (parity[CLIP] ^ (horiz[CLIP]!=NH))
^ (parity[SUBJ] ^ (horiz[SUBJ]!=NH));
tl= (parity[CLIP] ^ (horiz[CLIP]!=NH) ^ edge->bundle[BELOW][CLIP])
^ (parity[SUBJ] ^ (horiz[SUBJ]!=NH) ^ edge->bundle[BELOW][SUBJ]);
break;
case GPC_UNION:
contributing= (exists[CLIP] && (!parity[SUBJ] || horiz[SUBJ]))
|| (exists[SUBJ] && (!parity[CLIP] || horiz[CLIP]))
|| (exists[CLIP] && exists[SUBJ]
&& (parity[CLIP] == parity[SUBJ]));
br= (parity[CLIP])
|| (parity[SUBJ]);
bl= (parity[CLIP] ^ edge->bundle[ABOVE][CLIP])
|| (parity[SUBJ] ^ edge->bundle[ABOVE][SUBJ]);
tr= (parity[CLIP] ^ (horiz[CLIP]!=NH))
|| (parity[SUBJ] ^ (horiz[SUBJ]!=NH));
tl= (parity[CLIP] ^ (horiz[CLIP]!=NH) ^ edge->bundle[BELOW][CLIP])
|| (parity[SUBJ] ^ (horiz[SUBJ]!=NH) ^ edge->bundle[BELOW][SUBJ]);
break;
}
/* Update parity */
parity[CLIP]^= edge->bundle[ABOVE][CLIP];
parity[SUBJ]^= edge->bundle[ABOVE][SUBJ];
/* Update horizontal state */
if (exists[CLIP])
horiz[CLIP]=
next_h_state[horiz[CLIP]]
[((exists[CLIP] - 1) << 1) + parity[CLIP]];
if (exists[SUBJ])
horiz[SUBJ]=
next_h_state[horiz[SUBJ]]
[((exists[SUBJ] - 1) << 1) + parity[SUBJ]];
vclass= tr + (tl << 1) + (br << 2) + (bl << 3);
if (contributing)
{
xb= edge->xb;
switch (vclass)
{
case EMN:
new_tristrip(&tlist, edge, xb, yb);
cf= edge;
break;
case ERI:
edge->outp[ABOVE]= cf->outp[ABOVE];
if (xb != cf->xb)
VERTEX(edge, ABOVE, RIGHT, xb, yb);
cf= NULL;
break;
case ELI:
VERTEX(edge, BELOW, LEFT, xb, yb);
edge->outp[ABOVE]= NULL;
cf= edge;
break;
case EMX:
if (xb != cf->xb)
VERTEX(edge, BELOW, RIGHT, xb, yb);
edge->outp[ABOVE]= NULL;
cf= NULL;
break;
case IMN:
if (cft == LED)
{
if (cf->bot.y != yb)
VERTEX(cf, BELOW, LEFT, cf->xb, yb);
new_tristrip(&tlist, cf, cf->xb, yb);
}
edge->outp[ABOVE]= cf->outp[ABOVE];
VERTEX(edge, ABOVE, RIGHT, xb, yb);
break;
case ILI:
new_tristrip(&tlist, edge, xb, yb);
cf= edge;
cft= ILI;
break;
case IRI:
if (cft == LED)
{
if (cf->bot.y != yb)
VERTEX(cf, BELOW, LEFT, cf->xb, yb);
new_tristrip(&tlist, cf, cf->xb, yb);
}
VERTEX(edge, BELOW, RIGHT, xb, yb);
edge->outp[ABOVE]= NULL;
break;
case IMX:
VERTEX(edge, BELOW, LEFT, xb, yb);
edge->outp[ABOVE]= NULL;
cft= IMX;
break;
case IMM:
VERTEX(edge, BELOW, LEFT, xb, yb);
edge->outp[ABOVE]= cf->outp[ABOVE];
if (xb != cf->xb)
VERTEX(cf, ABOVE, RIGHT, xb, yb);
cf= edge;
break;
case EMM:
VERTEX(edge, BELOW, RIGHT, xb, yb);
edge->outp[ABOVE]= NULL;
new_tristrip(&tlist, edge, xb, yb);
cf= edge;
break;
case LED:
if (edge->bot.y == yb)
VERTEX(edge, BELOW, LEFT, xb, yb);
edge->outp[ABOVE]= edge->outp[BELOW];
cf= edge;
cft= LED;
break;
case RED:
edge->outp[ABOVE]= cf->outp[ABOVE];
if (cft == LED)
{
if (cf->bot.y == yb)
{
VERTEX(edge, BELOW, RIGHT, xb, yb);
}
else
{
if (edge->bot.y == yb)
{
VERTEX(cf, BELOW, LEFT, cf->xb, yb);
VERTEX(edge, BELOW, RIGHT, xb, yb);
}
}
}
else
{
VERTEX(edge, BELOW, RIGHT, xb, yb);
VERTEX(edge, ABOVE, RIGHT, xb, yb);
}
cf= NULL;
break;
default:
break;
} /* End of switch */
} /* End of contributing conditional */
} /* End of edge exists conditional */
} /* End of AET loop */
/* Delete terminating edges from the AET, otherwise compute xt */
for (edge= aet; edge; edge= edge->next)
{
if (edge->top.y == yb)
{
prev_edge= edge->prev;
next_edge= edge->next;
if (prev_edge)
prev_edge->next= next_edge;
else
aet= next_edge;
if (next_edge)
next_edge->prev= prev_edge;
/* Copy bundle head state to the adjacent tail edge if required */
if ((edge->bstate[BELOW] == BUNDLE_HEAD) && prev_edge)
{
if (prev_edge->bstate[BELOW] == BUNDLE_TAIL)
{
prev_edge->outp[BELOW]= edge->outp[BELOW];
prev_edge->bstate[BELOW]= UNBUNDLED;
if (prev_edge->prev)
if (prev_edge->prev->bstate[BELOW] == BUNDLE_TAIL)
prev_edge->bstate[BELOW]= BUNDLE_HEAD;
}
}
}
else
{
if (edge->top.y == yt)
edge->xt= edge->top.x;
else
edge->xt= edge->bot.x + edge->dx * (yt - edge->bot.y);
}
}
if (scanbeam < sbt_entries)
{
/* === SCANBEAM INTERIOR PROCESSING ============================== */
build_intersection_table(&it, aet, dy);
/* Process each node in the intersection table */
for (intersect= it; intersect; intersect= intersect->next)
{
e0= intersect->ie[0];
e1= intersect->ie[1];
/* Only generate output for contributing intersections */
if ((e0->bundle[ABOVE][CLIP] || e0->bundle[ABOVE][SUBJ])
&& (e1->bundle[ABOVE][CLIP] || e1->bundle[ABOVE][SUBJ]))
{
p= e0->outp[ABOVE];
q= e1->outp[ABOVE];
ix= intersect->point.x;
iy= intersect->point.y + yb;
in[CLIP]= ( e0->bundle[ABOVE][CLIP] && !e0->bside[CLIP])
|| ( e1->bundle[ABOVE][CLIP] && e1->bside[CLIP])
|| (!e0->bundle[ABOVE][CLIP] && !e1->bundle[ABOVE][CLIP]
&& e0->bside[CLIP] && e1->bside[CLIP]);
in[SUBJ]= ( e0->bundle[ABOVE][SUBJ] && !e0->bside[SUBJ])
|| ( e1->bundle[ABOVE][SUBJ] && e1->bside[SUBJ])
|| (!e0->bundle[ABOVE][SUBJ] && !e1->bundle[ABOVE][SUBJ]
&& e0->bside[SUBJ] && e1->bside[SUBJ]);
/* Determine quadrant occupancies */
switch (op)
{
case GPC_DIFF:
case GPC_INT:
tr= (in[CLIP])
&& (in[SUBJ]);
tl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP])
&& (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ]);
br= (in[CLIP] ^ e0->bundle[ABOVE][CLIP])
&& (in[SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
bl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP] ^ e0->bundle[ABOVE][CLIP])
&& (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
break;
case GPC_XOR:
tr= (in[CLIP])
^ (in[SUBJ]);
tl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP])
^ (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ]);
br= (in[CLIP] ^ e0->bundle[ABOVE][CLIP])
^ (in[SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
bl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP] ^ e0->bundle[ABOVE][CLIP])
^ (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
break;
case GPC_UNION:
tr= (in[CLIP])
|| (in[SUBJ]);
tl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP])
|| (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ]);
br= (in[CLIP] ^ e0->bundle[ABOVE][CLIP])
|| (in[SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
bl= (in[CLIP] ^ e1->bundle[ABOVE][CLIP] ^ e0->bundle[ABOVE][CLIP])
|| (in[SUBJ] ^ e1->bundle[ABOVE][SUBJ] ^ e0->bundle[ABOVE][SUBJ]);
break;
}
vclass= tr + (tl << 1) + (br << 2) + (bl << 3);
switch (vclass)
{
case EMN:
new_tristrip(&tlist, e1, ix, iy);
e0->outp[ABOVE]= e1->outp[ABOVE];
break;
case ERI:
if (p)
{
P_EDGE(prev_edge, e0, ABOVE, px, iy);
VERTEX(prev_edge, ABOVE, LEFT, px, iy);
VERTEX(e0, ABOVE, RIGHT, ix, iy);
e1->outp[ABOVE]= e0->outp[ABOVE];
e0->outp[ABOVE]= NULL;
}
break;
case ELI:
if (q)
{
N_EDGE(next_edge, e1, ABOVE, nx, iy);
VERTEX(e1, ABOVE, LEFT, ix, iy);
VERTEX(next_edge, ABOVE, RIGHT, nx, iy);
e0->outp[ABOVE]= e1->outp[ABOVE];
e1->outp[ABOVE]= NULL;
}
break;
case EMX:
if (p && q)
{
VERTEX(e0, ABOVE, LEFT, ix, iy);
e0->outp[ABOVE]= NULL;
e1->outp[ABOVE]= NULL;
}
break;
case IMN:
P_EDGE(prev_edge, e0, ABOVE, px, iy);
VERTEX(prev_edge, ABOVE, LEFT, px, iy);
N_EDGE(next_edge, e1, ABOVE, nx, iy);
VERTEX(next_edge, ABOVE, RIGHT, nx, iy);
new_tristrip(&tlist, prev_edge, px, iy);
e1->outp[ABOVE]= prev_edge->outp[ABOVE];
VERTEX(e1, ABOVE, RIGHT, ix, iy);
new_tristrip(&tlist, e0, ix, iy);
next_edge->outp[ABOVE]= e0->outp[ABOVE];
VERTEX(next_edge, ABOVE, RIGHT, nx, iy);
break;
case ILI:
if (p)
{
VERTEX(e0, ABOVE, LEFT, ix, iy);
N_EDGE(next_edge, e1, ABOVE, nx, iy);
VERTEX(next_edge, ABOVE, RIGHT, nx, iy);
e1->outp[ABOVE]= e0->outp[ABOVE];
e0->outp[ABOVE]= NULL;
}
break;
case IRI:
if (q)
{
VERTEX(e1, ABOVE, RIGHT, ix, iy);
P_EDGE(prev_edge, e0, ABOVE, px, iy);
VERTEX(prev_edge, ABOVE, LEFT, px, iy);
e0->outp[ABOVE]= e1->outp[ABOVE];
e1->outp[ABOVE]= NULL;
}
break;
case IMX:
if (p && q)
{
VERTEX(e0, ABOVE, RIGHT, ix, iy);
VERTEX(e1, ABOVE, LEFT, ix, iy);
e0->outp[ABOVE]= NULL;
e1->outp[ABOVE]= NULL;
P_EDGE(prev_edge, e0, ABOVE, px, iy);
VERTEX(prev_edge, ABOVE, LEFT, px, iy);
new_tristrip(&tlist, prev_edge, px, iy);
N_EDGE(next_edge, e1, ABOVE, nx, iy);
VERTEX(next_edge, ABOVE, RIGHT, nx, iy);
next_edge->outp[ABOVE]= prev_edge->outp[ABOVE];
VERTEX(next_edge, ABOVE, RIGHT, nx, iy);
}
break;
case IMM:
if (p && q)
{
VERTEX(e0, ABOVE, RIGHT, ix, iy);
VERTEX(e1, ABOVE, LEFT, ix, iy);
P_EDGE(prev_edge, e0, ABOVE, px, iy);
VERTEX(prev_edge, ABOVE, LEFT, px, iy);
new_tristrip(&tlist, prev_edge, px, iy);
N_EDGE(next_edge, e1, ABOVE, nx, iy);
VERTEX(next_edge, ABOVE, RIGHT, nx, iy);
e1->outp[ABOVE]= prev_edge->outp[ABOVE];
VERTEX(e1, ABOVE, RIGHT, ix, iy);
new_tristrip(&tlist, e0, ix, iy);
next_edge->outp[ABOVE]= e0->outp[ABOVE];
VERTEX(next_edge, ABOVE, RIGHT, nx, iy);
}
break;
case EMM:
if (p && q)
{
VERTEX(e0, ABOVE, LEFT, ix, iy);
new_tristrip(&tlist, e1, ix, iy);
e0->outp[ABOVE]= e1->outp[ABOVE];
}
break;
default:
break;
} /* End of switch */
} /* End of contributing intersection conditional */
/* Swap bundle sides in response to edge crossing */
if (e0->bundle[ABOVE][CLIP])
e1->bside[CLIP]= !e1->bside[CLIP];
if (e1->bundle[ABOVE][CLIP])
e0->bside[CLIP]= !e0->bside[CLIP];
if (e0->bundle[ABOVE][SUBJ])
e1->bside[SUBJ]= !e1->bside[SUBJ];
if (e1->bundle[ABOVE][SUBJ])
e0->bside[SUBJ]= !e0->bside[SUBJ];
/* Swap e0 and e1 bundles in the AET */
prev_edge= e0->prev;
next_edge= e1->next;
if (e1->next)
e1->next->prev= e0;
if (e0->bstate[ABOVE] == BUNDLE_HEAD)
{
search= TRUE;
while (search)
{
prev_edge= prev_edge->prev;
if (prev_edge)
{
if (prev_edge->bundle[ABOVE][CLIP]
|| prev_edge->bundle[ABOVE][SUBJ]
|| (prev_edge->bstate[ABOVE] == BUNDLE_HEAD))
search= FALSE;
}
else
search= FALSE;
}
}
if (!prev_edge)
{
e1->next= aet;
aet= e0->next;
}
else
{
e1->next= prev_edge->next;
prev_edge->next= e0->next;
}
e0->next->prev= prev_edge;
e1->next->prev= e1;
e0->next= next_edge;
} /* End of IT loop*/
/* Prepare for next scanbeam */
for (edge= aet; edge; edge= next_edge)
{
next_edge= edge->next;
succ_edge= edge->succ;
if ((edge->top.y == yt) && succ_edge)
{
/* Replace AET edge by its successor */
succ_edge->outp[BELOW]= edge->outp[ABOVE];
succ_edge->bstate[BELOW]= edge->bstate[ABOVE];
succ_edge->bundle[BELOW][CLIP]= edge->bundle[ABOVE][CLIP];
succ_edge->bundle[BELOW][SUBJ]= edge->bundle[ABOVE][SUBJ];
prev_edge= edge->prev;
if (prev_edge)
prev_edge->next= succ_edge;
else
aet= succ_edge;
if (next_edge)
next_edge->prev= succ_edge;
succ_edge->prev= prev_edge;
succ_edge->next= next_edge;
}
else
{
/* Update this edge */
edge->outp[BELOW]= edge->outp[ABOVE];
edge->bstate[BELOW]= edge->bstate[ABOVE];
edge->bundle[BELOW][CLIP]= edge->bundle[ABOVE][CLIP];
edge->bundle[BELOW][SUBJ]= edge->bundle[ABOVE][SUBJ];
edge->xb= edge->xt;
}
edge->outp[ABOVE]= NULL;
}
}
} /* === END OF SCANBEAM PROCESSING ================================== */
/* Generate result tristrip from tlist */
result->strip= NULL;
result->num_strips= count_tristrips(tlist);
if (result->num_strips > 0)
{
MALLOC(result->strip, result->num_strips * sizeof(gpc_vertex_list),
"tristrip list creation", gpc_vertex_list);
s= 0;
for (tn= tlist; tn; tn= tnn)
{
tnn= tn->next;
if (tn->active > 2)
{
/* Valid tristrip: copy the vertices and free the heap */
result->strip[s].num_vertices= tn->active;
MALLOC(result->strip[s].vertex, tn->active * sizeof(gpc_vertex),
"tristrip creation", gpc_vertex);
v= 0;
if (INVERT_TRISTRIPS)
{
lt= tn->v[RIGHT];
rt= tn->v[LEFT];
}
else
{
lt= tn->v[LEFT];
rt= tn->v[RIGHT];
}
while (lt || rt)
{
if (lt)
{
ltn= lt->next;
result->strip[s].vertex[v].x= lt->x;
result->strip[s].vertex[v].y= lt->y;
v++;
FREE(lt);
lt= ltn;
}
if (rt)
{
rtn= rt->next;
result->strip[s].vertex[v].x= rt->x;
result->strip[s].vertex[v].y= rt->y;
v++;
FREE(rt);
rt= rtn;
}
}
s++;
}
else
{
/* Invalid tristrip: just free the heap */
for (lt= tn->v[LEFT]; lt; lt= ltn)
{
ltn= lt->next;
FREE(lt);
}
for (rt= tn->v[RIGHT]; rt; rt=rtn)
{
rtn= rt->next;
FREE(rt);
}
}
FREE(tn);
}
}
/* Tidy up */
reset_it(&it);
reset_lmt(&lmt);
FREE(c_heap);
FREE(s_heap);
FREE(sbt);
}
/*
===========================================================================
End of file: gpc.c
===========================================================================
*/
/*
===========================================================================
Project: Generic Polygon Clipper
A new algorithm for calculating the difference, intersection,
exclusive-or or union of arbitrary polygon sets.
File: gpc.h
Author: Alan Murta (email: gpc@cs.man.ac.uk)
Version: 2.32
Date: 17th December 2004
Copyright: (C) Advanced Interfaces Group,
University of Manchester.
This software is free for non-commercial use. It may be copied,
modified, and redistributed provided that this copyright notice
is preserved on all copies. The intellectual property rights of
the algorithms used reside with the University of Manchester
Advanced Interfaces Group.
You may not use this software, in whole or in part, in support
of any commercial product without the express consent of the
author.
There is no warranty or other guarantee of fitness of this
software for any purpose. It is provided solely "as is".
===========================================================================
*/
#ifndef __gpc_h
#define __gpc_h
#include <stdio.h>
/*
===========================================================================
Constants
===========================================================================
*/
/* Increase GPC_EPSILON to encourage merging of near coincident edges */
#define GPC_EPSILON (DBL_EPSILON)
#define GPC_VERSION "2.32"
/*
===========================================================================
Public Data Types
===========================================================================
*/
typedef enum /* Set operation type */
{
GPC_DIFF, /* Difference */
GPC_INT, /* Intersection */
GPC_XOR, /* Exclusive or */
GPC_UNION /* Union */
} gpc_op;
typedef struct /* Polygon vertex structure */
{
double x; /* Vertex x component */
double y; /* vertex y component */
} gpc_vertex;
typedef struct /* Vertex list structure */
{
int num_vertices; /* Number of vertices in list */
gpc_vertex *vertex; /* Vertex array pointer */
} gpc_vertex_list;
typedef struct /* Polygon set structure */
{
int num_contours; /* Number of contours in polygon */
int *hole; /* Hole / external contour flags */
gpc_vertex_list *contour; /* Contour array pointer */
} gpc_polygon;
typedef struct /* Tristrip set structure */
{
int num_strips; /* Number of tristrips */
gpc_vertex_list *strip; /* Tristrip array pointer */
} gpc_tristrip;
/*
===========================================================================
Public Function Prototypes
===========================================================================
*/
void gpc_read_polygon (FILE *infile_ptr,
int read_hole_flags,
gpc_polygon *polygon);
void gpc_write_polygon (FILE *outfile_ptr,
int write_hole_flags,
gpc_polygon *polygon);
void gpc_add_contour (gpc_polygon *polygon,
gpc_vertex_list *contour,
int hole);
void gpc_polygon_clip (gpc_op set_operation,
gpc_polygon *subject_polygon,
gpc_polygon *clip_polygon,
gpc_polygon *result_polygon);
void gpc_tristrip_clip (gpc_op set_operation,
gpc_polygon *subject_polygon,
gpc_polygon *clip_polygon,
gpc_tristrip *result_tristrip);
void gpc_polygon_to_tristrip (gpc_polygon *polygon,
gpc_tristrip *tristrip);
void gpc_free_polygon (gpc_polygon *polygon);
void gpc_free_tristrip (gpc_tristrip *tristrip);
#endif
/*
===========================================================================
End of file: gpc.h
===========================================================================
*/
Generic Polygon Clipper (gpc) Revision History
==============================================
v2.32 17th Dec 2004
---------------------
Fixed occasional memory leak occurring when processing some
degenerate polygon arrangements.
Added explicit type casting to memory allocator in support of
increased code portability.
v2.31 4th Jun 1999
---------------------
Separated edge merging measure based on a user-defined GPC_EPSILON
value from general numeric equality testing and ordering, which now
uses direct arithmetic comparison rather an EPSILON based proximity
test.
Fixed problem with numerical equality test during construction of
local minima and scanbeam tables, leading to occasional crash.
Fixed hole array memory leak in gpc_add_contour.
Fixed uninitialised hole field bug in gpc_polygon_clip result.
v2.30 11th Apr 1999
---------------------
Major re-write.
Minor API change: additional 'hole' array field added to gpc_polygon
datatype to indicate which constituent contours are internal holes,
and which form external boundaries.
Minor API change: additional 'hole' argument to gpc_add_contour
to indicate whether the new contour is a hole or external contour.
Minor API change: additional parameter to gpc_read_polygon and
gpc_write_polygon to indicate whether or not to read or write
contour hole flags.
Fixed NULL pointer bug in add/merge left/right operations.
Fixed numerical problem in intersection table generation.
Fixed zero byte malloc problem.
Fixed problem producing occasional 2 vertex contours.
Added bounding box test optimisations.
Simplified edge bundle creation, detection of scanbeam internal
edge intersections and tristrip scanbeam boundary code.
Renamed 'class' variable to be C++ friendly.
v2.22 17th Oct 1998
---------------------
Re-implemented edge interpolation and intersection calculations
to improve numerical robustness.
Simplified setting of GPC_EPSILON.
v2.21 19th Aug 1998
---------------------
Fixed problem causing occasional incorrect output when processing
self-intersecting polygons (bow-ties etc).
Removed bug which may lead to non-generation of uppermost triangle
in tristrip output.
v2.20 26th May 1998
---------------------
Major re-write.
Added exclusive-or polygon set operation.
Replaced table-based processing of edge intersections with
rule-based system.
Replaced two-pass approach to scanbeam interior processing with
single pass method.
v2.10a 14th May 1998
---------------------
Minor bug-fixes to counter some v2.10 reliability problems.
v2.10 11th May 1998
---------------------
Major re-write.
Incorporated edge bundle processing of AET to overcome coincident
edge problems present in previous releases.
Replaced Vatti's method for processing scanbeam interior regions
with an adapted version of the scanbeam boundary processing
algorithm.
v2.02 16th Apr 1998 (unreleased)
----------------------------------
Fixed internal minimum vertex duplication in gpc_polygon_clip
result.
Improved line intersection code discourage superfluous
intersections near line ends.
Removed limited precision number formatting in gpc_write_polygon.
Modification to allow subject or clip polygon to be reused as the
result in gpc_polygon_clip without memory leakage.
v2.01 23rd Feb 1998
---------------------
Removed bug causing duplicated vertices in output polygon.
Fixed scanbeam table index overrun problem.
v2.00 25th Nov 1997
---------------------
Major re-write.
Replaced temporary horizontal edge work-around (using tilting)
with true horizontal edge handling.
Trapezoidal output replaced by tristrips.
gpc_op constants now feature a `GPC_' prefix.
Data structures now passed by reference to gpc functions.
Replaced AET search by proxy addressing in polygon table.
Eliminated most (all?) coincident vertex / edge crashes.
v1.02 18th Oct 1997 (unreleased)
----------------------------------
Significantly reduced number of mallocs in build_lmt.
Scanbeam table now built using heapsort rather than insertion
sort.
v1.01 12th Oct 1997
---------------------
Fixed memory leak during output polygon build in
gpc_clip_polygon.
Removed superfluous logfile debug code.
Commented out malloc counts.
Added missing horizontal edge tilt-correction code in
gpc_clip_polygon.
v1.00 8th Oct 1997
--------------------
First release.
// PolyLine.cpp ... implementation of CPolyLine class from FreePCB.
//
// implementation for kicad
// implementation for kicad and kbool polygon clipping library
//
using namespace std;
......@@ -13,8 +13,6 @@ using namespace std;
#include "PolyLine.h"
#define to_int( x ) (int) round( (x) )
#define pi 3.14159265359
......@@ -23,17 +21,7 @@ CPolyLine::CPolyLine()
m_HatchStyle = 0;
m_Width = 0;
utility = 0;
#ifdef USE_GPC_POLY_LIB
m_gpc_poly = new gpc_polygon;
m_gpc_poly->num_contours = 0;
#else
m_gpc_poly = NULL;
#endif
#ifdef USE_GPL_POLY_LIB
m_php_poly = new polygon;
#else
m_php_poly = NULL;
#endif
m_Kbool_Poly_Engine = NULL;
}
......@@ -42,288 +30,286 @@ CPolyLine::CPolyLine()
CPolyLine::~CPolyLine()
{
Undraw();
#ifdef USE_GPC_POLY_LIB
FreeGpcPoly();
delete m_gpc_poly;
#endif
#ifdef USE_GPL_POLY_LIB
delete m_php_poly;
#endif
}
#ifdef USE_GPC_POLY_LIB
// Use the General Polygon Clipping Library to clip contours
// If this results in new polygons, return them as std::vector p
// If bRetainArcs == TRUE, try to retain arcs in polys
// Returns number of external contours, or -1 if error
//
int CPolyLine::NormalizeWithGpc( std::vector<CPolyLine*> * pa, bool bRetainArcs )
/** Function NormalizeWithKbool
* Use the Kbool Library to clip contours: if outlines are crossing, the self-crossing polygon
* is converted to non self-crossing polygon by adding extra points at the crossing locations
* if more than one outside contour are found, extra CPolyLines will be created
* because copper areas have only one outside contour
* Therefore, if this results in new CPolyLines, return them as std::vector pa
* @param pa: pointer on a std::vector<CPolyLine*> to store extra CPolyLines
* @param bRetainArcs == TRUE, try to retain arcs in polys
* @return number of external contours, or -1 if error
*/
int CPolyLine::NormalizeWithKbool( std::vector<CPolyLine*> * pa, bool bRetainArcs )
{
std::vector<CArc> arc_array;
std::vector<CArc> arc_array;
std::vector <void*> hole_array; // list of holes
std::vector<int> * hole; // used to store corners for a given hole
CPolyLine* polyline;
int n_ext_cont = 0; // CPolyLine count
/* Creates a bool engine from this CPolyLine.
* Normalized outlines and holes will be in m_Kbool_Poly_Engine
* If some polygons are self crossing, after running the Kbool Engine, self crossing polygons
* will be converted in non self crossing polygons by inserting extra points at the crossing locations
* True holes are combined if possible
*/
if( bRetainArcs )
MakeGpcPoly( -1, &arc_array );
MakeKboolPoly( -1, -1, &arc_array );
else
MakeGpcPoly( -1, NULL );
MakeKboolPoly( -1, -1, NULL );
Undraw();
// now, recreate poly
// first, find outside contours and create new CPolyLines if necessary
int n_ext_cont = 0;
for( int ic = 0; ic<m_gpc_poly->num_contours; ic++ )
/* now, recreate polys
* if more than one outside contour are found, extra CPolyLines will be created
* because copper areas have only one outside contour
* the first outside contour found is the new "this" outside contour
* if others outside contours are found we create new CPolyLines
* Note: if there are holes in polygons, we must store them
* and when all outside contours are found, search the corresponding outside contour for each hole
*/
while( m_Kbool_Poly_Engine->StartPolygonGet() )
{
if( !(m_gpc_poly->hole)[ic] )
// See if the current polygon is flagged as a hole
if( m_Kbool_Poly_Engine->GetPolygonPointEdgeType() == KB_INSIDE_EDGE )
{
if( n_ext_cont == 0 )
hole = new std::vector<int>;
hole_array.push_back( hole );
while( m_Kbool_Poly_Engine->PolygonHasMorePoints() ) // store hole
{
// first external contour, replace this poly
corner.clear();
side_style.clear();
for( int i = 0; i<m_gpc_poly->contour[ic].num_vertices; i++ )
int x = m_Kbool_Poly_Engine->GetPolygonXPoint();
int y = m_Kbool_Poly_Engine->GetPolygonYPoint();
hole->push_back( x );
hole->push_back( y );
}
m_Kbool_Poly_Engine->EndPolygonGet();
}
else if( n_ext_cont == 0 )
{
// first external contour, replace this poly
corner.clear();
side_style.clear();
bool first = true;
while( m_Kbool_Poly_Engine->PolygonHasMorePoints() )
{ // foreach point in the polygon
int x = m_Kbool_Poly_Engine->GetPolygonXPoint();
int y = m_Kbool_Poly_Engine->GetPolygonYPoint();
if( first )
{
int x = to_int( ( (m_gpc_poly->contour)[ic].vertex )[i].x );
int y = to_int( ( (m_gpc_poly->contour)[ic].vertex )[i].y );
if( i==0 )
Start( m_layer, x, y, m_HatchStyle );
else
AppendCorner( x, y, STRAIGHT, FALSE );
first = false;
Start( GetLayer(), x, y, GetHatchStyle() );
}
Close();
n_ext_cont++;
else
AppendCorner( x, y );
}
else if( pa )
m_Kbool_Poly_Engine->EndPolygonGet();
Close();
n_ext_cont++;
}
else if( pa ) // a new outside contour is found: create a new CPolyLine
{
polyline = new CPolyLine; // create new poly
pa->push_back( polyline ); // put it in array
bool first = true;
while( m_Kbool_Poly_Engine->PolygonHasMorePoints() ) // read next external contour
{
// next external contour, create new poly
CPolyLine* poly = new CPolyLine;
pa->push_back( poly ); // put in array
for( int i = 0; i<m_gpc_poly->contour[ic].num_vertices; i++ )
int x = m_Kbool_Poly_Engine->GetPolygonXPoint();
int y = m_Kbool_Poly_Engine->GetPolygonYPoint();
if( first )
{
int x = to_int( ( (m_gpc_poly->contour)[ic].vertex )[i].x );
int y = to_int( ( (m_gpc_poly->contour)[ic].vertex )[i].y );
if( i==0 )
poly->Start( m_layer, x, y, m_HatchStyle );
else
poly->AppendCorner( x, y, STRAIGHT, FALSE );
first = false;
polyline->Start( GetLayer(), x, y, GetHatchStyle() );
}
poly->Close( STRAIGHT, FALSE );
n_ext_cont++;
else
polyline->AppendCorner( x, y );
}
m_Kbool_Poly_Engine->EndPolygonGet();
polyline->Close( STRAIGHT, FALSE );
n_ext_cont++;
}
}
// now add cutouts to the CPolyLine(s)
for( int ic = 0; ic<m_gpc_poly->num_contours; ic++ )
// now add cutouts to the corresponding CPolyLine(s)
for( unsigned ii = 0; ii < hole_array.size(); ii++ )
{
if( (m_gpc_poly->hole)[ic] )
hole = (std::vector<int> *)hole_array[ii];
polyline = NULL;
if( n_ext_cont == 1 )
{
CPolyLine* ext_poly = NULL;
if( n_ext_cont == 1 )
{
ext_poly = this;
}
else
polyline = this;
}
else
{
// find the polygon that contains this hole
// testing one corner inside is enought because a hole is entirely inside the polygon
// sowe test only the first corner
int x = (*hole)[0];
int y = (*hole)[1];
if( TestPointInside( x, y ) )
polyline = this;
else if( pa )
{
// find the polygon that contains this hole
for( int i = 0; i<m_gpc_poly->contour[ic].num_vertices; i++ )
for( int ext_ic = 0; ext_ic<n_ext_cont - 1; ext_ic++ )
{
int x = to_int( ( (m_gpc_poly->contour)[ic].vertex )[i].x );
int y = to_int( ( (m_gpc_poly->contour)[ic].vertex )[i].y );
if( TestPointInside( x, y ) )
ext_poly = this;
else
if( (*pa)[ext_ic]->TestPointInside( x, y ) )
{
for( int ext_ic = 0; ext_ic<n_ext_cont - 1; ext_ic++ )
{
if( (*pa)[ext_ic]->TestPointInside( x, y ) )
{
ext_poly = (*pa)[ext_ic];
break;
}
}
}
if( ext_poly )
polyline = (*pa)[ext_ic];
break;
}
}
}
if( !ext_poly )
wxASSERT( 0 );
for( int i = 0; i<m_gpc_poly->contour[ic].num_vertices; i++ )
}
if( !polyline )
wxASSERT( 0 );
else
{
for( unsigned ii = 0; ii< (*hole).size(); ii++ )
{
int x = to_int( ( (m_gpc_poly->contour)[ic].vertex )[i].x );
int y = to_int( ( (m_gpc_poly->contour)[ic].vertex )[i].y );
ext_poly->AppendCorner( x, y, STRAIGHT, FALSE );
int x = (*hole)[ii]; ii++;
int y = (*hole)[ii];
polyline->AppendCorner( x, y, STRAIGHT, FALSE );
}
ext_poly->Close( STRAIGHT, FALSE );
polyline->Close( STRAIGHT, FALSE );
}
}
if( bRetainArcs )
RestoreArcs( &arc_array, pa );
FreeGpcPoly();
return n_ext_cont;
}
#endif
delete m_Kbool_Poly_Engine;
m_Kbool_Poly_Engine = NULL;
#ifdef USE_GPL_POLY_LIB
// free hole list
for( unsigned ii = 0; ii < hole_array.size(); ii++ )
delete (std::vector<int> *)hole_array[ii];
// make a php_polygon from first contour
int CPolyLine::MakePhpPoly()
{
FreePhpPoly();
int nv = GetContourEnd( 0 );
for( int iv = 0; iv <= nv; iv++ )
m_php_poly->addv( GetX( iv ), GetY( iv ) );
m_php_poly->getFirst()->m_id = 1;
return 0;
return n_ext_cont;
}
void CPolyLine::FreePhpPoly()
/** Function AddPolygonsToBoolEng
* and edges contours to a kbool engine, preparing a boolean op between polygons
* @param aStart_contour: starting contour number (-1 = all, 0 is the outlines of zone, > 1 = holes in zone
* @param aEnd_contour: ending contour number (-1 = all after aStart_contour)
* @param arc_array: arc converted to poly segments (NULL if not exists)
* @param aBooleng : pointer on a bool engine (handle a set of polygons)
* @param aGroup : group to fill (aGroup = GROUP_A or GROUP_B) operations are made between GROUP_A and GROUP_B
*/
int CPolyLine::AddPolygonsToBoolEng( Bool_Engine* aBooleng,
GroupType aGroup,
int aStart_contour,
int aEnd_contour,
std::vector<CArc> * arc_array )
{
// delete all vertices
while( m_php_poly->m_cnt > 1 )
{
vertex* fv = m_php_poly->getFirst();
m_php_poly->del( fv->m_nextV );
}
delete m_php_poly->m_first;
m_php_poly->m_first = NULL;
m_php_poly->m_cnt = 0;
}
int count = 0;
if( (aGroup != GROUP_A) && (aGroup != GROUP_B ) )
return 0; //Error !
// Use the php clipping lib to clip this poly against poly
//
void CPolyLine::ClipPhpPolygon( int php_op, CPolyLine* poly )
{
Undraw();
poly->MakePhpPoly();
MakePhpPoly();
polygon* p = m_php_poly->boolean( poly->m_php_poly, php_op );
poly->FreePhpPoly();
FreePhpPoly();
MakeKboolPoly( aStart_contour, aEnd_contour, arc_array );
if( p )
while( m_Kbool_Poly_Engine->StartPolygonGet() )
{
// now screw with the PolyLine
corner.clear();
side_style.clear();
do
if( aBooleng->StartPolygonAdd( GROUP_A ) )
{
vertex* v = p->getFirst();
Start( m_layer, to_int( v->X() ), to_int( v->Y() ), m_HatchStyle );
do
while( m_Kbool_Poly_Engine->PolygonHasMorePoints() )
{
vertex* n = v->Next();
AppendCorner( to_int( v->X() ), to_int( (v->Y()) ) );
v = n;
} while( v->id() != p->getFirst()->id() );
Close();
int x = m_Kbool_Poly_Engine->GetPolygonXPoint();
int y = m_Kbool_Poly_Engine->GetPolygonYPoint();
aBooleng->AddPoint( x, y );
count++;
}
// p = p->NextPoly();
delete p;
p = NULL;
} while( p );
aBooleng->EndPolygonAdd();
}
m_Kbool_Poly_Engine->EndPolygonGet();
}
Draw();
}
#endif
int CPolyLine::MakePolygonFromAreaOutlines( int icontour, std::vector<CArc> * arc_array )
{
#ifdef USE_GPC_POLY_LIB
return MakeGpcPoly( icontour, arc_array );
#endif
#ifdef USE_GPL_POLY_LIB
return MakePhpPoly( );
#endif
}
delete m_Kbool_Poly_Engine;
m_Kbool_Poly_Engine = NULL;
void CPolyLine::FreePolygon()
{
#ifdef USE_GPC_POLY_LIB
FreeGpcPoly();
#endif
#ifdef USE_GPL_POLY_LIB
FreePhpPoly();
#endif
}
int CPolyLine::NormalizeAreaOutlines( std::vector<CPolyLine*> * pa, bool bRetainArcs )
{
#ifdef USE_GPC_POLY_LIB
return NormalizeWithGpc( pa, bRetainArcs );
#endif
#ifdef USE_GPL_POLY_LIB
#warning NormalizeAreaOutlines with GPL lib must be finished (TODO)
return 1;
#endif
return count;
}
#ifdef USE_GPC_POLY_LIB
/** Function MakeGpcPoly
* make a gpc_polygon for a closed polyline contour
/** Function MakeKboolPoly
* fill a kbool engine with a closed polyline contour
* approximates arcs with multiple straight-line segments
* @param icontour : if icontour = -1, make polygon with all contours,
* @param aStart_contour: starting contour number (-1 = all, 0 is the outlines of zone, > 1 = holes in zone
* @param aEnd_contour: ending contour number (-1 = all after aStart_contour)
* combining intersecting contours if possible
* @param arc_array : return data on arcs in arc_array
* @param arc_array : return corners computed from arcs approximations in arc_array
* @return error: 0 if Ok, 1 if error
*/
int CPolyLine::MakeGpcPoly( int icontour, std::vector<CArc> * arc_array )
int CPolyLine::MakeKboolPoly( int aStart_contour, int aEnd_contour, std::vector<CArc> * arc_array )
{
if( m_gpc_poly->num_contours )
FreeGpcPoly();
if( !GetClosed() && (icontour == (GetNumContours() - 1) || icontour == -1) )
if( m_Kbool_Poly_Engine )
{
delete m_Kbool_Poly_Engine;
m_Kbool_Poly_Engine = NULL;
}
if( !GetClosed() && (aStart_contour == (GetNumContours() - 1) || aStart_contour == -1) )
return 1; // error
// initialize m_gpc_poly
m_gpc_poly->num_contours = 0;
m_gpc_poly->hole = NULL;
m_gpc_poly->contour = NULL;
int n_arcs = 0;
int first_contour = icontour;
int last_contour = icontour;
if( icontour == -1 )
int first_contour = aStart_contour;
int last_contour = aEnd_contour;
if( aStart_contour == -1 )
{
first_contour = 0;
last_contour = GetNumContours() - 1;
}
if( aEnd_contour == -1 )
{
last_contour = GetNumContours() - 1;
}
if( arc_array )
arc_array->clear();
int iarc = 0;
for( int icont = first_contour; icont<=last_contour; icont++ )
{
// make gpc_polygon for this contour
gpc_polygon* gpc = new gpc_polygon;
gpc->num_contours = 0;
gpc->hole = NULL;
gpc->contour = NULL;
// Fill a kbool engine for this contour,
// and combine it with previous contours
Bool_Engine* booleng = new Bool_Engine();
ArmBoolEng( booleng );
if( m_Kbool_Poly_Engine ) // a previous contour exists. Put it in new engine
{
while( m_Kbool_Poly_Engine->StartPolygonGet() )
{
if( booleng->StartPolygonAdd( GROUP_A ) )
{
while( m_Kbool_Poly_Engine->PolygonHasMorePoints() )
{
int x = m_Kbool_Poly_Engine->GetPolygonXPoint();
int y = m_Kbool_Poly_Engine->GetPolygonYPoint();
booleng->AddPoint( x, y );
}
booleng->EndPolygonAdd();
}
m_Kbool_Poly_Engine->EndPolygonGet();
}
}
// first, calculate number of vertices in contour
int n_vertices = 0;
int ic_st = GetContourStart( icont );
int ic_end = GetContourEnd( icont );
if( !booleng->StartPolygonAdd( GROUP_B ) )
{
wxASSERT( 0 );
return 1; //error
}
for( int ic = ic_st; ic<=ic_end; ic++ )
{
int style = side_style[ic];
......@@ -353,10 +339,7 @@ int CPolyLine::MakeGpcPoly( int icontour, std::vector<CArc> * arc_array )
}
}
// now create gcp_vertex_list for this contour
gpc_vertex_list* g_v_list = new gpc_vertex_list;
g_v_list->vertex = (gpc_vertex*) calloc( sizeof(gpc_vertex), n_vertices );
g_v_list->num_vertices = n_vertices;
// now enter this contour to booleng
int ivtx = 0;
for( int ic = ic_st; ic<=ic_end; ic++ )
{
......@@ -376,8 +359,7 @@ int CPolyLine::MakeGpcPoly( int icontour, std::vector<CArc> * arc_array )
}
if( style == STRAIGHT )
{
g_v_list->vertex[ivtx].x = x1;
g_v_list->vertex[ivtx].y = y1;
booleng->AddPoint( x1, y1 );
ivtx++;
}
else
......@@ -480,8 +462,7 @@ int CPolyLine::MakeGpcPoly( int icontour, std::vector<CArc> * arc_array )
x = x1;
y = y1;
}
g_v_list->vertex[ivtx].x = x;
g_v_list->vertex[ivtx].y = y;
booleng->AddPoint( x1, y1 );
ivtx++;
}
}
......@@ -490,42 +471,93 @@ int CPolyLine::MakeGpcPoly( int icontour, std::vector<CArc> * arc_array )
if( n_vertices != ivtx )
wxASSERT( 0 );
// add vertex_list to gpc
gpc_add_contour( gpc, g_v_list, 0 );
// close list added to the bool engine
booleng->EndPolygonAdd();
/* now combine polygon to the previous polygons.
* note: the first polygon is the outline contour, and others are holes inside the first polygon
* The first polygon is ORed with nothing, but is is a trick to sort corners (vertex)
* clockwise with the kbool engine.
* Others polygons are substract to the outline and corners will be ordered counter clockwise
* by the kbool engine
*/
if( aStart_contour <= 0 && icont != 0 ) // substract hole to outside ( if the outline contour is take in account)
{
booleng->Do_Operation( BOOL_A_SUB_B );
}
else // add outside or add holes if we do not use the outline contour
{
booleng->Do_Operation( BOOL_OR );
}
// now clip m_gpc_poly with gpc, put new poly into result
gpc_polygon* result = new gpc_polygon;
if( icontour == -1 && icont != 0 )
gpc_polygon_clip( GPC_DIFF, m_gpc_poly, gpc, result ); // hole
else
gpc_polygon_clip( GPC_UNION, m_gpc_poly, gpc, result ); // outside
// now copy result to m_gpc_poly
gpc_free_polygon( m_gpc_poly );
delete m_gpc_poly;
m_gpc_poly = result;
gpc_free_polygon( gpc );
delete gpc;
free( g_v_list->vertex );
free( g_v_list );
if( m_Kbool_Poly_Engine )
delete m_Kbool_Poly_Engine;
m_Kbool_Poly_Engine = booleng;
}
return 0;
}
void CPolyLine::FreeGpcPoly()
/** Function ArmBoolEng
* Initialise parameters used in kbool
* @param aBooleng = pointer to the Bool_Engine to initialise
* @param aConvertHoles = mode for holes when a boolean operation is made
* true: holes are linked into outer contours by double overlapping segments
* false: holes are not linked: in this mode contours are added clockwise
* and polygons added counter clockwise are holes
*/
void ArmBoolEng( Bool_Engine* aBooleng, bool aConvertHoles )
{
if( m_gpc_poly->num_contours )
// set some global vals to arm the boolean engine
double DGRID = 1000; // round coordinate X or Y value in calculations to this
double MARGE = 0.001; // snap with in this range points to lines in the intersection routines
// should always be > DGRID a MARGE >= 10*DGRID is oke
// this is also used to remove small segments and to decide when
// two segments are in line.
double CORRECTIONFACTOR = 500.0; // correct the polygons by this number
double CORRECTIONABER = 1.0; // the accuracy for the rounded shapes used in correction
double ROUNDFACTOR = 1.5; // when will we round the correction shape to a circle
double SMOOTHABER = 10.0; // accuracy when smoothing a polygon
double MAXLINEMERGE = 1000.0; // leave as is, segments of this length in smoothen
// DGRID is only meant to make fractional parts of input data which
// are doubles, part of the integers used in vertexes within the boolean algorithm.
// Within the algorithm all input data is multiplied with DGRID
// space for extra intersection inside the boolean algorithms
// only change this if there are problems
int GRID = 10000;
aBooleng->SetMarge( MARGE );
aBooleng->SetGrid( GRID );
aBooleng->SetDGrid( DGRID );
aBooleng->SetCorrectionFactor( CORRECTIONFACTOR );
aBooleng->SetCorrectionAber( CORRECTIONABER );
aBooleng->SetSmoothAber( SMOOTHABER );
aBooleng->SetMaxlinemerge( MAXLINEMERGE );
aBooleng->SetRoundfactor( ROUNDFACTOR );
if( aConvertHoles )
{
aBooleng->SetLinkHoles( true ); // holes will be connected by double overlapping segments
aBooleng->SetOrientationEntryMode( false ); // all polygons are contours, not holes
}
else
{
delete m_gpc_poly->contour->vertex;
delete m_gpc_poly->contour;
delete m_gpc_poly->hole;
aBooleng->SetLinkHoles( false ); // holes will not ce connected by double overlapping segments
aBooleng->SetOrientationEntryMode( true ); // holes are entered counter clockwise
}
m_gpc_poly->num_contours = 0;
}
#endif
int CPolyLine::NormalizeAreaOutlines( std::vector<CPolyLine*> * pa, bool bRetainArcs )
{
return NormalizeWithKbool( pa, bRetainArcs );
}
// Restore arcs to a polygon where they were replaced with steps
// If pa != NULL, also use polygons in pa array
......@@ -548,8 +580,9 @@ int CPolyLine::RestoreArcs( std::vector<CArc> * arc_array, std::vector<CPolyLine
poly = (*pa)[ip - 1];
poly->Undraw();
for( int ic = 0; ic<poly->GetNumCorners(); ic++ )
poly->SetUtility( ic, 0 ); // clear utility flag
poly->SetUtility( ic, 0 );
// clear utility flag
}
// find arcs and replace them
......@@ -1181,19 +1214,20 @@ void CPolyLine::Hatch()
if( corner[ic].end_contour || ( ic == (int) (corner.size() - 1) ) )
{
ok = FindLineSegmentIntersection( a, slope,
corner[ic].x, corner[ic].y,
corner[i_start_contour].x, corner[i_start_contour].y,
side_style[ic],
&x, &y, &x2, &y2 );
corner[ic].x, corner[ic].y,
corner[i_start_contour].x,
corner[i_start_contour].y,
side_style[ic],
&x, &y, &x2, &y2 );
i_start_contour = ic + 1;
}
else
{
ok = FindLineSegmentIntersection( a, slope,
corner[ic].x, corner[ic].y,
corner[ic + 1].x, corner[ic + 1].y,
side_style[ic],
&x, &y, &x2, &y2 );
corner[ic].x, corner[ic].y,
corner[ic + 1].x, corner[ic + 1].y,
side_style[ic],
&x, &y, &x2, &y2 );
}
if( ok )
{
......@@ -1267,11 +1301,12 @@ void CPolyLine::Hatch()
double y2 = yy[ip + 1] - dx * slope;
m_HatchLines.push_back( CSegment( xx[ip], yy[ip], to_int( x1 ), to_int( y1 ) ) );
m_HatchLines.push_back( CSegment( xx[ip + 1], yy[ip + 1], to_int( x2 ),
to_int( y2 ) ) );
to_int( y2 ) ) );
}
}
} // end for
}
// end for
}
}
......@@ -1309,16 +1344,16 @@ bool CPolyLine::TestPointInside( int x, int y )
int ok;
if( ic == istart )
ok = FindLineSegmentIntersection( a, slope,
corner[iend].x, corner[iend].y,
corner[istart].x, corner[istart].y,
side_style[corner.size() - 1],
&x, &y, &x2, &y2 );
corner[iend].x, corner[iend].y,
corner[istart].x, corner[istart].y,
side_style[corner.size() - 1],
&x, &y, &x2, &y2 );
else
ok = FindLineSegmentIntersection( a, slope,
corner[ic - 1].x, corner[ic - 1].y,
corner[ic].x, corner[ic].y,
side_style[ic - 1],
&x, &y, &x2, &y2 );
corner[ic - 1].x, corner[ic - 1].y,
corner[ic].x, corner[ic].y,
side_style[ic - 1],
&x, &y, &x2, &y2 );
if( ok )
{
xx[npts] = (int) x;
......@@ -1393,16 +1428,16 @@ bool CPolyLine::TestPointInsideContour( int icont, int x, int y )
int ok;
if( ic == istart )
ok = FindLineSegmentIntersection( a, slope,
corner[iend].x, corner[iend].y,
corner[istart].x, corner[istart].y,
side_style[corner.size() - 1],
&x, &y, &x2, &y2 );
corner[iend].x, corner[iend].y,
corner[istart].x, corner[istart].y,
side_style[corner.size() - 1],
&x, &y, &x2, &y2 );
else
ok = FindLineSegmentIntersection( a, slope,
corner[ic - 1].x, corner[ic - 1].y,
corner[ic].x, corner[ic].y,
side_style[ic - 1],
&x, &y, &x2, &y2 );
corner[ic - 1].x, corner[ic - 1].y,
corner[ic].x, corner[ic].y,
side_style[ic - 1],
&x, &y, &x2, &y2 );
if( ok )
{
xx[npts] = (int) x;
......@@ -1455,12 +1490,6 @@ void CPolyLine::Copy( CPolyLine* src )
// copy side styles
for( unsigned ii = 0; ii < src->side_style.size(); ii++ )
side_style.push_back( src->side_style[ii] );
#ifdef USE_GPC_POLY_LIB
// don't copy the Gpc_poly, just clear the old one
FreeGpcPoly();
#endif
}
......@@ -1632,9 +1661,9 @@ void CPolyLine::AddContourForPadClearance( int type,
}
AppendCorner( to_int( x + corner_x ), to_int( y + corner_y ), STRAIGHT, 0 );
AppendCorner( to_int( x + r * cos( th1 ) ), to_int( y + r * sin(
th1 ) ), STRAIGHT, 0 );
th1 ) ), STRAIGHT, 0 );
AppendCorner( to_int( x + r * cos( th2 ) ), to_int( y + r * sin(
th2 ) ), ARC_CCW, 0 );
th2 ) ), ARC_CCW, 0 );
Close( STRAIGHT );
}
}
......
// PolyLine.h ... definition of CPolyLine class
//
// A polyline contains one or more contours, where each contour
// is defined by a list of corners and side-styles
......@@ -16,150 +17,214 @@
#include <vector>
#define USE_GPC_POLY_LIB
//#define USE_GPL_POLY_LIB
#include "kbool/include/booleng.h"
#include "freepcbDisplayList.h"
#include "pad_shapes.h"
#include "defs-macros.h"
#include "GenericPolygonClipperLibrary.h"
#include "php_polygon.h"
#include "php_polygon_vertex.h"
/** Function ArmBoolEng
* Initialise parameters used in kbool
* @param aBooleng = pointer to the Bool_Engine to initialise
* @param aConvertHoles = mode for holes when a boolean operation is made
* true: holes are linked into outer contours by double overlapping segments
* false: holes are not linked: in this mode contours are added clockwise
* and polygons added counter clockwise are holes
*/
void ArmBoolEng( Bool_Engine* aBooleng, bool aConvertHoles = false);
#include "PolyLine2Kicad.h"
#define PCBU_PER_MIL 10
#define NM_PER_MIL 10 // 25400
#include "freepcbDisplayList.h"
#include "math_for_graphics.h"
#define to_int( x ) (int) round( (x) )
#ifndef min
#define min( x1, x2 ) ( (x1) > (x2) ) ? (x2) : (x1)
#endif
#ifndef max
#define max( x1, x2 ) ( (x1) > (x2) ) ? (x1) : (x2)
#endif
class CSegment {
class CRect
{
public:
int xi, yi, xf, yf;
CSegment() {};
CSegment(int x0, int y0, int x1, int y1) {
xi = x0; yi = y0; xf = x1; yf = y1; }
int left, right, top, bottom;
};
class CArc {
class CPoint
{
public:
int x, y;
public:
enum{ MAX_STEP = 50*25400 }; // max step is 20 mils
enum{ MIN_STEPS = 18 }; // min step is 5 degrees
int style;
int xi, yi, xf, yf;
int n_steps; // number of straight-line segments in gpc_poly
bool bFound;
CPoint( void ) { x = y = 0; };
CPoint( int i, int j ) { x = i; y = j; };
};
class CPolyPt
class CSegment
{
public:
CPolyPt( int qx=0, int qy=0, bool qf=FALSE )
{ x=qx; y=qy; end_contour=qf; utility = 0; };
int x;
int y;
bool end_contour;
int utility;
int xi, yi, xf, yf;
CSegment() { };
CSegment( int x0, int y0, int x1, int y1 )
{
xi = x0; yi = y0; xf = x1; yf = y1;
}
};
class CPolyLine
#include "math_for_graphics.h"
class CArc
{
public:
enum { STRAIGHT, ARC_CW, ARC_CCW }; // side styles
enum { NO_HATCH, DIAGONAL_FULL, DIAGONAL_EDGE }; // hatch styles
// constructors/destructor
CPolyLine();
~CPolyLine();
// functions for modifying polyline
void Start( int layer, int x, int y, int hatch );
void AppendCorner( int x, int y, int style = STRAIGHT, bool bDraw=TRUE );
void InsertCorner( int ic, int x, int y );
void DeleteCorner( int ic, bool bDraw=TRUE );
void MoveCorner( int ic, int x, int y );
void Close( int style = STRAIGHT, bool bDraw=TRUE );
void RemoveContour( int icont );
void RemoveAllContours( void );
// drawing functions
void Undraw();
void Draw( );
void Hatch();
void MoveOrigin( int x_off, int y_off );
// misc. functions
CRect GetBounds();
CRect GetCornerBounds();
CRect GetCornerBounds( int icont );
void Copy( CPolyLine * src );
bool TestPointInside( int x, int y );
bool TestPointInsideContour( int icont, int x, int y );
bool IsCutoutContour( int icont );
void AppendArc( int xi, int yi, int xf, int yf, int xc, int yc, int num );
// access functions
int GetLayer() { return m_layer;}
int GetNumCorners();
int GetNumSides();
int GetClosed();
int GetNumContours();
int GetContour( int ic );
int GetContourStart( int icont );
int GetContourEnd( int icont );
int GetContourSize( int icont );
int GetX( int ic );
int GetY( int ic );
int GetEndContour( int ic );
int GetUtility( int ic ){ return corner[ic].utility; };
void SetUtility( int ic, int utility ){ corner[ic].utility = utility; };
int GetSideStyle( int is );
int GetHatchStyle(){ return m_HatchStyle; }
void SetHatch( int hatch ){ Undraw(); m_HatchStyle = hatch; Draw(); };
void SetX( int ic, int x );
void SetY( int ic, int y );
void SetEndContour( int ic, bool end_contour );
void SetSideStyle( int is, int style );
int RestoreArcs( std::vector<CArc> * arc_array, std::vector<CPolyLine*> * pa=NULL );
CPolyLine * MakePolylineForPad( int type, int x, int y, int w, int l, int r, int angle );
void AddContourForPadClearance( int type, int x, int y, int w,
int l, int r, int angle, int fill_clearance,
int hole_w, int hole_clearance, bool bThermal=FALSE, int spoke_w=0 );
int MakePolygonFromAreaOutlines( int icontour, std::vector<CArc> * arc_array );
void FreePolygon();
int NormalizeAreaOutlines( std::vector<CPolyLine*> * pa=NULL, bool bRetainArcs=FALSE );
#ifdef USE_GPC_POLY_LIB
// GPC functions
int MakeGpcPoly( int icontour=0, std::vector<CArc> * arc_array=NULL );
void FreeGpcPoly();
gpc_polygon * GetGpcPoly(){ return m_gpc_poly; };
int NormalizeWithGpc( std::vector<CPolyLine*> * pa=NULL, bool bRetainArcs=FALSE );
#endif
enum { MAX_STEP = 50 * 25400 }; // max step is 20 mils
enum { MIN_STEPS = 18 }; // min step is 5 degrees
int style;
int xi, yi, xf, yf;
int n_steps; // number of straight-line segments in gpc_poly
bool bFound;
};
class CPolyPt
{
public:
CPolyPt( int qx = 0, int qy = 0, bool qf = FALSE )
{ x = qx; y = qy; end_contour = qf; utility = 0; };
int x;
int y;
bool end_contour;
int utility;
};
// PHP functions
#ifdef USE_GPL_POLY_LIB
int MakePhpPoly();
void FreePhpPoly();
void ClipPhpPolygon( int php_op, CPolyLine * poly );
polygon * GetPhpPoly(){ return m_php_poly; };
#endif
class CPolyLine
{
public:
enum { STRAIGHT, ARC_CW, ARC_CCW }; // side styles
enum { NO_HATCH, DIAGONAL_FULL, DIAGONAL_EDGE }; // hatch styles
// constructors/destructor
CPolyLine();
~CPolyLine();
// functions for modifying polyline
void Start( int layer, int x, int y, int hatch );
void AppendCorner( int x, int y, int style = STRAIGHT, bool bDraw = TRUE );
void InsertCorner( int ic, int x, int y );
void DeleteCorner( int ic, bool bDraw = TRUE );
void MoveCorner( int ic, int x, int y );
void Close( int style = STRAIGHT, bool bDraw = TRUE );
void RemoveContour( int icont );
void RemoveAllContours( void );
// drawing functions
void Undraw();
void Draw();
void Hatch();
void MoveOrigin( int x_off, int y_off );
// misc. functions
CRect GetBounds();
CRect GetCornerBounds();
CRect GetCornerBounds( int icont );
void Copy( CPolyLine* src );
bool TestPointInside( int x, int y );
bool TestPointInsideContour( int icont, int x, int y );
bool IsCutoutContour( int icont );
void AppendArc( int xi, int yi, int xf, int yf, int xc, int yc, int num );
// access functions
int GetLayer() { return m_layer; }
int GetNumCorners();
int GetNumSides();
int GetClosed();
int GetNumContours();
int GetContour( int ic );
int GetContourStart( int icont );
int GetContourEnd( int icont );
int GetContourSize( int icont );
int GetX( int ic );
int GetY( int ic );
int GetEndContour( int ic );
int GetUtility( int ic ) { return corner[ic].utility; };
void SetUtility( int ic, int utility ) { corner[ic].utility = utility; };
int GetSideStyle( int is );
int GetHatchStyle() { return m_HatchStyle; }
void SetHatch( int hatch ) { Undraw(); m_HatchStyle = hatch; Draw(); };
void SetX( int ic, int x );
void SetY( int ic, int y );
void SetEndContour( int ic, bool end_contour );
void SetSideStyle( int is, int style );
int RestoreArcs( std::vector<CArc> * arc_array, std::vector<CPolyLine*> * pa = NULL );
CPolyLine* MakePolylineForPad( int type, int x, int y, int w, int l, int r, int angle );
void AddContourForPadClearance( int type,
int x,
int y,
int w,
int l,
int r,
int angle,
int fill_clearance,
int hole_w,
int hole_clearance,
bool bThermal = FALSE,
int spoke_w = 0 );
int NormalizeAreaOutlines( std::vector<CPolyLine*> * pa = NULL,
bool bRetainArcs = FALSE );
// KBOOL functions
/** Function AddPolygonsToBoolEng
* and edges contours to a kbool engine, preparing a boolean op between polygons
* @param aStart_contour: starting contour number (-1 = all, 0 is the outlines of zone, > 1 = holes in zone
* @param aEnd_contour: ending contour number (-1 = all after aStart_contour)
* @param arc_array: arc connverted to poly (NULL if not exists)
* @param aBooleng : pointer on a bool engine (handle a set of polygons)
* @param aGroup : group to fill (aGroup = GROUP_A or GROUP_B) operations are made between GROUP_A and GROUP_B
*/
int AddPolygonsToBoolEng( Bool_Engine* aBooleng,
GroupType aGroup,
int aStart_contour = -1,
int aEnd_contour = -1,
std::vector<CArc> * arc_array = NULL );
/** Function MakeKboolPoly
* fill a kbool engine with a closed polyline contour
* approximates arcs with multiple straight-line segments
* @param aStart_contour: starting contour number (-1 = all, 0 is the outlines of zone, > 1 = holes in zone
* @param aEnd_contour: ending contour number (-1 = all after aStart_contour)
* combining intersecting contours if possible
* @param arc_array : return data on arcs in arc_array
* @return error: 0 if Ok, 1 if error
*/
int MakeKboolPoly( int aStart_contour = -1, int aEnd_contour = -1, std::vector<CArc> * arc_array = NULL );
/** Function NormalizeWithKbool
* Use the Kbool Library to clip contours: if outlines are crossing, the self-crossing polygon
* is converted in 2 or more non self-crossing polygons
* If this results in new polygons, return them as std::vector pa
* @param pa: pointer on a std::vector<CPolyLine*> to store extra polylines
* @param bRetainArcs == TRUE, try to retain arcs in polys
* @return number of external contours, or -1 if error
*/
int NormalizeWithKbool( std::vector<CPolyLine*> * pa, bool bRetainArcs );
private:
int m_layer; // layer to draw on
int m_Width; // lines width when drawing. Provided but not really used
int utility;
int m_layer; // layer to draw on
int m_Width; // lines width when drawing. Provided but not really used
int utility;
public:
std::vector <CPolyPt> corner; // array of points for corners
std::vector <int> side_style; // array of styles for sides
int m_HatchStyle; // hatch style, see enum above
std::vector <CSegment> m_HatchLines; // hatch lines
std::vector <CPolyPt> corner; // array of points for corners
std::vector <int> side_style; // array of styles for sides
int m_HatchStyle; // hatch style, see enum above
std::vector <CSegment> m_HatchLines; // hatch lines
private:
gpc_polygon * m_gpc_poly; // polygon in gpc format
polygon * m_php_poly;
bool bDrawn;
Bool_Engine * m_Kbool_Poly_Engine; // polygons set in kbool engine data
bool bDrawn;
};
#endif // #ifndef POLYLINE_H
#endif // #ifndef POLYLINE_H
// PolyLine.h ... definition of CPolyLine class
//
// A polyline contains one or more contours, where each contour
// is defined by a list of corners and side-styles
// There may be multiple contours in a polyline.
// The last contour may be open or closed, any others must be closed.
// All of the corners and side-styles are concatenated into 2 arrays,
// separated by setting the end_contour flag of the last corner of
// each contour.
//
// When used for copper areas, the first contour is the outer edge
// of the area, subsequent ones are "holes" in the copper.
#ifndef POLYLINE2KICAD_H
#define POLYLINE2KICAD_H
#define PCBU_PER_MIL 10
#define NM_PER_MIL 10 // 25400
#include "pad_shapes.h"
class CRect {
public:
int left, right, top, bottom;
};
class CPoint {
public:
int x, y;
public:
CPoint(void) { x = y = 0;};
CPoint(int i, int j) { x = i; y = j;};
};
#endif // #ifndef POLYLINE2KICAD_H
/**********************/
/* Some usual defines */
/**********************/
#ifndef DEFS_MACROS_H
#define DEFS_MACROS_H
#ifndef BOOL
#define BOOL bool
#endif
#ifndef FALSE
#define FALSE false
#endif
#ifndef TRUE
#define TRUE true
#endif
#ifndef NULL
#define NULL 0
#endif
#ifndef abs
#define abs(x) (((x) >=0) ? (x) : (-(x)))
#endif
#ifndef min
#define min(x,y) (((x) <= (y)) ? (x) : (y))
#endif
#ifndef max
#define max(x,y) (((x) >= (y)) ? (x) : (y))
#endif
#define TRACE printf
#endif // ifndef DEFS_MACROS_H
PROJECT( kbool )
SUBDIRS( src samples )
/*! \file kbool/include/kbool/_dl_itr.cpp
\brief Double Linked list with Iterators on list
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: _dl_itr.cpp,v 1.1 2005/05/24 19:13:35 titato Exp $
*/
#ifdef __GNUG__
#pragma implementation
#endif
#ifdef __UNIX__
#include "kbool/include/_dl_itr.h"
#endif
//=======================================================================
// implementation class DL_Node
//=======================================================================
/*! \class DL_Node
* This class is used in the class DL_List to contain the items of the list. This can be a
* pointer to an object or the object itself. The class contains a next and a previous pointer
* to connect the nodes in the list. \n
* class Dtype | Object stored at the node
*/
/*!
Construct a node for a list object
\param it Item the node will contain
*/
template <class Dtype>
DL_Node<Dtype>::DL_Node(Dtype it) // + init nodeitem
:_item(it)
{}
/*!
Template constructor no contents
Construct a node for a list object
*/
template <class Dtype>
DL_Node<Dtype>::DL_Node()
:_item(0)
{}
/*!
Destruct a node object
*/
template <class Dtype>
DL_Node<Dtype>::~DL_Node()
{
}
//=======================================================================
// implementation class DL_List
//=======================================================================
/*! \class DL_List
* class is the base class for implementing a double linked list. The Root node marks the begining and end of the list. The
* lists consists of nodes double linked with a next and previous pointer DL_Node The nodes are cyclic connected to the root
* node. The list is meant to be used with an iterator class, to traverse the nodes. More then 1 iterator can be attached to the
* list. The list keeps track of the number of iterators that are attached to it. Depending on this certain operations are allowed
* are not. For instance a node can only be deleted if there is only one iterator attached to the list.
* class | Dtype | Object contaning List Nodes
*/
/*!
Construct a node object
\par Example:
How to construct a list of type integer:
\code
DL_List<int> * a_list = new DL_List<int>();
\endcode
*/
template <class Dtype>
DL_List<Dtype>::DL_List()
:_nbitems(0), _iterlevel(0)
{
_root = new DL_Node<Dtype>();
_root->_next=_root;
_root->_prev=_root;
}
/*!
//Destruct a list object
\par Example:
How to construct a list of type integer:
\code
DL_List<int> * a_list = new DL_List<int>(); # declaration and allocation
delete a_list; #delete it (must have no iterators attached to it)
\endcode
*/
template <class Dtype>
DL_List<Dtype>::~DL_List()
{
if (_iterlevel != 0)
throw Bool_Engine_Error("DL_List::~DL_List()\n_iterlevel > 0 ","list error", 0, 1);
remove_all(false);
delete _root;
_root=0;_nbitems=0; //reset memory used (no lost pointers)
}
/*!
Error report for list error inside DL_List class
the error function is used internally in the list class to report errors,
the function will generate a message based on the error code.
Then an exeption will be generated using the global booleng class instance. \n
tcarg: class | Dtype | item object in list
\par Example
to call error from inside an DL_List class
\code
Error("remove_all",ITER_GT_O);
\endcode
\param function string that generated this error
\param error code to generate a message for
*/
template <class Dtype>
void DL_List<Dtype>::Error(const char* function,Lerror a_error)
{
char buf[100];
strcpy(buf,"DL_List<Dtype>::");
strcat(buf,function);
switch (a_error)
{
case NO_MES: strcat(buf,""); break;
case EMPTY: strcat(buf,"list is empty"); break;
case ITER_GT_0: strcat(buf,"more then zero iter"); break;
case NO_LIST: strcat(buf,"no list attached"); break;
case SAME_LIST: strcat(buf,"same list not allowed"); break;
case AC_ITER_LIST_OTHER: strcat(buf,"iter not allowed on other list"); break;
default: strcat(buf,"unhandled error"); break;
}
throw Bool_Engine_Error(buf,"list error", 0, 1);
}
/*!
is list empty (contains items or not)? \n
class | Dtype | item object in list
\return returns true is list is empty else false
\par Example
too see if list is empty
\code
DL_List<int> _intlist; #create a list of integers
if (_intlist.Empty())
cout << "empty";
\endcode
*/
template <class Dtype>
bool DL_List<Dtype>::empty()
{
return(bool)(_nbitems==0);
}
/*!
number of items in list \n
class | Dtype | item object in list
\return return number of items in the list
\par Example
too see if list contains only one object
\code
DL_List <int> _intlist; #create a list of integers
if (_intlist.count() == 1)
cout << "one object in list";
\endcode
*/
template <class Dtype>
int DL_List<Dtype>::count()
{
return _nbitems;
}
/*!
remove all objects from the list\n
class | Dtype | item object in list
\note
The objects itself are not deleted, only removed from the list.
The user is responsible for memory management.
\note
The iterator level must be zero to be able to use this function,
else an error will be generated
\note
Use this function if an iterator is not needed to do more complex things.
This will save time, since the iterator does not have to be created.
\par Example
too insert integer a and b into list and remove_all directly
\code
DL_List<int> _intlist; #create a list of integers
int a=123;
int b=345;
_intlist.insbegin(a);
_intlist.insbegin(b);
_intlist.remove_all();
\endcode
*/
template <class Dtype>
void DL_List<Dtype>::remove_all( bool deleteObject )
{
if (_iterlevel > 0 )
Error("remove_all()",ITER_GT_0);
Dtype* obj;
DL_Node<Dtype> *node;
for (int i=0; i<_nbitems; i++)
{
node = _root->_next;
_root->_next = node->_next;
if ( deleteObject == true )
{
obj=(Dtype*)(node->_item);
delete obj;
}
delete node;
}
_nbitems=0;_iterlevel=0; //reset memory used (no lost pointers)
_root->_prev=_root;
}
/*!
remove the object at the begin of the list (head).
\note
The object itself is not deleted, only removed from the list.
The user is responsible for memory management.
\note
The iterator level must be zero to be able to use this function, else an error will be generated
\note
The list must contain objects, else an error will be generated.
\note
Use this function if an iterator is not needed to do more complex things. This will save time, since the iterator does not
have to be created.
\par Example:
too insert integer a at begin of list and remove it directly.
\code
DL_List<int> _intlist; #create a list of integers
int a=123;
_intlist.insbegin(a)
_intlist.removehead();
\endcode
*/
template <class Dtype>
void DL_List<Dtype>::removehead()
{
if (_iterlevel > 0 )
Error("removehead()",ITER_GT_0);
if(_nbitems==0)
Error("removehead()",EMPTY);
DL_Node<Dtype>* node=_root->_next;
node->_prev->_next = node->_next; // update forward link
node->_next->_prev = node->_prev; // update backward link
_nbitems--;
delete node; // delete list node
}
/*!
remove the object at the begin of the list (head).
\note
- The object itself is not deleted, only removed from the list.
The user is responsible for memory management.
- The iterator level must be zero to be able to use this function,
else an error will be generated
- The list must contain objects, else an error will be generated.
- Use this function if an iterator is not needed to do more complex things.
This will save time, since the iterator does not have to be created.
\par Example:
too insert integer a at end of list and remove it directly.
\code
DL_List<int> _intlist; #create a list of integers
int a=123;
_intlist.insend(a)
_intlist.removetail();
\endcode
*/
template <class Dtype>
void DL_List<Dtype>::removetail()
{
if (_iterlevel > 0)
Error("removetail()",ITER_GT_0);
if (_nbitems==0)
Error("removehead()",EMPTY);
DL_Node<Dtype>* node=_root->_prev;
node->_prev->_next = node->_next; // update forward link
node->_next->_prev = node->_prev; // update backward link
_nbitems--;
delete node; // delete list node
}
/*!
insert the object given at the end of the list, after tail
\note
The iterator level must be zero to be able to use this function,
else an error will be generated
\note
Use this function if an iterator is not needed to do more complex things.
This will save time, since the iterator does not have to be created.
\par Example:
too insert integer a at end of list
\code
DL_List<int> _intlist; #create a list of integers
int a=123;
_intlist.insend(a)
\endcode
\param newitem an object for which the template list was generated
*/
template <class Dtype>
DL_Node<Dtype>* DL_List<Dtype>::insend(Dtype newitem)
{
if (_iterlevel > 0)
Error("insend()",ITER_GT_0);
DL_Node<Dtype>* newnode = new DL_Node<Dtype>(newitem);
newnode ->_next = _root;
newnode ->_prev = _root->_prev;
_root->_prev->_next = newnode;
_root->_prev = newnode;
_nbitems++;
return newnode;
}
/*!
insert the object given at the begin of the list, before head
\note
The iterator level must be zero to be able to use this function,
else an error will be generated
\note
Use this function if an iterator is not needed to do more complex things.
This will save time, since the iterator does not have to be created.
\par Example:
too insert integer a at begin of list
\code
DL_List<int> _intlist; #create a list of integers
int a=123;
_intlist.insbegin(a)
\endcode
\param newitem an object for which the template list was generated
*/
template <class Dtype>
DL_Node<Dtype>* DL_List<Dtype>::insbegin(Dtype newitem)
{
if (_iterlevel > 0)
Error("insbegin()",ITER_GT_0);
DL_Node<Dtype>* newnode = new DL_Node<Dtype>(newitem);
newnode ->_prev = _root;
newnode ->_next = _root->_next;
_root->_next->_prev = newnode;
_root->_next = newnode;
_nbitems++;
return newnode;
}
/*!
get head item
\return returns the object at the head of the list.
\par Example:
too insert integer a and b into list and make c be the value of b
which is at head of list|
\code
DL_List<int> _intlist; #create a list of integers
int a=123;
int b=345;
int c;
_intlist.insbegin(a)
_intlist.insbegin(b)
c=_intlist.headitem()
\endcode
*/
template <class Dtype>
Dtype DL_List<Dtype>::headitem()
{
return _root->_next->_item;
}
/*!
get tail item
\return returns the object at the tail/end of the list.
\par Example:
too insert integer a and b into list and make c be the value of b which
is at the tail of list
\code
DL_List<int> _intlist; #create a list of integers
int a=123;
int b=345;
int c;
_intlist.insbegin(a)
_intlist.insbegin(b)
c=_intlist.headitem()
\endcode
*/
template <class Dtype>
Dtype DL_List<Dtype>::tailitem()
{
return _root->_prev->_item;
}
/*!
* \note
The iterator level must be zero to be able to use this function, else an error will be generated
* \note The list may not be the same list as this list
* \param otherlist the list to take the items from
*/
template <class Dtype>
void DL_List<Dtype>::takeover(DL_List<Dtype>* otherlist)
{
if (otherlist==0)
Error("takeover(DL_List*)",NO_LIST);
// no iterators allowed on otherlist
if (otherlist->_iterlevel > 0)
Error("takeover(DL_List*)",AC_ITER_LIST_OTHER);
// otherlist not this list
else if (otherlist == this)
Error("takeover(DL_List*)",SAME_LIST);
if (otherlist->_nbitems == 0)
return;
//link other list into this list at the end
_root->_prev->_next=otherlist->_root->_next;
otherlist->_root->_next->_prev=_root->_prev;
otherlist->_root->_prev->_next=_root;
_root->_prev=otherlist->_root->_prev;
//empty other list
_nbitems+=otherlist->_nbitems;
otherlist->_nbitems=0;
otherlist->_root->_next=otherlist->_root;
otherlist->_root->_prev=otherlist->_root;
}
//=======================================================================
// implementation class DL_Iter
//=======================================================================
/*! \class DL_Iter
template iterator for any list/node type\n
This class is the base class to attach/instantiate an iterator on a double linked list. \n
DL_List The iterator is used to traverse and perform functions on the nodes of a list. \n
More then 1 iterator can be attached to a list. The list keeps track of the
number of iterators that are attached to it. \n
Depending on this certain operations are allowed are not. For instance a node can
only be deleted if there is only one iterator attached to the list. \n
class | Dtype | Object for traversing a DL_List of the same Dtype
// \par Example
to insert integer a and b into list and remove_all directly using an iterator
\code
DL_List<int>* a_list = new DL_List<int>(); // declaration and allocation
int a=123;
int b=345;
{
DL_Iter<int>* a_listiter=new DL_Iter<int>(a_list);
a_listiter->insbegin(a)
a_listiter->insbegin(b)
a_listiter->remove_all()
} //to destruct the iterator before the list is deleted
delete a_list; #delete it (must have no iterators attached to it)
\endcode
*/
/*!
Error report for list error inside DL_Iter class
the error function is used internally in the iterator class to report errors,
the function will generate a message based on the error code.
Then an exception will be generated using the global booleng class instance.|
\par Example
to call error from inside an DL_List class|
\code
Error("remove_all",ITER_GT_O);
\endcode
\param function: function string that generated this error
\param a_error: error code to generate a message for
*/
template <class Dtype>
void DL_Iter<Dtype>::Error(const char* function,Lerror a_error)
{
char buf[100];
strcpy(buf,"DL_Iter<Dtype>::");
strcat(buf,function);
switch (a_error)
{
case NO_MES: strcat(buf,""); break;
case NO_LIST: strcat(buf,"no list attached"); break;
case NO_LIST_OTHER: strcat(buf,"no list on other iter"); break;
case AC_ITER_LIST_OTHER: strcat(buf,"iter not allowed on other list"); break;
case SAME_LIST: strcat(buf,"same list not allowed"); break;
case NOT_SAME_LIST: strcat(buf,"must be same list"); break;
case ITER_GT_1: strcat(buf,"more then one iter"); break;
case ITER_HITROOT: strcat(buf,"iter at root"); break;
case NO_ITEM: strcat(buf,"no item at current"); break;
case NO_NEXT: strcat(buf,"no next after current"); break;
case NO_PREV: strcat(buf,"no prev before current"); break;
case EMPTY: strcat(buf,"list is empty"); break;
case NOT_ALLOW: strcat(buf,"not allowed"); break;
case ITER_NEG: strcat(buf,"to much iters deleted"); break;
default: strcat(buf,"unhandled error"); break;
}
throw Bool_Engine_Error(buf,"list error", 0, 1);
}
/*!
Construct an iterator object for a given list of type Dtype \n
tcarg: class | Dtype | list item object
\par Example
How to construct a list of type integer and an iterator for it:
\code
DL_List<int>* IntegerList;
IntegerList = new DL_List<int>();
DL_Iter<int>* a_listiter=new DL_Iter<int>(IntegerList);
\endcode
\param newlist: list for the iterator
*/
template <class Dtype>
DL_Iter<Dtype>:: DL_Iter(DL_List<Dtype>* newlist)
:_list(newlist), _current(RT)
{
_list->_iterlevel++; // add 1 to DL_Iters on list
}
/*!
This constructs an iterator for a list using an other iterator on the same list,
The new iterator will be pointing to the same list item as the other iterator.\n
tcarg: class | Dtype | list item object
\par Example
How to construct a list of type integer and a second iterator for it:|
\code
DL_List<int>* IntegerList;
IntegerList = new DL_List<int>();
DL_Iter<int>* a_listiter=new DL_Iter<int>(IntegerList);
DL_Iter<int>* a_secondlistiter=new DL_Iter<int>(a_listiter);
\endcode
\param otheriter other iterator on same list
*/
template <class Dtype>
DL_Iter<Dtype>:: DL_Iter(DL_Iter* otheriter)
{
if (otheriter->_current==0)
Error("DL_Iter(otheriter)",NO_LIST_OTHER);
_list=otheriter->_list;
_list->_iterlevel++; // add 1 to DL_Iters on List
_current=otheriter->_current;
}
/*!
This constructs an iterator for a list of a given type, the list does not have to exist.
Later on when a list is constructed,the iterator can be attached to it.
This way an iterator to a specific list can be made static to a class, and can be used
for several lists at the same time. \n
tcarg: class | Dtype | list item object
\par Example
How to construct an iterator, without having a list first.
This constructs an iterator for a list of the given type, but the list thus not yet exist.
\code
DL_Iter<int>* a_iter=new DL_Iter<int>();
DL_List<int>* IntegerList;
IntegerList = new DL_List<int>();
a_iter.Attach(IntegerList);
a_iter.insend(123);
a_iter.Detach();
\endcode
*/
template <class Dtype>
DL_Iter<Dtype>:: DL_Iter()
:_list(0), _current(0)
{
}
/*!
destruct an iterator for a list of a given type.
*/
template <class Dtype>
DL_Iter<Dtype>::~DL_Iter()
{
if (_current==0)
return;
_list->_iterlevel--; // decrease iterators
if (_list->_iterlevel < 0)
Error("~DL_Iter()",ITER_NEG);
}
/*!
This attaches an iterator to a list of a given type, the list must exist.
This way an iterator to a specific list can be made
static to a class, and can be used for several lists at the same time.\n
!tcarg: class | Dtype | list item object
\par Example
How to construct an iterator, without having a list first, and attach an iterator later:|
\code
DL_Iter<int>* a_iter=new DL_Iter<int>();
DL_List<int>* IntegerList;
IntegerList = new DL_List<int>();
a_iter.Attach(IntegerList);
a_iter.insend(123);
a_iter.Detach();
\endcode
\param newlist the list to attached the iterator to
*/
template <class Dtype>
void DL_Iter<Dtype>::Attach(DL_List<Dtype>* newlist)
{
if (_current!=0)
Error("Attach(list)",NOT_ALLOW);
_list=newlist;
_current=HD;
_list->_iterlevel++; // add 1 to DL_Iters on list
}
/*!
This detaches an iterator from a list of a given type, the list must exist.
This way an iterator to a specific list can be made static to a class,
and can be used for several lists at the same time. \n
!tcarg: class | Dtype | list item object
\par Example:
How to construct an iterator, without having a list first, and attach an iterator later:
\code
DL_Iter<int>* a_iter=new DL_Iter<int>();
DL_List<int>* IntegerList;
IntegerList = new DL_List<int>();
a_iter.Attach(IntegerList);
a_iter.insend(123);
a_iter.Detach();
\endcode
\param newlist: the list to attached the iterator to
*/
template <class Dtype>
void DL_Iter<Dtype>::Detach()
{
if (_current==0)
Error("Attach()",NO_LIST);
_list->_iterlevel--; // subtract 1 from DL_Iters on list
_list=0;
_current=0;
}
/*
// copy pointers to items from other list
template <class Dtype> void DL_Iter<Dtype>::merge(DL_List<Dtype>* otherlist)
{
DL_Node* node=otherlist->HD; //can be 0 if empty
for(int i=0; i<otherlist->NB; i++)
{
insend(node->new_item); // insert item at end
node=node->_next; // next item of otherlist
}
}
*/
/*
//call Dtype::mfp for each item
template <class Dtype>
void DL_Iter<Dtype>::foreach_mf(void (Dtype::*mfp)())
{
DL_Node<Dtype>* node=HD; //can be 0 if empty
for(int i=0; i< NB; i++)
{
((node->_item).*mfp)();
node=node->_next;
}
}
*/
/*! call given function for each item*/
template <class Dtype>
void DL_Iter<Dtype>::foreach_f(void (*fp) (Dtype n) )
{
DL_Node<Dtype>* node=HD; //can be 0 if empty
for(int i=0; i< NB; i++)
{
fp (node->_item);
node=node->_next;
}
}
/*!
to move all objects in a list to the list of the iterator.
\note
The iterator level must be one to be able to use this function,
else an error will be generated
\note
The list may not be the same list as the iterator list
\par Example
to take over all items in _intlist|
\code
DL_List<int> _intlist; #create a list of integers
DL_List<int> _intlist2; #create a list of integers
int a=123;
DL_Iter<int>* a_listiter2=new DL_Iter<int>(&_intlist2);
_intlist->insend(a) // insert at end
a_listiter2->takeover(_intlist)
\endcode
\param otherlist the list to take the items from
*/
template <class Dtype>
void DL_Iter<Dtype>::takeover(DL_List<Dtype>* otherlist)
{
if (_current==0)
Error("takeover(DL_List*)",NO_LIST);
// no iterators allowed on otherlist
if (otherlist->_iterlevel > 0)
Error("takeover(DL_List*)",AC_ITER_LIST_OTHER);
// otherlist not this list
else if (otherlist == _list)
Error("takeover(DL_List*)",SAME_LIST);
if (otherlist->_nbitems == 0)
return;
//link other list into this list at the end
TL->_next=otherlist->_root->_next;
otherlist->_root->_next->_prev=TL;
otherlist->_root->_prev->_next=RT;
TL=otherlist->_root->_prev;
//empty other list
NB+=otherlist->_nbitems;
otherlist->_nbitems=0;
otherlist->_root->_next=otherlist->_root;
otherlist->_root->_prev=otherlist->_root;
}
/*!
to move all objects in a list (using iterator of that list) to the list of the iterator.
\note
The iterator level for both iterators must be one to be able to use this function,
\note
else an error will be generated
\note
The list may not be the same list as the iterator list
\par Example
to take over all items in a_listiter1 it's list|
\code
DL_List<int> _intlist; #create a list of integers
DL_List<int> _intlist2; #create a list of integers
int a=123;
DL_Iter<int>* a_listiter1=new DL_Iter<int>(&_intlist);
DL_Iter<int>* a_listiter2=new DL_Iter<int>(&_intlist2);
a_listiter1->insend(a) // insert at end
a_listiter2->takeover(a_listiter1)
\\!to move all objects in a list (using iterator of that list) to the list of the iterator
\endcode
\param otheriter: the iterator to take the items from
*/
template <class Dtype>
void DL_Iter<Dtype>::takeover(DL_Iter* otheriter)
{
if (otheriter->_current==0)
Error(" DL_Iter",NO_LIST_OTHER);
if (_current==0)
Error(" DL_Iter",NO_LIST);
// only one iterator allowed on other list?
if (otheriter->_list->_iterlevel > 1)
Error("takeover(DL_Iter*)",AC_ITER_LIST_OTHER);
// otherlist not this list?
else if (otheriter->_list == _list)
Error("takeover(DL_Iter*)",SAME_LIST);
if (otheriter->NB == 0)
return;
//link other list into this list at the end
TL->_next=otheriter->HD;
otheriter->HD->_prev=TL;
otheriter->TL->_next=RT;
TL=otheriter->TL;
//empty other iter & list
NB+=otheriter->NB;
otheriter->NB=0;
otheriter->HD=otheriter->RT;
otheriter->TL=otheriter->RT;
otheriter->_current=otheriter->RT;
}
/*!
to move maxcount objects in a list (using iterator of that list)
to the list of the iterator.
\note The iterator level for both iterators must be one to be able to use this function,
else an error will be generated
\note The list may not be the same list as the iterator list
\note If less then maxcount objects are available in the source iterator,
all of them are taken and no error will accur
\par Example
to take over 1 item from a_listiter1 it's list
\code
DL_List<int> _intlist; #create a list of integers
DL_List<int> _intlist2; #create a list of integers
int a=123;
DL_Iter<int>* a_listiter1=new DL_Iter<int>(&_intlist);
DL_Iter<int>* a_listiter2=new DL_Iter<int>(&_intlist2);
a_listiter1->insend(a) // insert at end
a_listiter2->takeover(a_listiter1,1);
//! to move maxcount objects in a list (using iterator of that list) to the list of the iterator
\endcode
\param otheriter the iterator to take the items from
\param maxcount maximum number of objects to take over
*/
template <class Dtype>
void DL_Iter<Dtype>::takeover(DL_Iter* otheriter, int maxcount)
{
if (otheriter->_current==0)
Error("takeover(DL_Iter*,int)",NO_LIST_OTHER);
if (_current==0)
Error("takeover(DL_Iter*,int)",NO_LIST);
if (otheriter->_list->_iterlevel > 1)
Error("takeover(DL_Iter*,int)",AC_ITER_LIST_OTHER);
else if (otheriter->_list == _list)
Error("takeover(DL_Iter*,int)",SAME_LIST);
if (maxcount<0)
Error("takeover(DL_Iter*,int), maxcount < 0",NO_MES);
if (otheriter->NB == 0)
return;
if (otheriter->NB <= maxcount)
{ //take it all
//link other list into this list at the end
TL->_next=otheriter->HD;
otheriter->HD->_prev=TL;
otheriter->TL->_next=RT;
TL=otheriter->TL;
//empty other iter & list
NB+=otheriter->NB;
otheriter->NB=0;
otheriter->HD=otheriter->RT;
otheriter->TL=otheriter->RT;
otheriter->_current=otheriter->RT;
}
else
{ //take maxcount elements from otheriter
//set cursor in otherlist to element maxcount
DL_Node<Dtype>* node;
if (NB/2 < maxcount)
{ // this is faster (1st half)
node=otheriter->HD;
for(int i=1; i<maxcount; i++)
node=node->_next;
}
else
{ // no, this is faster (2nd half)
node=otheriter->TL;
for(int i=NB; i>maxcount+1; i--)
node=node->_prev;
}
// link this->tail to other->head
if (NB>0)
{
TL->_next=otheriter->HD;
otheriter->HD->_prev=TL;
}
else // target is empty
{
HD=otheriter->HD;
otheriter->HD->_prev=RT;
}
// set other root to node-> next (after last to copy)
otheriter->HD=node->_next;
otheriter->HD->_prev=otheriter->RT;
// set this->tail to other->item()->prev (last element to be copied)
TL=node;
node->_next=RT;
// still need to update element counter
NB+=maxcount;
// update other list
otheriter->NB-=maxcount;
otheriter->_current=otheriter->HD; // other->current is moved to this!
}
}
/*!
put the iterator root object before the current iterator position in the list.
The current object will become the new head of the list.
\note The iterator level must be one to be able to use this function,
else an error will be generated
\par Example
move the root object to make the new head the old tail object|
\code
DL_List <int> _intlist; #create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(1234);
a_listiter->insend(2345);
a_listiter->insend(3456);
a_listiter->totail();
a_listiter->reset_head();
a_listiter->tohead(); //the new head will be at object 3456
\endcode
*/
template <class Dtype>
void DL_Iter<Dtype>::reset_head()
{
if (_current==0)
Error("reset_head()",NO_LIST);
if (_list->_iterlevel > 1 )
Error("reset_head()",ITER_GT_1);
if(_current==RT)
Error("reset head()",ITER_HITROOT);
//link out RT
HD->_prev=TL;
TL->_next=HD;
//link in RT before current
HD=_current;
TL=_current->_prev;
TL->_next=RT;
HD->_prev=RT;
}
/*!
put the iterator root object after the current iterator position in the list.
The current object will become the new tail of the list.
\note
The iterator level must be one to be able to use this function,
else an error will be generated
\par Example
move the root object to make the new tail the old head object
\code
DL_List <int> _intlist; #create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(1234);
a_listiter->insend(2345);
a_listiter->insend(3456);
a_listiter->tohead();
a_listiter->reset_tail();
a_listiter->totail(); //the new tail will be at object 1234
\endcode
*/
template <class Dtype>
void DL_Iter<Dtype>::reset_tail()
{
if (_current==0)
Error("reset_tail()",NO_LIST);
if (_list->_iterlevel > 1 )
Error("reset_tail()",ITER_GT_1);
if(_current==RT)
Error("reset head()",ITER_HITROOT);
//link out RT
HD->_prev=TL;
TL->_next=HD;
//link in RT after current
TL=_current;
HD=_current->_next;
HD->_prev=RT;
TL->_next=RT;
}
/*!
is list empty (contains items or not)?
\return returns true is list is empty else false
\par exmaple:
too see if list is empty
\code
DL_List<int> _intlist; #create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
if (a_listiter->Empty())
cout << "empty"
\endcode
*/
template <class Dtype>
bool DL_Iter<Dtype>::empty()
{
if (_current==0)
Error("empty()",NO_LIST);
return(bool)(NB==0);
}
/*!
is the iterator at the root of the list.
\note Traversing the list in a certain direction using a while loop,
the end can be tested with this function.
\return returns true if the iterator is at the root of the list (after the last/tail/head object), else false.
\par example:
to traverse in both directions|
\code
DL_List <int> _intlist; #create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->tohead();
//traverse forwards
while ( ! a_listiter->hitroot())
{
cout << "The item =" << a_listiter->item();
a_listiter++; //goto next object
}
a_listiter->totail();
//traverse backwards
while ( ! a_listiter->hitroot())
{
cout << "The item =" << a_listiter->item();
a_listiter--; //goto next object
}
\endcode
*/
template <class Dtype>
bool DL_Iter<Dtype>::hitroot()
{
if (_current==0)
Error("hitroot()",NO_LIST);
return(bool)(_current == RT);
}
/*!
is the iterator at the head of the list.
\return returns true if the iterator is at the head object of the list, else false.
\par exmaple:
too see the object at the head
\code
DL_List <int> _intlist; #create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->tohead();
if (a_listiter->athead())
cout << "at the head The item =" << a_listiter->item();
\endcode
*/
template <class Dtype>
bool DL_Iter<Dtype>::athead()
{
if (_current==0)
Error("athead()",NO_LIST);
return(bool)(_current == HD);
}
/*!
is the iterator at the tail of the list.
\return returns true if the iterator is at the tail object of the list,
else false.
\par Example
too see the object at the tail|
\code
DL_List <int> _intlist; #create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->totail();
if (a_listiter->attail())
cout << "at the tail The item =" << a_listiter->item();
\endcode
*/
template <class Dtype>
bool DL_Iter<Dtype>::attail()
{
if (_current==0)
Error("attail()",NO_LIST);
return(bool)(_current == TL);
}
/*!
does the iterator/list contain the given object
\return returns true if the iterator/list contains the given object in the list, else false.
\par Example
too see if the object is already in the list
\code
DL_List <int> _intlist; #create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(1234);
if (a_listiter->has(1234))
cout << "yes it does";
\endcode
\param otheritem item to search for
*/
template <class Dtype>
bool DL_Iter<Dtype>::has(Dtype otheritem)
{
if (_current==0)
Error("has()",NO_LIST);
DL_Node<Dtype>* node=HD; //can be 0 if empty
for(int i=0; i<NB; i++)
{ if (node->_item == otheritem)
return true;
node=node->_next;
}
return false;
}
/*!
number of items in list
\return number of items in the list
\par Example:
to see if a list contains only one object
\code
DL_List <int> _intlist; #create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
if (a_listiter->count() == 1)
cout << "one object in list";
\endcode
*/
template <class Dtype>
int DL_Iter<Dtype>::count()
{
if (_current==0)
Error("count()",NO_LIST);
return NB;
}
/*!
go to first item, if list is empty goto hite
\par Example
set iterator to head of list
\code
DL_List <int> _intlist; #create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(1234);
a_listiter->tohead();
\endcode
*/
template <class Dtype>
void DL_Iter<Dtype>::tohead()
{
if (_current==0)
Error("tohead()",NO_LIST);
_current=HD;
}
/*!
go to last item, if list is empty goto hite
\par Example
set iterator to tail of list
\code
DL_List <int> _intlist; #create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(1234);
a_listiter->totail();
\endcode
*/
template <class Dtype>
void DL_Iter<Dtype>::totail()
{
if (_current==0)
Error("totail()",NO_LIST);
_current=TL;
}
/*!
set the iterator position to the root (empty dummy) object in the list.
\par Example
set iterator to root of list and iterate
\code
DL_List <int> _intlist; #create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(1234);
a_listiter->toroot();
while (a_listiter->iterate())
cout << a_listiter->item();
\endcode
*/
template <class Dtype>
void DL_Iter<Dtype>::toroot()
{
if (_current==0)
Error("toroot()",NO_LIST);
_current=RT;
}
/*!
set the iterator position to next object in the list ( can be the root also)(prefix).
\par Example
how to iterate backwards
\code
DL_List <int> _intlist; //create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(1234);
a_listiter->tohead();
while (!a_listiter->hitroot())
{
cout << a_listiter->item();
_listiter++;
}
\endcode
*/
template <class Dtype>
void DL_Iter<Dtype>::operator++(void)
{
if (_current==0)
Error("operator++()",NO_LIST);
_current=_current->_next;
}
/*!
set the iterator position to next object in the list ( can be the root also)(prefix).
\par Example
how to iterate backwards
\code
DL_List <int> _intlist; //create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(1234);
a_listiter->tohead();
while (!a_listiter->hitroot())
{
cout << a_listiter->item();
++_listiter;
}
\endcode
*/
template <class Dtype>
void DL_Iter<Dtype>::operator++(int)
{
if (_current==0)
Error("operator++(int)",NO_LIST);
_current=_current->_next;
}
/*!
set the iterator position to previous object in the list ( can be the root also)(prefix).
\par Example
how to iterate backwards
\code
DL_List <int> _intlist; //create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(1234);
a_listiter->totail();
while (!a_listiter->hitroot())
{
cout << a_listiter->item();
_listiter--;
}
\endcode
*/
template <class Dtype>
void DL_Iter<Dtype>::operator--(void)
{
if (_current==0)
Error("operator++()",NO_LIST);
_current=_current->_prev;
}
/*!
set the iterator position to previous object in the list ( can be the root also)(prefix).
\par Example
how to iterate backwards
\code
DL_List <int> _intlist; //create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(1234);
a_listiter->totail();
while (!a_listiter->hitroot())
{
cout << a_listiter->item();
--_listiter;
}
\endcode
*/
template <class Dtype>
void DL_Iter<Dtype>::operator--(int)
{
if (_current==0)
Error("operator++(int)",NO_LIST);
_current=_current->_prev;
}
/*!
set the iterator position n objects in the next direction ( can be the root also).
\par Example:
how to set iterator 2 items forward
\code
DL_List <int> _intlist; #create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(1234);
a_listiter->tohead();
a_listiter>>2;//at root now
\endcode
\param n go n places forward
*/
template <class Dtype>
void DL_Iter<Dtype>::operator>>(int n)
{
if (_current==0)
Error("operator>>()",NO_LIST);
for(int i=0; i<n; i++)
_current=_current->_next;
}
/*!
set the iterator position n objects in the previous direction ( can be the root also).
\par Example:
how to set iterator 2 items backwards
\code
DL_List <int> _intlist; #create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(1234);
a_listiter->totail();
a_listiter<<2;//at root now
\endcode
\param n go n places back
*/
template <class Dtype>
void DL_Iter<Dtype>::operator<<(int n)
{
if (_current==0)
Error("operator<<()",NO_LIST);
for(int i=0; i<n; i++)
_current=_current->_prev;
}
/*!
put the iterator at the position of the given object in the list.
\return returns true if the object was in the list, else false
\par Example:
goto element 2345
\code
DL_List <int> _intlist; #create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(1234);
a_listiter->insend(2345);
a_listiter->insend(3456);
a_listiter->toitem(2345); template <class Dtype>
\endcode
*/
template <class Dtype>
bool DL_Iter<Dtype>::toitem(Dtype item)
{
if (_current==0)
Error("toitem(item)",NO_LIST);
DL_Node<Dtype>* node=HD; //can be 0 if empty
for(int i=0; i<NB; i++)
{ if (node->_item == item)
{
_current = node;
return true;
}
node=node->_next;
}
return false;
}
/*!
put the iterator at the same position as the given iterator in the list.
\par Example:
goto element 2345 and let a_listiter2 point to the same position
\code
DL_List <int> _intlist; #create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
DL_Iter<int>* a_listiter2=new DL_Iter<int>(&_intlist);
a_listiter->insend(1234);
a_listiter->insend(2345);
a_listiter->insend(3456);
a_listiter->toitem(2345);
a_listiter2->toiter(a_listiter2);
\endcode
\param otheriter other iterator to let this iterator point to.
*/
template <class Dtype>
void DL_Iter<Dtype>::toiter(DL_Iter *otheriter)
{
if (otheriter->_current==0)
Error("toiter(otheriter)",NO_LIST);
// both iters must have the same list
if (_list != otheriter->_list)
Error("toiter(otheriter)",NOT_SAME_LIST);
_current = otheriter->_current;
}
/*!
put the iterator at the position of the given object in the list.
\note DO NOT use this function. Normally you will not be able to address the nodes in a list.
\return returns true if the node was in the list, else false
\param othernode a node to let this iterator point to.
*/
template <class Dtype>
bool DL_Iter<Dtype>::tonode(DL_Node<Dtype> *othernode)
{
DL_Node<Dtype>* node=HD; //can be 0 if empty //node is a temporary cursor
for(int i=0; i<NB; i++)
{ if (node == othernode)
{
_current = othernode;
return true;
}
node=node->_next;
}
return false;
}
/*!
advance the iterator one position in the next direction in the list.
\return returns true if not at the end/root of the list else false.
\note This function combines iteration and testing for the end of
the list in one.
\note Therefore we do not have to advance the iterator ourselves.
\note
The iterator is first put to the next object, before testing for the end of the list. |
This is why we need to start at the root element in general usage.
\par Example
iterate through all the items in a list
\code
DL_List <int> _intlist; #create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(1234);
a_listiter->insend(2345);
a_listiter->insend(3456);
a_listiter->tobegin(2345);
while (a_listiter->iterate())
{ cout << a_listiter->item(); }
\endcode
*/
template <class Dtype>
bool DL_Iter<Dtype>::iterate(void)
{
if (_current==0)
Error("iterate()",NO_LIST);
_current=_current->_next;
if (_current==RT)
return false;
return true;
}
/*!
To get the item at the current iterator position
\return returns the object where the iterator is pointing to at the moment.
\note
If the iterator is at the root of the list an error will be generated,
since there is no item there.
\par Example:
get the element at the head of the list|
\code
DL_List <int> _intlist; //create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(1234);
a_listiter->tohead();
int theitem=a_listiter->item();
\endcode
*/
template <class Dtype>
Dtype DL_Iter<Dtype>::item()
{
if (_current==0)
Error("item()",NO_LIST);
if (_current==RT)
Error("item()",NO_ITEM);
return _current->_item;
}
//! get the node at iterater position
template <class Dtype>
DL_Node<Dtype>* DL_Iter<Dtype>::node()
{
if (_current==0)
Error("item()",NO_LIST);
if (_current==RT)
Error("item()",NO_ITEM);
return _current;
}
/*!
set the iterator position to next object in the list ( can be the root also).
\note Use this function inside a new class derived from DL_Iter.
*/
template <class Dtype>
void DL_Iter<Dtype>::next()
{
if (_current==0)
Error("item()",NO_LIST);
_current=_current->_next;
}
/*!
set the iterator position to next object in the list, if this would be the root object,
then set the iterator at the head object
\par Example
cycle the list twice
\code
DL_List <int> _intlist; #create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(1234);
a_listiter->insend(2345);
a_listiter->tohead();
int count=2*a_listiter->count();
while (count)
{
cout << a_listiter->item();
next_wrap();
count--;
}
\endcode
*/
template <class Dtype>
void DL_Iter<Dtype>::next_wrap()
{
if (_current==0)
Error("item()",NO_LIST);
_current=_current->_next;
if (_current==RT)
_current=_current->_next;
}
/*!
set the iterator position to previous object in the list ( can be the root also).
\note Use this function inside a new class derived from DL_Iter.
*/
template <class Dtype>
void DL_Iter<Dtype>::prev()
{
if (_current==0)
Error("item()",NO_LIST);
_current=_current->_prev;
}
/*!
set the iterator position to previous object in the list, if this would be the root object,
then set the iterator at the tail object
\par Example
cycle the list twice
\code
DL_List <int> _intlist; #create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(1234);
a_listiter->insend(2345);
a_listiter->totail();
int count=2*a_listiter->count();
while (count)
{
cout << a_listiter->item();
prev_wrap();
count--;
}
\endcode
*/
template <class Dtype>
void DL_Iter<Dtype>::prev_wrap()
{
if (_current==0)
Error("item()",NO_LIST);
_current=_current->_prev;
if (_current==RT)
_current=_current->_prev;
}
template <class Dtype>
void DL_Iter<Dtype>::remove_all()
{
if (_current==0)
Error("remove_all()",NO_LIST);
if (_list->_iterlevel > 1 )
Error("remove_all()",ITER_GT_1);
_list->_iterlevel--;
_list->remove_all();
_list->_iterlevel++;
_current=RT;
}
/*!
remove object at current iterator position from the list.
\note The object itself is not deleted, only removed from the list. The user is responsible for memory management.
\note The iterator level must be one to be able to use this function, else an error will be generated
\note The list must contain an object at the current iterator position, else an error will be generated.
\par Example:
to insert integer a at begin of list and remove it directly
\code
DL_List<int> _intlist; #create a list of integers
int a=123;
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insbegin(a);
a_listiter->tohead();
a_listiter->remove();
\endcode
*/
template <class Dtype>
void DL_Iter<Dtype>::remove()
{
if (_current==0)
Error("remove()",NO_LIST);
if (_list->_iterlevel > 1 )
Error("remove()",ITER_GT_1);
if (_current==RT)
Error("remove()",ITER_HITROOT);
DL_Node<Dtype>* node=_current;
_current=_current->_next;
node->_prev->_next = node->_next; // update forward link
node->_next->_prev = node->_prev; // update backward link
NB--;
delete node; // delete list node
}
/*!
remove the object at the begin of the list using an iterator
\note The object itself is not deleted, only removed from the list. The user is responsible for memory management.
\note The iterator level must be one to be able to use this function, else an error will be generated
\note The list must contain objects, else an error will be generated.
\note Use this function if an iterator is needed to do more complex things. Else use the list member functions directly.
\par Example:
to insert integer a at begin of list and remove it directly|
\code
DL_List<int> _intlist; #create a list of integers
int a=123;
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insbegin(a);
a_listiter->removehead();
\endcode
*/
template <class Dtype>
void DL_Iter<Dtype>::removehead()
{
if (_current==0)
Error("removehead()",NO_LIST);
if (_list->_iterlevel > 1 )
Error("removehead()",ITER_GT_1);
if(NB==0)
Error("removehead()",EMPTY);
if (_current==HD)
_current=_current->_next;
_list->_iterlevel--;
_list->removehead();
_list->_iterlevel++;
}
/*!
//remove the object at the end of the list using an iterator
\note The object itself is not deleted, only removed from the list. The user is responsible for memory management.
\note The iterator level must be one to be able to use this function, else an error will be generated
\note The list must contain objects, else an error will be generated.
\note Use this function if an iterator is needed to do more complex things. Else use the list member functions directly.
\par Example:
to insert integer a at end of list and remove it directly
\code
DL_List<int> _intlist; #create a list of integers
int a=123;
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(a);
a_listiter->removetail();
\endcode
*/
template <class Dtype>
void DL_Iter<Dtype>::removetail()
{
if (_current==0)
Error("removetail()",NO_LIST);
if (_list->_iterlevel > 1 )
Error("removetail()",ITER_GT_1);
if (NB==0)
Error("removehead()",EMPTY);
if (_current==TL)
_current=_current->_prev;
_list->_iterlevel--;
_list->removetail();
_list->_iterlevel++;
}
/*!
insert the object given at the end of the list
\note The iterator level must be one to be able to use this function, else an error will be generated
\note Use this function if an iterator is needed to do more complex things. Else use the list member functions directly.
\par Example:
to insert integer a at end of list|
\code
DL_List<int> _intlist; #create a list of integers
int a=123;
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(a);
\endcode
*/
template <class Dtype>
DL_Node<Dtype>* DL_Iter<Dtype>::insend(Dtype newitem)
{
if (_current==0)
Error("insend()",NO_LIST);
if (_list->_iterlevel > 1)
Error("insend()",ITER_GT_1);
_list->_iterlevel--;
DL_Node<Dtype>* ret = _list->insend(newitem);
_list->_iterlevel++;
return ret;
}
/*!
insert the object given at the begin of the list
\note The iterator level must be one to be able to use this function, else an error will be generated
\note Use this function if an iterator is needed to do more complex things. Else use the list member functions directly.
\par Example:
to insert integer a at begin of list|
\code
DL_List<int> _intlist; #create a list of integers
int a=123;
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insbegin(a);
\endcode
\param newitem an object for which the template list/iterator was generated
*/
template <class Dtype>
DL_Node<Dtype>* DL_Iter<Dtype>::insbegin(Dtype newitem)
{
if (_current==0)
Error("insbegin()",NO_LIST);
if (_list->_iterlevel > 1)
Error("insbegin()",ITER_GT_1);
_list->_iterlevel--;
DL_Node<Dtype>* ret = _list->insbegin(newitem);
_list->_iterlevel++;
return ret;
}
/*!
//insert the object given before the current position of the iterator in list
\note The iterator level must be one to be able to use this function, else an error will be generated
\par Example:
to insert integer before the iterator position in the list|
\code
DL_List<int> _intlist; #create a list of integers
int a=123;
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->totail();
a_listiter->insbefore(a); // insert before tail
\endcode
\param newitem an object for which the template list/iterator was generated
*/
template <class Dtype>
DL_Node<Dtype>* DL_Iter<Dtype>::insbefore(Dtype newitem)
{
if (_current==0)
Error("insbefore()",NO_LIST);
if (_list->_iterlevel > 1)
Error("insbefore()",ITER_GT_1);
DL_Node<Dtype>* newnode = new DL_Node<Dtype>(newitem);
newnode ->_next = _current;
_current->_prev->_next = newnode;
newnode ->_prev = _current->_prev;
_current->_prev = newnode;
NB++;
return newnode;
}
/*!
insert the object given after the current position of the iterator in list
\note The iterator level must be one to be able to use this function, else an error will be generated
\par Example: to insert integer after the iterator position in the list|
\code
DL_List<int> _intlist; #create a list of integers
int a=123;
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->tohead();
a_listiter->insafter(a); // insert after head
\endcode
\param newitem an object for which the template list/iterator was generated
*/
template <class Dtype>
DL_Node<Dtype>* DL_Iter<Dtype>::insafter(Dtype newitem)
{
if (_current==0)
Error("insafter()",NO_LIST);
if (_list->_iterlevel > 1)
Error("insafter()",ITER_GT_1);
DL_Node<Dtype>* newnode = new DL_Node<Dtype>(newitem);
newnode ->_next = _current->_next;
newnode ->_prev = _current;
_current->_next->_prev = newnode;
_current->_next = newnode;
NB++;
return newnode;
}
/*!
sort all items in the list according to the compare function.
when items need to be swapped to reach the right order the swap function will be called also.
\note There are no restrictions on the internal decision in the compare function when to return -1,0,1.
\note The swap function can be used to change items when they are swapped.
fcmp (function, fcmp)
\verbatim
Declaration: int (*fcmp) (Dtype,Dtype)
compare function pointer, the function takes two objects in the list. It must return -1, 0, 1, to sort the list in upgoing
order the function should return:
-1 is returned if the first object is bigger then the second.
0 is returned if the objects are equal.
1 is returned if the first object is smaller then the second.
To sort the list in downgoing order:
1 is returned if the first object is bigger then the second.
0 is returned if the objects are equal.
-1 is returned if the first object is smaller then the second.
fswap (function, fswap)
Declaration: void (*fswap) (Dtype,Dtype)
swap function pointer, the function takes two objects in the list. It will be called when the objects are swapped to
reach the right order. If it is NULL, it will not be called.
\endverbatim
\par Example: sort the list in upgoing order using cocktailsort and the function numbersorter|
\code
int numbersorter(int a,int b)
{
if(a < b) return(1);
else
if(a == b) return(0);
return(-1);
}
DL_List <int> _intlist; #create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(2345);
a_listiter->insend(3456);
a_listiter->insend(1234);
a_listiter->cocktailsort(numbersorter,NULL);
\endcode
\param fcmp sortfunction
\param fswap swapfunction
*/
template <class Dtype>
int DL_Iter<Dtype>::cocktailsort(int (*fcmp) (Dtype, Dtype), bool (*fswap)(Dtype, Dtype))
{
if (_current==0)
Error("cocktailsort()",NO_LIST);
if (NB <= 1)
return 0;
DL_Node<Dtype>* cursor;
Dtype swap;
int swapResult = 0;
// boven/ondergrens setten
DL_Node<Dtype> *bg = TL, *bgold = TL;
DL_Node<Dtype> *og = HD, *ogold = HD;
bool swapped = true;
// while swaping is done & lowerborder upperborder don't touch
while (swapped && (og!=bg))
{
swapped = false;
// BUBBELSLAG lowerborder--->> upperborder
cursor=og;
while(!(cursor == bgold))
{
// (current.next < current)?
if( fcmp(cursor->_next->_item, cursor->_item)==1)
{
// user function
if ( fswap != NULL )
if ( fswap(cursor->_item, cursor->_next->_item) )
swapResult++;
// update swap-flag en upperborder
swapped = true;
bg = cursor;
// swap the items of the nodes
swap = cursor->_item;
cursor->_item = cursor->_next->_item;
cursor->_next->_item = swap;
}
cursor=cursor->_next;
}// end bubbelslag
bgold = bg;
// BRICKSLAG lowerborder <<---upperborder
cursor=bg;
while(!(cursor == ogold))
{
// (current < current.next)?
if( fcmp(cursor->_item, cursor->_prev->_item)==1)
{
// user function
if ( fswap != NULL )
if ( fswap(cursor->_item, cursor->_prev->_item) )
swapResult++;
// update swap-flag and lowerborder
swapped = true;
og = cursor;
// swap de items van de nodes
swap = cursor->_item;
cursor->_item = cursor->_prev->_item;
cursor->_prev->_item = swap;
}
cursor=cursor->_prev;
}// end brickslag
ogold = og;
}// end while(ongesorteerd)
return swapResult;
}
/*!
sort all items in the list according to the compare function.
\note
There are no restrictions on the internal decision in the compare function when to return -1,0,1.
\note
For the mergesort function the objects will be swapped when the return value is -1.
\note
\verbatim
fcmp (function, fcmp)
Declaration: int (*fcmp) (Dtype,Dtype)
compare function pointer, the function takes two objects in the list. It must return -1, 0, 1, to sort the list in upgoing
order the function should return:
-1 is returned if the first object is bigger then the second.
0 is returned if the objects are equal.
1 is returned if the first object is smaller then the second.
To sort the list in downgoing order:
1 is returned if the first object is bigger then the second.
0 is returned if the objects are equal.
-1 is returned if the first object is smaller then the second.
\endverbatim
!tcarg: class | Dtype | list item object
\par example
sort the list in upgoing order using mergesort and the function numbersorter|
\code
int numbersorter(int a,int b)
{
if(a < b) return(1);
else
if(a == b) return(0);
return(-1);
}
DL_List <int> _intlist; #create a list of integers
DL_Iter<int>* a_listiter=new DL_Iter<int>(&_intlist);
a_listiter->insend(2345);
a_listiter->insend(3456);
a_listiter->insend(1234);
a_listiter->mergesort(numbersorter);
\endcode
*/
template <class Dtype>
void DL_Iter<Dtype>::mergesort(int (*fcmp) (Dtype, Dtype))
{
if (_current==0)
Error("mergesort()",NO_LIST);
mergesort_rec(fcmp, RT, NB);
}
template <class Dtype>
void DL_Iter<Dtype>::mergesort_rec(int (*fcmp)(Dtype,Dtype), DL_Node<Dtype> *RT1, int n1)
{
if (n1 > 1) //one element left then stop
{
DL_Node<Dtype> RT2;
int n2;
RT2._prev=RT1->_prev;
RT2._next=RT1->_next;
// goto middle
n2=n1;n1>>=1;n2-=n1;
for (int i=0; i <n1;i++)
RT2._next=RT2._next->_next;
//RT2 is at half
RT1->_prev->_next=&RT2;
RT2._prev=RT1->_prev;
RT1->_prev=RT2._next->_prev;
RT2._next->_prev->_next=RT1;
mergesort_rec(fcmp,RT1,n1);
mergesort_rec(fcmp,&RT2,n2);
mergetwo(fcmp,RT1,&RT2);
}
}
template <class Dtype>
void DL_Iter<Dtype>::mergetwo(int (*fcmp)(Dtype,Dtype), DL_Node<Dtype> *RT1,DL_Node<Dtype> *RT2)
{
DL_Node<Dtype> *c,*a,*b;
a=RT1->_next;b=RT2->_next;
c=RT1;
do
{
if (fcmp(a->_item , b->_item) > -1)
{ c->_next=a;a->_prev=c;c=a;a=a->_next;}
else
{ c->_next=b;b->_prev=c;c=b;b=b->_next;}
if (a == RT1)
{ c->_next=
b;b->_prev=c; //connect list b to the list made sofar
RT1->_prev=RT2->_prev;
RT1->_prev->_next=RT1;
break;
}
if (b == RT2)
{ c->_next=a;a->_prev=c; //connect list a to the list made sofar
break;
}
}
while (true);
}
//=======================================================================
// implementation class DL_StackIter
//=======================================================================
/*! \class DL_StackIter
* template class DL_StackIter class for stack iterator on DL_List
* template stack iterator for any list/node type \n
* This class is the base class to attach/instantiate a stack iterator on a double linked list
* DL_List. The stack iterator is used to push and pop objects
* to and from the beginning of a list.
* class | Dtype | Object for traversing a DL_List of the same Dtype
*\par Example
How to work with a stack iterator for a list of type integer \n
to push a and b, pop a into list and remove_all directly using a stack iterator
*
*\code DL_List<int>* a_list = new DL_List<int>();# declaration and allocation
*
* int a=123;
*
* int b=345;
*
* {
*
* DL_StackIter<int>* a_listiter=new DL_StackIter<int>(a_list);
*
* a_listiter->push(a)
*
* a_listiter->push(b)
*
* a_listiter->pop()
*
* a_listiter->remove_all()
*
* } //to destruct the iterator before the list is deleted
*
* delete a_list; #delete it (must have no iterators attached to it)
*\endcode
*/
// constructor
template <class Dtype>
DL_StackIter<Dtype>::DL_StackIter(DL_List<Dtype> *newlist)
:DL_Iter<Dtype>(newlist) // initialiseer BaseIter
{}
// destructor
template <class Dtype>
DL_StackIter<Dtype>::~DL_StackIter()
{
}
// plaats nieuw item op stack
template <class Dtype>
void DL_StackIter<Dtype>::push(Dtype newitem)
{
DL_Iter<Dtype>::insbegin(newitem);
}
// remove current item
template <class Dtype>
void DL_StackIter<Dtype>::remove_all()
{
DL_Iter<Dtype>::remove_all();
}
// is stack leeg?
template <class Dtype>
bool DL_StackIter<Dtype>::empty()
{
return DL_Iter<Dtype>::empty();
}
// aantal items op stack
template <class Dtype>
int DL_StackIter<Dtype>::count()
{
return DL_Iter<Dtype>::count();
}
// haal bovenste item van stack
template <class Dtype>
Dtype DL_StackIter<Dtype>::pop()
{
if(DL_Iter<Dtype>::empty())
this->Error("pop()",EMPTY);
DL_Iter<Dtype>::tohead();
Dtype temp = DL_Iter<Dtype>::item();
DL_Iter<Dtype>::removehead();
return temp;
}
//=======================================================================
// implementation class DL_SortIter
//=======================================================================
/*! \class DL_SortIter
* template class DL_SortIter
* class for sort iterator on DL_List
* template sort iterator for any list/node type
* This class is a derived class to attach/instantiate a sorted iterator on a double linked list
* DL_List. The iterator is used to insert items in sorted order into a list.
//!tcarg: class | Dtype | Object for traversing a DL_List of the same Dtype
*/
// constructor
template <class DType>
DL_SortIter<DType>::DL_SortIter(DL_List<DType>* nw_list, int (*new_func)(DType ,DType ))
:DL_Iter<DType>(nw_list), comparef(new_func)
{}
// destructor
template <class DType>
DL_SortIter<DType>::~DL_SortIter()
{}
// general function to insert item
template <class DType>
void DL_SortIter<DType>::insert(DType new_item)
{
DL_Node<DType>* cursor=this->_current; //can be 0 if empty //node is a temporary cursor
// if list is empty directly insert
if (DL_Iter<DType>::empty())
{
DL_Iter<DType>::insend(new_item);
}
else
{
// put new item left of item
DL_Iter<DType>::tohead();
while(!DL_Iter<DType>::hitroot())
{
if (!(*comparef)(DL_Iter<DType>::item(), new_item))
break;
DL_Iter<DType>::next();
}
//if at root
DL_Iter<DType>::insbefore(new_item);
}
this->_current=cursor; //set to old cursor position
}
template <class DType>
void DL_SortIter<DType>::sortitererror()
{
this->Error("sortiter()",NOT_ALLOW);
}
/*! \file kbool/include/kbool/_dl_itr.h
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: _dl_itr.h,v 1.1 2005/05/24 19:13:35 titato Exp $
*/
//! author="Klaas Holwerda"
/*
* Definitions of classes, for list implementation
* template list and iterator for any list node type
*/
#ifndef _DL_Iter_H
#define _DL_Iter_H
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma interface
#endif
#include <stdlib.h>
#include "../include/booleng.h"
#ifndef _STATUS_ENUM
#define _STATUS_ENUM
//!<enum Error codes for List and iterator class
enum Lerror {
NO_MES, /*!<No Message will be generated */
NO_LIST, /*!<List is not attached to the iterator*/
NO_LIST_OTHER, /*!<no attached list on other iter*/
AC_ITER_LIST_OTHER, /*!<iter not allowed on other list */
SAME_LIST, /*!<same list not allowed*/
NOT_SAME_LIST, /*!<must be same list*/
ITER_GT_1, /*!<more then one iteriter at root*/
ITER_GT_0, /*!<iter not allowed*/
ITER_HITROOT, /*!<iter at root*/
NO_ITEM, /*!<no item at current*/
NO_NEXT, /*!<no next after current*/
NO_PREV, /*!<no prev before current */
EMPTY, /*!<list is empty*/
NOT_ALLOW, /*!<not allowed*/
ITER_NEG /*!<to much iters deleted*/
};
#endif
#define SWAP(x,y,t)((t)=(x),(x)=(y),(y)=(t))
#define RT _list->_root
#define HD _list->_root->_next
#define TL _list->_root->_prev
#define NB _list->_nbitems
template <class Dtype> class DL_List;
template <class Dtype> class DL_Iter;
template <class Dtype> class DL_SortIter;
//! Template class DL_Node
template <class Dtype> class DL_Node
{
friend class DL_List<Dtype>;
friend class DL_Iter<Dtype>;
friend class DL_SortIter<Dtype>;
//!Public members
public:
//!Template constructor no contents
//!Construct a node for a list object
DL_Node();
//!constructor with init of Dtype
DL_Node( Dtype n );
//!Destructor
~DL_Node();
//!Public members
public:
//!data in node
Dtype _item;
//!pointer to next node
DL_Node* _next;
//!pointer to previous node
DL_Node* _prev;
};
//!Template class DL_List
template <class Dtype> class DL_List
{
friend class DL_Iter<Dtype>;
friend class DL_SortIter<Dtype>;
public:
//!Constructor
//!Construct a list object
//!!tcarg class | Dtype | list object
DL_List();
//!destructor
~DL_List();
//!Report off List Errors
void Error(const char* function,Lerror a_error);
//!Number of items in the list
int count();
//!Empty List?
bool empty();
//!insert the object given at the end of the list, after tail
DL_Node<Dtype>* insend( Dtype n );
//!insert the object given at the begin of the list, before head
DL_Node<Dtype>* insbegin( Dtype n );
//!remove the object at the begin of the list (head)
void removehead();
//! remove the object at the end of the list (tail)
void removetail();
//!remove all objects from the list
void remove_all( bool deleteObject = false );
//!Get the item at the head of the list
Dtype headitem();
//!Get the item at the tail of the list
Dtype tailitem();
//! to move all objects in a list to this list.
void takeover(DL_List<Dtype>* otherlist);
public:
//!the root node pointer of the list, the first and last node
//! in the list are connected to the root node. The root node is used
//! to detect the end / beginning of the list while traversing it.
DL_Node<Dtype>* _root;
//!the number of items in the list, if empty list it is 0
int _nbitems;
//!number of iterators on the list, Attaching or instantiating an iterator to list,
//! will increment this member, detaching and
//! destruction of iterator for a list will decrement this number
short int _iterlevel;
};
//! Template class DL_Iter for iterator on DL_List
template <class Dtype>
class DL_Iter
{
public:
//!Construct an iterator object for a given list of type Dtype
DL_Iter(DL_List<Dtype>* newlist);
//!Constructor of iterator for the same list as another iterator
DL_Iter(DL_Iter* otheriter);
//!Constructor without an attached list
DL_Iter();
//!destructor
~DL_Iter();
//!Report off Iterator Errors
void Error(const char* function,Lerror a_error);
//!This attaches an iterator to a list of a given type.
void Attach(DL_List<Dtype>* newlist);
//!This detaches an iterator from a list
void Detach();
//!execute given function for each item in the list/iterator
void foreach_f(void (*fp) (Dtype n) );
//! list mutations
//!insert after tail item
DL_Node<Dtype>* insend(Dtype n);
//!insert before head item
DL_Node<Dtype>* insbegin(Dtype n);
//!insert before current iterator position
DL_Node<Dtype>* insbefore(Dtype n);
//!insert after current iterator position
DL_Node<Dtype>* insafter(Dtype n);
//!to move all objects in a list to the list of the iterator.
void takeover(DL_List<Dtype>* otherlist);
//!to move all objects in a list (using iterator of that list) to the list of the iterator
void takeover(DL_Iter* otheriter);
//! to move maxcount objects in a list (using iterator of that list) to the list of the iterator
void takeover(DL_Iter* otheriter, int maxcount);
//!remove object at current iterator position from the list.
void remove();
//!Remove head item
void removehead();
//!Remove tail item
void removetail();
//!Remove all items
void remove_all();
/* void foreach_mf(void (Dtype::*mfp)() ); //call Dtype::mfp for each item */
//!is list empty (contains items or not)?
bool empty();
//!is iterator at root node (begin or end)?
bool hitroot();
//!is iterator at head/first node?
bool athead();
//!is iterator at tail/last node?
bool attail();
//!is given item member of the list
bool has(Dtype otheritem);
//!Number of items in the list
int count();
/* cursor movements */
//!go to last item, if list is empty goto hite
void totail();
//!go to first item, if list is empty goto hite
void tohead();
//!set the iterator position to the root (empty dummy) object in the list.
void toroot();
//! set the iterator position to next object in the list ( can be the root also).
void operator++ (void);
//!set iterator to next item (pre fix)
void operator++ (int);
//!set the iterator position to previous object in the list ( can be the root also)(postfix).
void operator-- (void);
//!set the iterator position to previous object in the list ( can be the root also)(pre fix).
void operator-- (int);
//!set the iterator position n objects in the next direction ( can be the root also).
void operator>> (int);
//!set the iterator position n objects in the previous direction ( can be the root also).
void operator<< (int);
//!set the iterator position to next object in the list, if this would be the root object,
//!then set the iterator at the head object
void next_wrap();
//!set the iterator position to previous object in the list, if this would be the root object,
//!then set the iterator at the tail object
void prev_wrap();
//!move root in order to make the current node the tail
void reset_tail();
//!move root in order to make the current node the head
void reset_head();
//!put the iterator at the position of the given object in the list.
bool toitem(Dtype);
//!put the iterator at the same position as the given iterator in the list.
void toiter(DL_Iter* otheriter);
//!put the iterator at the position of the given node in the list.
bool tonode(DL_Node<Dtype>*);
//!iterate through all items of the list
bool iterate(void);
//!To get the item at the current iterator position
Dtype item();
//! get node at iterator
DL_Node<Dtype>* node();
//!sort list with mergesort
void mergesort(int (*fcmp) (Dtype, Dtype));
//!sort list with cocktailsort
/*!
\return number of swaps done.
*/
int cocktailsort(int (*)(Dtype,Dtype), bool (*)(Dtype,Dtype)=NULL);
protected:
//!sort list with mergesort
void mergesort_rec(int (*fcmp)(Dtype,Dtype), DL_Node<Dtype> *RT1,int n);
//!sort list with mergesort
void mergetwo(int (*fcmp)(Dtype,Dtype), DL_Node<Dtype> *RT1,DL_Node<Dtype> *RT2);
//!set the iterator position to next object in the list ( can be the root also).
void next();
//!set the iterator position to previous object in the list ( can be the root also).
void prev();
//!the list for this iterator
DL_List<Dtype> *_list;
//!the current position of the iterator
DL_Node<Dtype> *_current;
};
//! template class DL_StackIter class for stack iterator on DL_List
template <class Dtype>
class DL_StackIter :protected DL_Iter<Dtype>
{
public:
//!Constructor of stack iterator for given list
DL_StackIter(DL_List<Dtype> *);
//!Constructor of stack iterator no list attached
DL_StackIter();
//!Destructor of stack iterator
~DL_StackIter();
//!Remove all items from the stack
void remove_all();
//!push given item on the stack
void push(Dtype n);
//!get last inserted item from stack
Dtype pop();
//!is stack empty?
bool empty();
//!number of items on the stack
int count();
};
//!template class DL_SortIter
template <class DType> class DL_SortIter :public DL_Iter<DType>
{
public:
//!Constructor of sort iterator for given list and sort function
DL_SortIter(DL_List<DType>* nw_list, int (*new_func)(DType ,DType ));
//!Constructor of sort iterator with sort function and no list attached
DL_SortIter(int (*newfunc)(DType,DType));
//!Destructor of sort iterator
~DL_SortIter();
//!insert item in sorted order
void insert (DType new_item);
/*override following functions to give an error */
//!Not allowed
void insend (bool n){sortitererror();};
//!Not allowed
void insbegin (bool n){sortitererror();};
//!Not allowed
void insbefore (bool n){sortitererror();};
//!Not allowed
void insafter (bool n){sortitererror();};
//!Not allowed
void takeover (DL_List<DType>*){sortitererror();};
//!Not allowed
void takeover (DL_Iter<DType>*){sortitererror();};
//!Not allowed
void takeover (DL_Iter<DType>* otheriter, int maxcount){sortitererror();};
//!Not allowed
void next_wrap() {sortitererror();};
//!Not allowed
void prev_wrap() {sortitererror();};
//!Not allowed
void reset_tail() {sortitererror();};
//!Not allowed
void reset_head() {sortitererror();};
private:
//!Report off Iterator Errors
void sortitererror();
//!comparefunction used to insert items in sorted order
int (*comparef)(DType, DType);
};
#include "../include/_dl_itr.cpp"
#endif
/*! \file kbool/include/kbool/_lnk_itr.cpp
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: _lnk_itr.cpp,v 1.1 2005/05/24 19:13:36 titato Exp $
*/
#ifdef __GNUG__
#pragma implementation
#endif
#ifdef __UNIX__
#include "kbool/include/_lnk_itr.h"
#endif
//=======================================================================
// implementation class LinkBaseIter
//=======================================================================
template<class Type>
TDLI<Type>::TDLI(DL_List<void*>* newlist):DL_Iter<void*>(newlist)
{
}
template<class Type>
TDLI<Type>::TDLI(DL_Iter<void*>* otheriter):DL_Iter<void*>(otheriter)
{
}
template<class Type>
TDLI<Type>::TDLI():DL_Iter<void*>()
{
}
// destructor TDLI
template<class Type>
TDLI<Type>::~TDLI()
{
}
template<class Type>
void TDLI<Type>::delete_all()
{
DL_Node<void*>* node;
Type* obj;
for (int i=0; i< NB; i++)
{
node = HD;
HD = node->_next;
obj=(Type*)(node->_item);
delete obj;
delete node;
}
NB=0; //reset memory used (no lost pointers)
TL=RT;
_current=RT;
}
template<class Type>
void TDLI<Type>::foreach_f(void (*fp) (Type* item) )
{
DL_Iter<void*>::foreach_f( (void (*)(void*))fp); //call fp for each item
}
template<class Type>
void TDLI<Type>::foreach_mf(void (Type::*mfp) ())
{
DL_Node<void*>* node=HD; //can be 0 if empty
Type* obj;
for(int i=0; i< NB; i++)
{
obj=(Type*)(node->_item);
(obj->*mfp)();
node=node->_next;
}
}
template<class Type>
void TDLI<Type>::takeover(DL_List<void*>* otherlist)
{
DL_Iter<void*>::takeover( (DL_List<void*>*) otherlist);
}
template<class Type>
void TDLI<Type>::takeover(TDLI* otheriter)
{
DL_Iter<void*>::takeover( (DL_Iter<void*>*) otheriter);
}
template<class Type>
void TDLI<Type>::takeover(TDLI* otheriter,int maxcount)
{
DL_Iter<void*>::takeover( (DL_Iter<void*>*) otheriter,maxcount);
}
// is item element of the list?
template<class Type>
bool TDLI<Type>::has(Type* otheritem)
{
return DL_Iter<void*>::has( (void*) otheritem);
}
// goto to item
template<class Type>
bool TDLI<Type>::toitem(Type* item)
{
return DL_Iter<void*>::toitem( (void*) item);
}
// get current item
template<class Type>
Type* TDLI<Type>::item()
{
return (Type*) DL_Iter<void*>::item();
}
template<class Type>
void TDLI<Type>::insend(Type* newitem)
{
DL_Iter<void*>::insend( (void*) newitem);
}
template<class Type>
void TDLI<Type>::insbegin(Type* newitem)
{
DL_Iter<void*>::insbegin( (void*) newitem);
}
template<class Type>
void TDLI<Type>::insbefore(Type* newitem)
{
DL_Iter<void*>::insbefore( (void*) newitem);
}
template<class Type>
void TDLI<Type>::insafter(Type* newitem)
{
DL_Iter<void*>::insafter( (void*) newitem);
}
template<class Type>
void TDLI<Type>::insend_unsave(Type* newitem)
{
short int iterbackup=_list->_iterlevel;
_list->_iterlevel=0;
DL_Iter<void*>::insend( (void*) newitem);
_list->_iterlevel=iterbackup;
}
template<class Type>
void TDLI<Type>::insbegin_unsave(Type* newitem)
{
short int iterbackup=_list->_iterlevel;
_list->_iterlevel=0;
DL_Iter<void*>::insbegin( (void*) newitem);
_list->_iterlevel=iterbackup;
}
template<class Type>
void TDLI<Type>::insbefore_unsave(Type* newitem)
{
short int iterbackup=_list->_iterlevel;
_list->_iterlevel=0;
DL_Iter<void*>::insbefore( (void*) newitem);
_list->_iterlevel=iterbackup;
}
template<class Type>
void TDLI<Type>::insafter_unsave(Type* newitem)
{
short int iterbackup=_list->_iterlevel;
_list->_iterlevel=0;
DL_Iter<void*>::insafter( (void*) newitem);
_list->_iterlevel=iterbackup;
}
template<class Type>
void TDLI<Type>::mergesort(int (*f)(Type* a,Type* b))
{
DL_Iter<void*>::mergesort( (int (*)(void*,void*)) f);
}
template<class Type>
int TDLI<Type>::cocktailsort(int (*f)(Type* a,Type* b), bool (*f2)(Type* c,Type* d))
{
return DL_Iter<void*>::cocktailsort( (int (*)(void*,void*)) f,( bool(*)(void*,void*)) f2);
}
template<class Type>
TDLISort<Type>::TDLISort(DL_List<void*>* lista, int (*newfunc)(void*,void*))
:DL_SortIter<void*>(lista, newfunc)
{
}
template<class Type>
TDLISort<Type>::~TDLISort()
{
}
template<class Type>
void TDLISort<Type>::delete_all()
{
DL_Node<void*>* node;
Type* obj;
for (int i=0; i< NB; i++)
{
node = HD;
HD = node->_next;
obj=(Type*)(node->_item);
delete obj;
delete node;
}
NB=0; //reset memory used (no lost pointers)
TL=RT;
_current=RT;
}
// is item element of the list?
template<class Type>
bool TDLISort<Type>::has(Type* otheritem)
{
return DL_Iter<void*>::has( (void*) otheritem);
}
// goto to item
template<class Type>
bool TDLISort<Type>::toitem(Type* item)
{
return DL_Iter<void*>::toitem( (void*) item);
}
// get current item
template<class Type>
Type* TDLISort<Type>::item()
{
return (Type*) DL_Iter<void*>::item();
}
template<class Type>
TDLIStack<Type>::TDLIStack(DL_List<void*>* newlist):DL_StackIter<void*>(newlist)
{
}
// destructor TDLI
template<class Type>
TDLIStack<Type>::~TDLIStack()
{
}
// plaats nieuw item op stack
template<class Type>
void TDLIStack<Type>::push(Type* newitem)
{
DL_StackIter<void*>::push((Type*) newitem);
}
// haal bovenste item van stack
template<class Type>
Type* TDLIStack<Type>::pop()
{
return (Type*) DL_StackIter<void*>::pop();
}
/*! \file kbool/include/kbool/_lnk_itr.h
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: _lnk_itr.h,v 1.1 2005/05/24 19:13:36 titato Exp $
*/
//! author="Klaas Holwerda"
//! version="1.0"
/*
* Definitions of classes, for list implementation
* template list and iterator for any list node type
*/
#ifndef _LinkBaseIter_H
#define _LinkBaseIter_H
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma interface
#endif
//! headerfiles="_dl_itr.h stdlib.h misc.h gdsmes.h"
#include <stdlib.h>
#include "../include/booleng.h"
#define SWAP(x,y,t)((t)=(x),(x)=(y),(y)=(t))
#include "../include/_dl_itr.h"
//! codefiles="_dl_itr.cpp"
//! Template class TDLI
/*!
class for iterator on DL_List<void*> that is type casted version of DL_Iter
\sa DL_Iter for further documentation
*/
template<class Type> class TDLI : public DL_Iter<void*>
{
public:
//!constructor
/*!
\param list to iterate on.
*/
TDLI(DL_List<void*>* list);
//!constructor
TDLI(DL_Iter<void*>* otheriter);
//! nolist constructor
TDLI();
//! destructor
~TDLI();
//!call fp for each item
void foreach_f(void (*fp) (Type* item) );
//!call fp for each item
void foreach_mf(void (Type::*fp) () );
/* list mutations */
//! delete all items
void delete_all ();
//! insert at end
void insend (Type* n);
//! insert at begin
void insbegin (Type* n);
//! insert before current
void insbefore (Type* n);
//! insert after current
void insafter (Type* n);
//! insert at end unsave (works even if more then one iterator is on the list
//! the user must be sure not to delete/remove items where other iterators
//! are pointing to.
void insend_unsave (Type* n);
//! insert at begin unsave (works even if more then one iterator is on the list
//! the user must be sure not to delete/remove items where other iterators
//! are pointing to.
void insbegin_unsave (Type* n);
//! insert before iterator position unsave (works even if more then one iterator is on the list
//! the user must be sure not to delete/remove items where other iterators
//! are pointing to.
void insbefore_unsave (Type* n);
//! insert after iterator position unsave (works even if more then one iterator is on the list
//! the user must be sure not to delete/remove items where other iterators
//! are pointing to.
void insafter_unsave (Type* n);
//! \sa DL_Iter::takeover(DL_List< Dtype >* otherlist )
void takeover (DL_List<void*>* otherlist);
//! \sa DL_Iter::takeover(DL_Iter* otheriter)
void takeover (TDLI* otheriter);
//! \sa DL_Iter::takeover(DL_Iter* otheriter, int maxcount)
void takeover (TDLI* otheriter, int maxcount);
//! \sa DL_Iter::has
bool has (Type*);
//! \sa DL_Iter::toitem
bool toitem (Type*);
//!get the item then iterator is pointing at
Type* item ();
//! \sa DL_Iter::mergesort
void mergesort (int (*f)(Type* a,Type* b));
//! \sa DL_Iter::cocktailsort
int cocktailsort( int (*) (Type* a,Type* b), bool (*) (Type* c,Type* d) = NULL);
};
//! Template class TDLIsort
/*!
// class for sort iterator on DL_List<void*> that is type casted version of DL_SortIter
// see also inhereted class DL_SortIter for further documentation
*/
template<class Type> class TDLISort : public DL_SortIter<void*>
{
public:
//!constructor givin a list and a sort function
TDLISort(DL_List<void*>* list, int (*newfunc)(void*,void*));
~TDLISort();
//!delete all items from the list
void delete_all();
bool has (Type*);
bool toitem (Type*);
Type* item ();
};
//! Template class TDLIStack
/*!
class for iterator on DL_List<void*> that is type casted version of DL_StackIter
see also inhereted class DL_StackIter for further documentation
*/
template<class Type> class TDLIStack : public DL_StackIter<void*>
{
public:
//constructor givin a list
TDLIStack(DL_List<void*>* list);
~TDLIStack();
void push(Type*);
Type* pop();
};
#include"../include/_lnk_itr.cpp"
#endif
/*! \file kbool/include/kbool/booleng.h
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: booleng.h,v 1.3 2005/06/11 19:25:12 frm Exp $
*/
#ifndef BOOLENG_H
#define BOOLENG_H
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma interface
#endif
#include <stdio.h>
#include <limits.h>
#ifdef A2DKBOOLMAKINGDLL
#define A2DKBOOLDLLEXP WXEXPORT
#define A2DKBOOLDLLEXP_DATA(type) WXEXPORT type
#define A2DKBOOLDLLEXP_CTORFN
#elif defined(WXUSINGDLL)
#define A2DKBOOLDLLEXP WXIMPORT
#define A2DKBOOLDLLEXP_DATA(type) WXIMPORT type
#define A2DKBOOLDLLEXP_CTORFN
#else // not making nor using DLL
#define A2DKBOOLDLLEXP
#define A2DKBOOLDLLEXP_DATA(type) type
#define A2DKBOOLDLLEXP_CTORFN
#endif
#define KBOOL_VERSION "1.8"
#define KBOOL_DEBUG 0
#define KBOOL_LOG 0
#define KBOOL_INT64 1
class KBoolLink;
#define LINELENGTH 200
#ifdef MAXDOUBLE
#undef MAXDOUBLE
#endif
#define MAXDOUBLE 1.7976931348623158e+308
#ifdef KBOOL_INT64
#if defined(__UNIX__) || defined(__GNUG__)
typedef long long B_INT; // 8 bytes integer
//#define MAXB_INT LONG_LONG_MAX
//#define MINB_INT LONG_LONG_MIN // 8 bytes integer
#ifndef MAXB_INT
const B_INT MAXB_INT = (0x7fffffffffffffffLL); // 8 bytes integer
#endif
#ifndef MINB_INT
const B_INT MINB_INT = (0x8000000000000000LL);
#endif
#else //defined(__UNIX__) || defined(__GNUG__)
typedef __int64 B_INT; // 8 bytes integer
#undef MAXB_INT
#undef MINB_INT
const B_INT MAXB_INT = (0x7fffffffffffffff); // 8 bytes integer
const B_INT MINB_INT = (0x8000000000000000);
#endif //defined(__UNIX__) || defined(__GNUG__)
#else //KBOOL_INT64
#if defined(__UNIX__) || defined(__GNUG__)
typedef long B_INT; // 4 bytes integer
const B_INT MAXB_INT = (0x7fffffffL); // 4 bytes integer
const B_INT MINB_INT = (0x80000000L);
#else
typedef long B_INT; // 4 bytes integer
const B_INT MAXB_INT = (0x7fffffff); // 4 bytes integer
const B_INT MINB_INT = (0x80000000);
#endif
#endif //KBOOL_INT64
B_INT babs(B_INT);
#ifdef M_PI
#undef M_PI
#endif
#define M_PI (3.1415926535897932384626433832795028841972)
#ifdef M_PI_2
#undef M_PI_2
#endif
#define M_PI_2 1.57079632679489661923
#ifdef M_PI_4
#undef M_PI_4
#endif
#define M_PI_4 0.785398163397448309616
#ifndef NULL
#define NULL 0
#endif
B_INT bmin(B_INT const value1, B_INT const value2);
B_INT bmax(B_INT const value1, B_INT const value2);
B_INT bmin(B_INT value1, B_INT value2);
B_INT bmax(B_INT value1, B_INT value2);
#include <string.h>
//! errors in the boolean algorithm will be thrown using this class
class A2DKBOOLDLLEXP Bool_Engine_Error
{
public:
Bool_Engine_Error(const char* message, const char* header=0, int degree = 9, int fatal = 0);
Bool_Engine_Error(const Bool_Engine_Error& a);
~Bool_Engine_Error();
char* GetErrorMessage();
char* GetHeaderMessage();
int GetErrorDegree();
int GetFatal();
protected:
char* _message;
char* _header;
int _degree;
int _fatal;
};
#define KBOOL_LOGFILE "kbool.log"
enum kbEdgeType
{
KB_OUTSIDE_EDGE, /*!< edge of the outside contour of a polygon */
KB_INSIDE_EDGE, /*!< edge of the inside hole a polygon */
KB_FALSE_EDGE /*!< edge to connect holes into polygons */
} ;
enum GroupType
{
GROUP_A, /*!< to set Group A for polygons */
GROUP_B /*!< to set Group A for polygons */
};
enum BOOL_OP
{
BOOL_NON, /*!< No operation */
BOOL_OR, /*!< boolean OR operation */
BOOL_AND, /*!< boolean AND operation */
BOOL_EXOR, /*!< boolean EX_OR operation */
BOOL_A_SUB_B, /*!< boolean Group A - Group B operation */
BOOL_B_SUB_A, /*!< boolean Group B - Group A operation */
BOOL_CORRECTION, /*!< polygon correction/offset operation */
BOOL_SMOOTHEN, /*!< smooth operation */
BOOL_MAKERING /*!< create a ring on all polygons */
};
class GraphList;
class Graph;
class KBoolLink;
class Node;
template<class Type> class TDLI;
//! boolean engine to perform operation on two sets of polygons.
/*
First the engine needs to be filled with polygons.
The first operand in the operation is called group A polygons, the second group B.
The boolean operation ( BOOL_OR, BOOL_AND, BOOL_EXOR, BOOL_A_SUB_B, BOOL_B_SUB_A )
are based on the two sets of polygons in group A and B.
The other operation on group A only.
At the end of the operation the resulting polygons can be extracted.
*/
class A2DKBOOLDLLEXP Bool_Engine {
public:
//! constructor
Bool_Engine();
//! destructor
virtual ~Bool_Engine();
const char* GetVersion() { return KBOOL_VERSION; }
//! reports progress of algorithm.
virtual void SetState( const char* = 0 );
//! called at an internal error.
virtual void error(const char *text, const char *title);
//! called at an internal generated possible error.
virtual void info(const char *text, const char *title);
bool Do_Operation(BOOL_OP operation);
//! distance within which points and lines will be snapped towards lines and other points
/*
The algorithm takes into account gaps and inaccuracies caused by rounding to integer coordinates
in the original data.
Imagine two rectangles one with a side ( 0,0 ) ( 2.0, 17.0 )
and the other has a side ( 0,0 ) ( 1.0, 8.5 )
If for some reason those coordinates where round to ( 0,0 ) ( 2, 17 ) ( 0,0 ) ( 1, 9 ),
there will be clearly a gap or overlap that was not intended.
Even without rounding this effect takes place since there is always a minimum significant bit
also when using doubles.
If the user used as minimum accuracy 0.001, you need to choose Marge > 0.001
The boolean engine scales up the input data with GetDGrid() * GetGrid() and rounds the result to
integer, So (assuming GRID = 100 DGRID = 1000) a vertex of 123.001 in the user data will
become 12300100 internal.
At the end of the algorithm the internal vertexes are scaled down again with GetDGrid() * GetGrid(),
so 12300103 becomes 123.00103 eventually.
So indeed the minimum accuracy might increase, you are free to round again if needed.
*/
void SetMarge(double marge);
double GetMarge();
//! input points are scaled up with GetDGrid() * GetGrid()
/*
Grid makes sure that the integer data used within the algorithm has room for extra intersections
smaller than the smallest number within the input data.
The input data scaled up with DGrid is related to the accuracy the user has in his input data.
Another scaling with Grid is applied on top of it to create space in the integer number for
even smaller numbers.
*/
void SetGrid(B_INT grid);
//! See SetGrid
B_INT GetGrid();
//! input points are scaled up with GetDGrid() * GetGrid()
/*
The input data scaled up with DGrid is related to the accuracy the user has in his input data.
User data with a minimum accuracy of 0.001, means set the DGrid to 1000.
The input data may contain data with a minimum accuracy much smaller, but by setting the DGrid
everything smaller than 1/DGrid is rounded.
DGRID is only meant to make fractional parts of input data which can be
doubles, part of the integers used in vertexes within the boolean algorithm.
And therefore DGRID bigger than 1 is not usefull, you would only loose accuracy.
Within the algorithm all input data is multiplied with DGRID, and the result
is rounded to an integer.
*/
void SetDGrid(double dgrid);
//! See SetDGrid
double GetDGrid();
//! When doing a correction operation ( also known as process offset )
//! this defines the detail in the rounded corners.
/*
Depending on the round factor the corners of the polygon may be rounding within the correction
algorithm. The detail within this rounded corner is set here.
It defines the deviation the generated segments in arc like polygon may have towards the ideal
rounded corner using a perfect arc.
*/
void SetCorrectionAber(double aber);
//! see SetCorrectionAber
double GetCorrectionAber();
//! When doing a correction operation ( also known as process offset )
//! this defines the amount of correction.
/*
The correction algorithm can apply positive and negative offset to polygons.
It takes into account closed in areas within a polygon, caused by overlapping/selfintersecting
polygons. So holes form that way are corrected proberly, but the overlapping parts itself
are left alone. An often used trick to present polygons with holes by linking to the outside
boundary, is therefore also handled properly.
The algoritm first does a boolean OR operation on the polygon, and seperates holes and
outside contours.
After this it creates a ring shapes on the above holes and outside contours.
This ring shape is added or subtracted from the holes and outside contours.
The result is the corrected polygon.
If the correction factor is > 0, the outside contours will become larger, while the hole contours
will become smaller.
*/
void SetCorrectionFactor(double aber);
//! see SetCorrectionFactor
double GetCorrectionFactor();
//! used within the smooth algorithm to define how much the smoothed curve may deviate
//! from the original.
void SetSmoothAber(double aber);
//! see SetSmoothAber
double GetSmoothAber();
//! segments of this size will be left alone in the smooth algorithm.
void SetMaxlinemerge(double maxline);
//! see SetMaxlinemerge
double GetMaxlinemerge();
//! Polygon may be filled in different ways (alternate and winding rule).
//! This here defines which method will be assumed within the algorithm.
void SetWindingRule(bool rule);
//! see SetWindingRule
bool GetWindingRule();
//! the smallest accuracy used within the algorithm for comparing two real numbers.
double GetAccur();
//! Used with in correction/offset algorithm.
/*
When the polygon contains sharp angles ( < 90 ), after a positive correction the
extended parrallel constructed offset lines may leed to extreme offsets on the angles.
The length of the crossing generated by the parrallel constructed offset lines
towards the original point in the polygon is compared to the offset which needs to be applied.
The Roundfactor then decides if this corner will be rounded.
A Roundfactor of 1 means that the resulting offset will not be bigger then the correction factor
set in the algorithm. Meaning even straight 90 degrees corners will be rounded.
A Roundfactor of > sqrt(2) is where 90 corners will be left alone, and smaller corners will be rounded.
*/
void SetRoundfactor(double roundfac);
//! see SetRoundfactor
double GetRoundfactor();
// the following are only be used within the algorithm,
// since they are scaled with m_DGRID
//! only used internal.
void SetInternalMarge( B_INT marge );
//! only used internal.
B_INT GetInternalMarge();
//! only used internal.
double GetInternalCorrectionAber();
//! only used internal.
double GetInternalCorrectionFactor();
//! only used internal.
double GetInternalSmoothAber();
//! only used internal.
B_INT GetInternalMaxlinemerge();
//! in this mode polygons add clockwise, or contours,
/*!
and polygons added counter clockwise or holes.
*/
void SetOrientationEntryMode( bool orientationEntryMode ) { m_orientationEntryMode = orientationEntryMode; }
//! see SetOrientationEntryMode()
bool GetOrientationEntryMode() { return m_orientationEntryMode; }
//! if set true holes are linked into outer contours by double overlapping segments.
/*!
This mode is needed when the software using the boolean algorithm does
not understand hole polygons. In that case a contour and its holes form one
polygon. In cases where software understands the concept of holes, contours
are clockwise oriented, while holes are anticlockwise oriented.
The output of the boolean operations, is following those rules also.
But even if extracting the polygons from the engine, each segment is marked such
that holes and non holes and linksegments to holes can be recognized.
*/
void SetLinkHoles( bool doLinkHoles ) { m_doLinkHoles = doLinkHoles; }
//! see SetLinkHoles()
bool GetLinkHoles() { return m_doLinkHoles; }
//!lof file will be created when set True
void SetLog( bool OnOff );
//! used to write to log file
void Write_Log(const char *);
//! used to write to log file
void Write_Log(const char *, const char *);
//! used to write to log file
void Write_Log(const char *, double);
//! used to write to log file
void Write_Log(const char *, B_INT);
FILE* GetLogFile() { return m_logfile; }
// methods used to add polygons to the eng using points
//! Start adding a polygon to the engine
/*
The boolean operation work on two groups of polygons ( group A or B ),
other algorithms are only using group A.
You add polygons like this to the engine.
// foreach point in a polygon ...
if (booleng->StartPolygonAdd(GROUP_A))
{
booleng->AddPoint(100,100);
booleng->AddPoint(-100,100);
booleng->AddPoint(-100,-100);
booleng->AddPoint(100,-100);
}
booleng->EndPolygonAdd();
\param A_or_B defines if the new polygon will be of group A or B
Holes or added by adding an inside polygons with opposite orientation compared
to another polygon added.
So the contour polygon ClockWise, then add counterclockwise polygons for holes, and visa versa.
BUT only if m_orientationEntryMode is set true, else all polygons are redirected, and become
individual areas without holes.
Holes in such a case must be linked into the contour using two extra segments.
*/
bool StartPolygonAdd( GroupType A_or_B );
//! see StartPolygonAdd
bool AddPoint(double x, double y);
//! see StartPolygonAdd
bool EndPolygonAdd();
// methods used to extract polygons from the eng by getting its points
//! Use after StartPolygonGet()
int GetNumPointsInPolygon() { return m_numPtsInPolygon ; }
//! get resulting polygons at end of an operation
/*!
// foreach resultant polygon in the booleng ...
while ( booleng->StartPolygonGet() )
{
// foreach point in the polygon
while ( booleng->PolygonHasMorePoints() )
{
fprintf(stdout,"x = %f\t", booleng->GetPolygonXPoint());
fprintf(stdout,"y = %f\n", booleng->GetPolygonYPoint());
}
booleng->EndPolygonGet();
}
*/
bool StartPolygonGet();
//! see StartPolygonGet
/*!
This iterates through the first graph in the graphlist.
Setting the current Node properly by following the links in the graph
through its nodes.
*/
bool PolygonHasMorePoints();
//! see StartPolygonGet
double GetPolygonXPoint();
//! see StartPolygonGet
double GetPolygonYPoint();
//! in the resulting polygons this tells if the current polygon segment is one
//! used to link holes into the outer contour of the surrounding polygon
bool GetHoleConnectionSegment();
//! in the resulting polygons this tells if the current polygon segment is part
//! of a hole within a polygon.
bool GetHoleSegment();
//! an other way to get the type of segment.
kbEdgeType GetPolygonPointEdgeType();
//! see StartPolygonGet()
/*!
Removes a graph from the graphlist.
Called after an extraction of an output polygon was done.
*/
void EndPolygonGet();
private:
bool m_doLog;
//! contains polygons in graph form
GraphList* m_graphlist;
double m_MARGE;
B_INT m_GRID;
double m_DGRID;
double m_CORRECTIONABER;
double m_CORRECTIONFACTOR;
double m_SMOOTHABER;
double m_MAXLINEMERGE;
bool m_WINDINGRULE;
double m_ACCUR;
double m_ROUNDFACTOR;
bool m_orientationEntryMode;
bool m_doLinkHoles;
//! used in the StartPolygonAdd, AddPt, EndPolygonAdd sequence
Graph* m_GraphToAdd;
//! used in the StartPolygonAdd, AddPt, EndPolygonAdd sequence
Node* m_lastNodeToAdd;
//! used in the StartPolygonAdd, AddPt, EndPolygonAdd sequence
Node* m_firstNodeToAdd;
//! the current group type ( group A or B )
GroupType m_groupType;
//! used in extracting the points from the resultant polygons
Graph* m_getGraph;
//! used in extracting the points from the resultant polygons
KBoolLink* m_getLink;
//! used in extracting the points from the resultant polygons
Node* m_getNode;
//! used in extracting the points from the resultant polygons
double m_PolygonXPoint;
//! used in extracting the points from the resultant polygons
double m_PolygonYPoint;
//! used in extracting the points from the resultant polygons
int m_numPtsInPolygon;
//! used in extracting the points from the resultant polygons
int m_numNodesVisited;
FILE* m_logfile;
public:
//! use in Node to iterate links.
TDLI<KBoolLink>* _linkiter;
//! how many time run intersections fase.
unsigned int m_intersectionruns;
};
#endif
/*! \file ../include/../graph.h
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: graph.h,v 1.1 2005/05/24 19:13:37 titato Exp $
*/
/* @@(#) $Source: /cvsroot/wxart2d/wxArt2D/modules/../include/graph.h,v $ $Revision: 1.1 $ $Date: 2005/05/24 19:13:37 $ */
/*
Program GRAPH.H
Purpose Used to Intercect and other process functions
Last Update 03-04-1996
*/
#ifndef GRAPH_H
#define GRAPH_H
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma interface
#endif
#include "../include/booleng.h"
#include "../include/_lnk_itr.h"
#include "../include/link.h"
#include "../include/line.h"
#include "../include/scanbeam.h"
class Node;
class GraphList;
//! one graph containing links that cab be connected.
class A2DKBOOLDLLEXP Graph
{
protected:
Bool_Engine* _GC;
public:
Graph(Bool_Engine* GC);
Graph(KBoolLink*,Bool_Engine* GC);
Graph( Graph* other );
~Graph();
bool GetBin() { return _bin; };
void SetBin(bool b) { _bin = b; };
void Prepare( int intersectionruns );
void RoundInt(B_INT grid);
void Rotate(bool plus90);
//! adds a link to the linklist
void AddLink(Node *begin,Node *end);
//! adds a link to the linklist
void AddLink(KBoolLink *a_link);
bool AreZeroLines(B_INT Marge);
//! Delete parallel lines
void DeleteDoubles();
//! delete zerolines
bool DeleteZeroLines(B_INT Marge);
bool RemoveNullLinks();
//! Process found intersections
void ProcessCrossings();
//! set flags for operations based on group
void Set_Operation_Flags();
//! Left Right values
void Remove_IN_Links();
//! reset bin and mark flags in links.
void ResetBinMark();
// Remove unused links
void ReverseAllLinks();
//! Simplify the graph
bool Simplify( B_INT Marge );
//! Takes over all links of the argument
bool Smoothen( B_INT Marge);
void TakeOver(Graph*);
//! function for maximum performance
//! Get the First link from the graph
KBoolLink* GetFirstLink();
Node* GetTopNode();
void SetBeenHere(bool);
void Reset_flags();
//! Set the group of a graph
void SetGroup(GroupType);
//! Set the number of the graph
void SetNumber(int);
void Reset_Mark_and_Bin();
bool GetBeenHere();
int GetGraphNum();
int GetNumberOfLinks();
void Boolean(BOOL_OP operation,GraphList* Result);
void Correction(GraphList* Result,double factor);
void MakeRing(GraphList* Result,double factor);
void CreateRing(GraphList *ring,double factor);
void CreateRing_fast(GraphList *ring,double factor);
void CreateArc(Node* center, KBoolLine* incoming, Node* end,double radius,double aber);
void CreateArc(Node* center, Node* begin, Node* end,double radius,bool clock,double aber);
void MakeOneDirection();
void Make_Rounded_Shape(KBoolLink* a_link, double factor);
bool MakeClockWise();
bool writegraph(bool linked);
bool writeintersections();
void WriteKEY( Bool_Engine* GC, FILE* file = NULL );
void WriteGraphKEY( Bool_Engine* GC );
protected:
//! Extracts partical polygons from the graph
/*
Links are sorted in XY at beginpoint. Bin and mark flag are reset.
Next start to collect subparts from the graph, setting the links bin for all found parts.
The parts are searched starting at a topleft corner NON set bin flag link.
Found parts are numbered, to be easily split into to real sperate graphs by Split()
\param operation operation to collect for.
\param detecthole if you want holes detected, influences also way of extraction.
\param foundholes when holes are found this flag is set true, but only if detecthole is set true.
*/
void Extract_Simples(BOOL_OP operation, bool detecthole, bool& foundholes );
//! split graph into small graph, using the numbers in links.
void Split(GraphList* partlist);
//! Collect a graph by starting at argument link
/*
Called from Extract_Simples, and assumes sorted links with bin flag unset for non extarted piece
Collect graphs pieces from a total graph, by following links set to a given boolean operation.
\param current_node start node to collect
\param operation operation to collect for.
\param detecthole if you want holes detected, influences also way of extraction.
\param graphnumber number to be given to links in the extracted graph piece
\param foundholes when holes are found this flag is set true.
*/
void CollectGraph(Node *current_node, BOOL_OP operation, bool detecthole,int graphnumber, bool& foundholes );
void CollectGraphLast(Node *current_node, BOOL_OP operation, bool detecthole,int graphnumber, bool& foundholes );
//! find a link not bin in the top left corner ( links should be sorted already )
/*!
Last found position is used to find it quickly.
Used in ExtractSimples()
*/
Node* GetMostTopLeft(TDLI<KBoolLink>* _LI);
//! calculates crossing for all links in a graph, and add those as part of the graph.
/*
It is not just crossings calculation, snapping close nodes is part of it.
This is not done at maximum stability in economic time.
There are faster ways, but hardly ever they solve the problems, and they do not snap.
Here it is on purpose split into separate steps, to get a better result in snapping, and
to reach a better stability.
\param Marge nodes and lines closer to eachother then this, are merged.
*/
bool CalculateCrossings(B_INT Marge);
//! equal nodes in position are merged into one.
int Merge_NodeToNode(B_INT Marge);
//! basic scan algorithm with a sweeping beam are line.
/*!
\param scantype a different face in the algorithm.
\param holes to detect hole when needed.
*/
int ScanGraph2( SCANTYPE scantype, bool& holes );
//! links not used for a certain operation can be deleted, simplifying extraction
void DeleteNonCond(BOOL_OP operation);
//! links not used for a certain operation can be set bin, simplifying extraction
void HandleNonCond(BOOL_OP operation);
//! debug
bool checksort();
//! used in correction/offset algorithm
bool Small(B_INT howsmall);
bool _bin;
DL_List<void*>* _linklist;
};
#endif
/*! \file ../include/../graphlst.h
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: graphlst.h,v 1.1 2005/05/24 19:13:37 titato Exp $
*/
/* @@(#) $Source: /cvsroot/wxart2d/wxArt2D/modules/../include/graphlst.h,v $ $Revision: 1.1 $ $Date: 2005/05/24 19:13:37 $ */
/*
Program GRAPHLST.H
Purpose Implements a list of graphs (header)
Last Update 11-03-1996
*/
#ifndef GRAPHLIST_H
#define GRAPHLIST_H
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma interface
#endif
#include "../include/booleng.h"
#include "../include/_lnk_itr.h"
#include "../include/graph.h"
class Debug_driver;
class A2DKBOOLDLLEXP GraphList: public DL_List<void*>
{
protected:
Bool_Engine* _GC;
public:
GraphList(Bool_Engine* GC);
GraphList( GraphList* other );
~GraphList();
void MakeOneGraph(Graph *total);
void Prepare(Graph *total);
void MakeRings();
void Correction();
void Simplify( double marge);
void Smoothen( double marge);
void Merge();
void Boolean(BOOL_OP operation, int intersectionRunsMax );
void WriteGraphs();
void WriteGraphsKEY( Bool_Engine* GC );
protected:
void Renumber();
void UnMarkAll();
};
#endif
#ifndef __A2D_KBOOLMOD_H__
#define __A2D_KBOOLMOD_H__
#include "../include/booleng.h"
#include "../include/graph.h"
#include "../include/graphlst.h"
#include "../include/line.h"
#include "../include/link.h"
#include "../include/lpoint.h"
#include "../include/node.h"
#include "../include/record.h"
#include "../include/scanbeam.h"
#endif
\ No newline at end of file
/*! \file ../include/../line.h
\brief Mainy used for calculating crossings
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: line.h,v 1.2 2005/06/12 00:03:11 kbluck Exp $
*/
#ifndef LINE_H
#define LINE_H
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma interface
#endif
#include "../include/booleng.h"
#include "../include/link.h"
class A2DKBOOLDLLEXP Bool_Engine;
// Status of a point to a line
enum PointStatus {LEFT_SIDE, RIGHT_SIDE, ON_AREA, IN_AREA};
class A2DKBOOLDLLEXP Graph;
class A2DKBOOLDLLEXP KBoolLine
{
protected:
Bool_Engine* m_GC;
public:
// constructors and destructor
KBoolLine(Bool_Engine* GC);
KBoolLine(KBoolLink*,Bool_Engine* GC);
~KBoolLine();
void Set(KBoolLink *);
KBoolLink* GetLink();
//! Get the beginnode from a line
Node* GetBeginNode();
//! Get the endnode from a line
Node* GetEndNode();
//! Check if two lines intersects
int CheckIntersect(KBoolLine*, double Marge);
//! Intersects two lines
int Intersect(KBoolLine*, double Marge);
int Intersect_simple(KBoolLine * lijn);
bool Intersect2(Node* crossing,KBoolLine * lijn);
//!For an infinite line
PointStatus PointOnLine(Node* a_node, double& Distance, double Marge );
//!For a non-infinite line
PointStatus PointInLine(Node* a_node, double& Distance, double Marge );
//! Caclulate Y if X is known
B_INT Calculate_Y(B_INT X);
B_INT Calculate_Y_from_X(B_INT X);
void Virtual_Point( LPoint *a_point, double distance);
//! assignment operator
KBoolLine& operator=(const KBoolLine&);
Node* OffsetContour(KBoolLine* const nextline,Node* last_ins, double factor,Graph *shape);
Node* OffsetContour_rounded(KBoolLine* const nextline,Node* _last_ins, double factor,Graph *shape);
bool OkeForContour(KBoolLine* const nextline,double factor,Node* LastLeft,Node* LastRight, LinkStatus& _outproduct);
bool Create_Ring_Shape(KBoolLine* nextline,Node** _last_ins_left,Node** _last_ins_right,double factor,Graph *shape);
void Create_Begin_Shape(KBoolLine* nextline,Node** _last_ins_left,Node** _last_ins_right,double factor,Graph *shape);
void Create_End_Shape(KBoolLine* nextline,Node* _last_ins_left,Node* _last_ins_right,double factor,Graph *shape);
//! Calculate the parameters if nessecary
void CalculateLineParameters();
//! Adds a crossing between the intersecting lines
void AddLineCrossing(B_INT , B_INT , KBoolLine *);
void AddCrossing(Node *a_node);
Node* AddCrossing(B_INT X, B_INT Y);
bool ProcessCrossings(TDLI<KBoolLink>* _LI);
// Linecrosslist
void SortLineCrossings();
bool CrossListEmpty();
DL_List<void*>* GetCrossList();
// bool HasInCrossList(Node*);
private:
//! Function needed for Intersect
int ActionOnTable1(PointStatus,PointStatus);
//! Function needed for Intersect
int ActionOnTable2(PointStatus,PointStatus);
double m_AA;
double m_BB;
double m_CC;
KBoolLink* m_link;
bool m_valid_parameters;
//! List with crossings through this link
DL_List<void*> *linecrosslist;
};
#endif
/*! \file kbool/include/kbool/link.h
\brief Part of a graph, connection between nodes (Header)
\author Probably Klaas Holwerda or Julian Smart
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: link.h,v 1.1 2005/05/24 19:13:37 titato Exp $
*/
#ifndef LINK_H
#define LINK_H
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma interface
#endif
#include "../include/booleng.h"
#include "../include/_lnk_itr.h"
enum LinkStatus {IS_LEFT,IS_ON,IS_RIGHT};
class LPoint;
class Node;
class Record;
//! segment within a graph
/*
A Graph contains a list of KBoolLink, the KBoolLink or connected by Node's.
Several KBoolLink can be connected to one Node.
A KBoolLink has a direction defined by its begin and end node.
Node do have a list of connected KBoolLink's.
So one can walk trough a graph in two ways:
1- via its KBoolLink list
2- via the node connected to the KBoolLink's
*/
class A2DKBOOLDLLEXP KBoolLink
{
protected:
Bool_Engine* _GC;
public:
//! contructors
KBoolLink(Bool_Engine* GC);
//! contructors
KBoolLink(int graphnr, Node* begin, Node* end, Bool_Engine* GC);
//! contructors
KBoolLink(Node *begin, Node *end, Bool_Engine* GC);
//! destructors
~KBoolLink();
//! Merges the other node with argument
void MergeNodes(Node* const);
//! outproduct of two links
LinkStatus OutProduct(KBoolLink* const two,double accur);
//! link three compared to this and two
LinkStatus PointOnCorner(KBoolLink* const, KBoolLink* const);
//! Removes argument from the link
void Remove(Node*);
//! replaces olddone in the link by newnode
void Replace(Node* oldnode, Node* newnode);
//!top hole marking
void SetTopHole(bool value);
//!top hole marking
bool IsTopHole();
//! Marking functions
void UnMark();
//! Marking functions
void Mark();
//! Marking functions
void SetMark(bool);
//! Marking functions
bool IsMarked();
//! holelink Marking functions
void SetHoleLink(bool val){ m_holelink = val;};
//! holelink Marking functions
bool GetHoleLink(){ return m_holelink;};
//! Bin functions
void SetNotBeenHere();
//! Bin functions
void SetBeenHere();
//! Have you been here ??
bool BeenHere();
//! Removes all the references to this
void UnLink();
//! functions for maximum performance
Node* GetBeginNode();
//! Datamember access functions
Node* GetEndNode();
Node* GetLowNode();
Node* GetHighNode();
//! Returns a next link beginning with argument
KBoolLink* Forth(Node*);
int GetGraphNum();
bool GetInc();
bool GetLeftA();
bool GetLeftB();
bool GetRightA();
bool GetRightB();
void GetLRO(LPoint*, int&, int&, double);
//! Return a node not equal to arg.
Node* GetOther(const Node* const);
//! Is this link unused ?
bool IsUnused();
//! Used for given operation ?
bool IsMarked(BOOL_OP operation);
//! return true if Left side is marked true for operation
bool IsMarkedLeft(BOOL_OP operation);
//! return true if Right side is marked true for operation
bool IsMarkedRight(BOOL_OP operation);
//! is this a hole link for given operation
bool IsHole(BOOL_OP operation);
//! set the hole mark
void SetHole(bool);
//! is the hole mark set?
bool GetHole();
//! Are the nodes on about the same coordinates ?
bool IsZero(B_INT marge );
bool ShorterThan(B_INT marge );
//! Resets the link
void Reset(Node* begin, Node* end, int graphnr = 0);
void Set(Node* begin, Node* end);
void SetBeginNode(Node*);
void SetEndNode(Node*);
void SetGraphNum(int);
void SetInc(bool);
void SetLeftA(bool);
void SetLeftB(bool);
void SetRightA(bool);
void SetRightB(bool);
void SetGroup(GroupType);
GroupType Group();
//! Flag calculation (internal only)
void SetLineTypes();
void Reset();
void Reset_flags();
//!put in this direction
void Redirect(Node* a_node);
void TakeOverOperationFlags( KBoolLink* link );
void SetRecordNode( DL_Node<Record*>* recordNode ) { m_record = recordNode; }
DL_Node<Record*>* GetRecordNode() { return m_record; }
protected:
//! The mainitems of a link
Node *m_beginnode, *m_endnode;
//! Marker for walking over the graph
bool m_bin : 1;
//! Is this a part of hole ?
bool m_hole : 1;
//! link that is toplink of hole?
bool m_hole_top : 1;
//! going in one more time in this graph if true else going out one time
bool m_Inc : 1;
//! Is left in polygongroup A
bool m_LeftA : 1;
//! Is right in polygon group A
bool m_RightA : 1;
//! Is left in polygon group B
bool m_LeftB : 1;
//! Is right in polygongroup B
bool m_RightB : 1;
//! General purose marker, internally unused
bool m_mark : 1;
//! link for linking holes
bool m_holelink : 1;
//! Marker for Merge Left
bool m_merge_L : 1;
//! Marker for substract a-b Left
bool m_a_substract_b_L: 1;
//! Marker for substract b-a Left
bool m_b_substract_a_L: 1;
//! Marker for intersect Left
bool m_intersect_L: 1;
//! Marker for X-OR Left
bool m_exor_L: 1;
//! Marker for Merge Right
bool m_merge_R : 1;
//! Marker for substract a-b Right
bool m_a_substract_b_R: 1;
//! Marker for substract b-a Right
bool m_b_substract_a_R: 1;
//! Marker for intersect Right
bool m_intersect_R: 1;
//! Marker for X-OR Right
bool m_exor_R: 1;
//! belongs to group A or B
GroupType m_group : 1;
//! belongs to this polygon part in the graph.
int m_graphnum;
DL_Node<Record*>* m_record;
};
#endif
/*! \file ../include/../lpoint.h
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: lpoint.h,v 1.1 2005/05/24 19:13:37 titato Exp $
*/
/* @@(#) $Source: /cvsroot/wxart2d/wxArt2D/modules/../include/lpoint.h,v $ $Revision: 1.1 $ $Date: 2005/05/24 19:13:37 $ */
/*
Program LPOINT.H
Purpose Definition of GDSII pointtype structure
Last Update 12-12-1995
*/
#ifndef LPOINT_H
#define LPOINT_H
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma interface
#endif
#include "../include/booleng.h"
class A2DKBOOLDLLEXP LPoint
{
public:
LPoint();
LPoint(B_INT const ,B_INT const);
LPoint(LPoint* const);
void Set(const B_INT,const B_INT);
void Set(const LPoint &);
LPoint GetPoint();
B_INT GetX();
B_INT GetY();
void SetX(B_INT);
void SetY(B_INT);
bool Equal(const LPoint a_point, B_INT Marge );
bool Equal(const B_INT,const B_INT , B_INT Marge);
bool ShorterThan(const LPoint a_point, B_INT marge);
bool ShorterThan(const B_INT X, const B_INT Y, B_INT);
LPoint &operator=(const LPoint &);
LPoint &operator+(const LPoint &);
LPoint &operator-(const LPoint &);
LPoint &operator*(int);
LPoint &operator/(int);
int operator==(const LPoint &) const;
int operator!=(const LPoint &) const;
protected:
B_INT _x;
B_INT _y;
};
#endif
/*! \file ../include/../node.h
\brief Holds a GDSII node structure (Header)
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: node.h,v 1.1 2005/05/24 19:13:37 titato Exp $
*/
#ifndef NODE_H
#define NODE_H
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma interface
#endif
#include <math.h>
#include "../include/booleng.h"
#include "../include/lpoint.h"
#include "../include/link.h"
#include "../include/_lnk_itr.h" // LinkBaseIter
enum NodePosition { N_LEFT, N_ON, N_RIGHT};
class A2DKBOOLDLLEXP Node : public LPoint
{
protected:
Bool_Engine* _GC;
public:
// friend must be deleted in the final version!
friend class Debug_driver;
// constructors and destructors
Node(Bool_Engine* GC);
Node(const B_INT, const B_INT, Bool_Engine* GC);
Node(LPoint* const a_point, Bool_Engine* GC);
Node(Node * const, Bool_Engine* GC);
Node& operator=(const Node &other_node);
~Node();
//public member functions
void AddLink(KBoolLink*);
DL_List<void*>* GetLinklist();
//! check two link for its operation flags to be the same when coming from the prev link.
bool SameSides( KBoolLink* const prev , KBoolLink* const link, BOOL_OP operation );
//! get the link most right or left to the current link, but with the specific operation
/*! flags the same on the sides of the new link.
*/
KBoolLink* GetMost( KBoolLink* const prev ,LinkStatus whatside, BOOL_OP operation );
//! get link that is leading to a hole ( hole segment or linking segment )
KBoolLink* GetMostHole( KBoolLink* const prev ,LinkStatus whatside, BOOL_OP operation );
//! get link that is not vertical.
KBoolLink* GetNotFlat();
//! get a link to a hole or from a hole.
KBoolLink* GetHoleLink( KBoolLink* const prev, bool checkbin, BOOL_OP operation );
int Merge(Node*);
void RemoveLink(KBoolLink*);
bool Simplify(Node* First, Node* Second, B_INT Marge );
// memberfunctions for maximum performance
void RoundInt(B_INT grid);
KBoolLink* GetIncomingLink();
int GetNumberOfLinks();
KBoolLink* GetNextLink();
KBoolLink* GetOtherLink(KBoolLink*);
KBoolLink* GetOutgoingLink();
KBoolLink* GetPrevLink();
KBoolLink* Follow(KBoolLink* const prev );
KBoolLink* GetBinHighest(bool binset);
protected:
DL_List<void*>* _linklist;
};
#endif
/*! \file ../include/../record.h
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: record.h,v 1.1 2005/05/24 19:13:37 titato Exp $
*/
#ifndef RECORD_H
#define RECORD_H
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma interface
#endif
class Node;
#include "../include/booleng.h"
#include "../include/link.h"
#include "../include/line.h"
enum BEAM_TYPE { NORMAL,FLAT};
enum DIRECTION {GO_LEFT,GO_RIGHT};
//extern void DeleteRecordPool();
class A2DKBOOLDLLEXP Bool_Engine;
class A2DKBOOLDLLEXP Record
{
protected:
Bool_Engine* _GC;
public:
// void deletepool();
Record(KBoolLink* link,Bool_Engine* GC);
~Record();
// void* operator new(size_t size);
// void operator delete(void* recordptr);
void SetNewLink(KBoolLink* link);
void Set_Flags();
void Calc_Ysp(Node* low);
KBoolLink* GetLink();
KBoolLine* GetLine();
B_INT Ysp();
void SetYsp(B_INT ysp);
DIRECTION Direction();
bool Calc_Left_Right(Record* record_above_me);
bool Equal(Record*);
private:
KBoolLine _line;
B_INT _ysp;
//! going left are right in beam
DIRECTION _dir;
//! how far in group_a
int _a;
//! how far in group_b
int _b;
};
#endif
/*! \file ../include/../scanbeam.h
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: scanbeam.h,v 1.2 2005/06/11 19:25:12 frm Exp $
*/
#ifndef SCANBEAM_H
#define SCANBEAM_H
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma interface
#endif
#include "../include/booleng.h"
#include "../include/_lnk_itr.h"
#include "../include/record.h"
#include "../include/link.h"
enum SCANTYPE{NODELINK,LINKLINK,GENLR,LINKHOLES,INOUT};
#if defined(WXUSINGDLL)
template class A2DKBOOLDLLEXP DL_Iter<Record*>;
#endif
class A2DKBOOLDLLEXP ScanBeam : public DL_List<Record*>
{
protected:
Bool_Engine* _GC;
public:
ScanBeam(Bool_Engine* GC);
~ScanBeam();
void SetType(Node* low,Node* high);
bool FindNew(SCANTYPE scantype,TDLI<KBoolLink>* _I, bool& holes );
bool RemoveOld(SCANTYPE scantype,TDLI<KBoolLink>* _I, bool& holes );
private:
bool ProcessHoles(bool atinsert,TDLI<KBoolLink>* _LI);
int Process_LinkToLink_Crossings(); // find crossings
int Process_PointToLink_Crossings();
int Process_LinkToLink_Flat(KBoolLine* flatline);
void SortTheBeam( bool backangle );
bool checksort();
bool writebeam();
void Calc_Ysp();
//int FindCloseLinksAndCross(TDLI<KBoolLink>* _I,Node* _lowf);
void Generate_INOUT(int graphnumber);
Node* _low;
DL_Iter<Record*> _BI;
int lastinserted;
BEAM_TYPE _type;
};
#endif
/*! \file kbool/include/kbool/valuesvc.h
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: valuesvc.h,v 1.1 2005/05/24 19:13:37 titato Exp $
*/
Boolean: GDSII viewer/editor + (boolean) operations on sets of 2d polygons.
Boolean Web Site:
http://boolean.klaasholwerda.nl/bool.html
Copyright section form the site:
The code is written by Klaas Holwerda, it is free to use for non commercial open source projects licensed as GPL.
Note:
License info in kbool files:
files are under wxWidget license
ADD_EXECUTABLE(boolonly boolonly.cpp)
IF(WIN32)
ADD_DEFINITIONS( -D_MSWVC_ )
ELSE(WIN32)
ADD_DEFINITIONS( -D__UNIX__ )
ENDIF(WIN32)
INCLUDE_DIRECTORIES( ${kbool_SOURCE_DIR}/.. )
TARGET_LINK_LIBRARIES( boolonly kbool )
/*! \file kbool/samples/boolonly/boolonly.cpp
\brief boolonly demonstrates the use of the boolean algorithm
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: boolonly.cpp,v 1.9 2005/01/16 18:39:24 kire_putsje Exp $
*/
#ifdef __GNUG__
#pragma implementation
#endif
#include "boolonly.h"
#include <math.h>
// Constructors
KBoolPoint::KBoolPoint()
{
_x = 0.0;
_y = 0.0;
}
KBoolPoint::KBoolPoint(double const X, double const Y)
{
_x = X;
_y = Y;
}
double KBoolPoint::GetX()
{
return _x;
}
double KBoolPoint::GetY()
{
return _y;
}
template class TDLI<KBoolPoint>;
void ArmBoolEng( Bool_Engine* booleng )
{
// set some global vals to arm the boolean engine
double DGRID = 1000; // round coordinate X or Y value in calculations to this
double MARGE = 0.001; // snap with in this range points to lines in the intersection routines
// should always be > DGRID a MARGE >= 10*DGRID is oke
// this is also used to remove small segments and to decide when
// two segments are in line.
double CORRECTIONFACTOR = 500.0; // correct the polygons by this number
double CORRECTIONABER = 1.0; // the accuracy for the rounded shapes used in correction
double ROUNDFACTOR = 1.5; // when will we round the correction shape to a circle
double SMOOTHABER = 10.0; // accuracy when smoothing a polygon
double MAXLINEMERGE = 1000.0; // leave as is, segments of this length in smoothen
// DGRID is only meant to make fractional parts of input data which
// are doubles, part of the integers used in vertexes within the boolean algorithm.
// Within the algorithm all input data is multiplied with DGRID
// space for extra intersection inside the boolean algorithms
// only change this if there are problems
int GRID =10000;
booleng->SetMarge( MARGE );
booleng->SetGrid( GRID );
booleng->SetDGrid( DGRID );
booleng->SetCorrectionFactor( CORRECTIONFACTOR );
booleng->SetCorrectionAber( CORRECTIONABER );
booleng->SetSmoothAber( SMOOTHABER );
booleng->SetMaxlinemerge( MAXLINEMERGE );
booleng->SetRoundfactor( ROUNDFACTOR );
}
void AddPolygonsToBoolEng2( Bool_Engine* booleng )
{
int x1 = 100;
int x2 = 200;
int y1 = 100;
int y2 = 200;
int pitch1 = 200;
int numRowsAndCols = 120;
int i, j;
for ( i = 0; i < numRowsAndCols; i++) {
for ( j = 0; j < numRowsAndCols; j++) {
// foreach point in a polygon ...
if (booleng->StartPolygonAdd(GROUP_A))
{
// Counter-Clockwise
booleng->AddPoint(x1,y1);
booleng->AddPoint(x2,y1);
booleng->AddPoint(x2,y2);
booleng->AddPoint(x1,y2);
}
booleng->EndPolygonAdd();
x1 += pitch1;
x2 += pitch1;
}
x1 = 100;
x2 = 200;
y1 += pitch1;
y2 += pitch1;
}
x1 = 150;
x2 = 250;
y1 = 150;
y2 = 250;
for ( i = 0; i < numRowsAndCols; i++) {
for ( int j = 0; j < numRowsAndCols; j++) {
// foreach point in a polygon ...
if (booleng->StartPolygonAdd(GROUP_B))
{
// Counter Clockwise
booleng->AddPoint(x1,y1);
booleng->AddPoint(x2,y1);
booleng->AddPoint(x2,y2);
booleng->AddPoint(x1,y2);
}
booleng->EndPolygonAdd();
x1 += pitch1;
x2 += pitch1;
}
x1 = 150;
x2 = 250;
y1 += pitch1;
y2 += pitch1;
}
}
void AddPolygonsToBoolEng( Bool_Engine* booleng )
{
// foreach point in a polygon ...
if (booleng->StartPolygonAdd(GROUP_A))
{
booleng->AddPoint( 28237.480000, 396.364000 );
booleng->AddPoint( 28237.980000, 394.121000 );
booleng->AddPoint( 28242.000000, 395.699000 );
booleng->AddPoint( 28240.830000, 397.679000 );
}
booleng->EndPolygonAdd();
// foreach point in a polygon ...
if (booleng->StartPolygonAdd(GROUP_B))
{
booleng->AddPoint( 28242.100000, 398.491000 );
booleng->AddPoint( 28240.580000, 397.485000 );
booleng->AddPoint( 28237.910000, 394.381000 );
}
booleng->EndPolygonAdd();
if (booleng->StartPolygonAdd(GROUP_B))
{
booleng->AddPoint( 28243.440000, 399.709000 );
booleng->AddPoint( 28237.910000, 394.381000 );
booleng->AddPoint( 28239.290000, 394.763000 );
}
booleng->EndPolygonAdd();
}
void AddPolygonsToBoolEng3( Bool_Engine* booleng )
{
// foreach point in a polygon ...
if (booleng->StartPolygonAdd(GROUP_A))
{
booleng->AddPoint(100,100);
booleng->AddPoint(-100,100);
booleng->AddPoint(-100,-100);
booleng->AddPoint(100,-100);
}
booleng->EndPolygonAdd();
// foreach point in a polygon ...
if (booleng->StartPolygonAdd(GROUP_B))
{
booleng->AddPoint(50,50);
booleng->AddPoint(-50,50);
booleng->AddPoint(-50,-50);
booleng->AddPoint(50,-50);
booleng->EndPolygonAdd();
}
booleng->EndPolygonAdd();
}
void AddPolygonsToBoolEng4( Bool_Engine* booleng )
{
// foreach point in a polygon ...
if (booleng->StartPolygonAdd(GROUP_A))
{
booleng->AddPoint(0,0);
booleng->AddPoint(0,1000);
booleng->AddPoint(1000,1000);
booleng->AddPoint(1000,0);
}
booleng->EndPolygonAdd();
}
void GetPolygonsFromBoolEng( Bool_Engine* booleng )
{
// foreach resultant polygon in the booleng ...
while ( booleng->StartPolygonGet() )
{
// foreach point in the polygon
while ( booleng->PolygonHasMorePoints() )
{
fprintf(stderr,"x = %f\t", booleng->GetPolygonXPoint());
fprintf(stderr,"y = %f\n", booleng->GetPolygonYPoint());
}
booleng->EndPolygonGet();
}
}
void GetPolygonsFromBoolEngKEY( Bool_Engine* booleng )
{
FILE* file = fopen("keyfile.key", "w");
fprintf(file,"\
HEADER 5; \
BGNLIB; \
LASTMOD {2-11-15 15:39:21}; \
LASTACC {2-11-15 15:39:21}; \
LIBNAME trial; \
UNITS; \
USERUNITS 0.0001; PHYSUNITS 2.54e-009; \
\
BGNSTR; \
CREATION {2-11-15 15:39:21}; \
LASTMOD {2-11-15 15:39:21}; \
STRNAME top; \
");
// foreach resultant polygon in the booleng ...
while ( booleng->StartPolygonGet() )
{
fprintf(file,"BOUNDARY; LAYER 2; DATATYPE 0;\n");
fprintf(file," XY %d; \n",booleng->GetNumPointsInPolygon()+1 );
booleng->PolygonHasMorePoints();
double firstx = booleng->GetPolygonXPoint();
double firsty = booleng->GetPolygonYPoint();
fprintf(file,"X %f;\t", firstx);
fprintf(file,"Y %f; \n", firsty);
// foreach point in the polygon
while ( booleng->PolygonHasMorePoints() )
{
fprintf(file,"X %f;\t", booleng->GetPolygonXPoint());
fprintf(file,"Y %f; \n", booleng->GetPolygonYPoint());
}
booleng->EndPolygonGet();
fprintf(file,"X %f;\t", firstx);
fprintf(file,"Y %f; \n", firsty);
fprintf(file,"ENDEL;\n");
}
fprintf(file,"\
ENDSTR top; \
ENDLIB; \
");
fclose (file);
}
int main()
{
printf( "------------------------------------------------------\n" );
printf( "| Unit test of the KBool Engine |\n" );
printf( "------------------------------------------------------\n" );
float correction;
char a = '1';
while (a != '0')
{
Bool_Engine* booleng = new Bool_Engine();
ArmBoolEng( booleng );
AddPolygonsToBoolEng( booleng );
printf( "\n***********************************\n" );
printf( "*** version: %s \n", booleng->GetVersion() );
printf( "***********************************\n" );
printf( "1: OR operation\n" );
printf( "2: AND operation\n" );
printf( "3: EXOR operation\n" );
printf( "4: A subtract B\n" );
printf( "5: B subtract A\n" );
printf( "6: Correct each polygon with a factor\n" );
printf( "7: Smoothen each polygon\n" );
printf( "8: Make a ring around each polygon\n" );
printf( "9: No operation\n" );
printf( "0: Quit\n" );
printf( "***********************************\n" );
printf( "type a number and <return>" );
scanf( "%c", &a );
switch (a)
{
case ('0'):
break;
case ('1'):
booleng->Do_Operation(BOOL_OR);
break;
case ('2'):
booleng->Do_Operation(BOOL_AND);
break;
case ('3'):
booleng->Do_Operation(BOOL_EXOR);
break;
case ('4'):
booleng->Do_Operation(BOOL_A_SUB_B);
break;
case ('5'):
booleng->Do_Operation(BOOL_B_SUB_A);
break;
case ('6'):
printf( "give correction factor (eg. 100.0 or -100.0)<return>:");
scanf("%f", &correction ); // correct the polygons by this number
booleng->SetCorrectionFactor( correction );
booleng->Do_Operation(BOOL_CORRECTION);
break;
case ('7'):
booleng->Do_Operation(BOOL_SMOOTHEN);
break;
case ('8'):
printf("give width of ring <return>:");
scanf("%f", &correction );
// create a ring of this size
booleng->SetCorrectionFactor( fabs( correction / 2.0) );
booleng->Do_Operation(BOOL_MAKERING);
break;
case ('9'):
break;
default:
break;
}
if (a != '0')
{
printf("\nresulting polygons\n" );
GetPolygonsFromBoolEng( booleng );
//OR USE THIS
//GetPolygonsFromBoolEngKEY( booleng );
printf( "\n\ntype a character and <return>");
scanf( "%c", &a );
}
delete booleng;
}
return 0;
}
/*! \file kbool/samples/boolonly/boolonly.h
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: boolonly.h,v 1.5 2005/05/24 19:13:38 titato Exp $
*/
#ifdef __GNUG__
#pragma implementation
#endif
#include "kbool/include/_lnk_itr.h"
#include "kbool/include/booleng.h"
class KBoolPoint
{
public:
KBoolPoint();
KBoolPoint(double const ,double const);
double GetX();
double GetY();
private:
double _x;
double _y;
};
IF(WIN32)
ADD_DEFINITIONS( -D_MSWVC_ )
ELSE(WIN32)
ADD_DEFINITIONS( -D__UNIX__ )
ENDIF(WIN32)
include_directories(${kbool_SOURCE_DIR}/include)
set(KBOOL_SRCS
booleng.cpp
graph.cpp
graphlst.cpp
line.cpp
link.cpp
lpoint.cpp
node.cpp
record.cpp
scanbeam.cpp)
ADD_LIBRARY( kbool ${KBOOL_SRCS})
/*! \file kbool/src/booleng.cpp
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: booleng.cpp,v 1.11 2005/05/24 19:13:38 titato Exp $
*/
#ifdef __GNUG__
#pragma implementation
#endif
#include <math.h>
#include <time.h>
#include "../include/booleng.h"
#include "../include/link.h"
#include "../include/line.h"
#include "../include/node.h"
#include "../include/graph.h"
#include "../include/graphlst.h"
B_INT bmin(B_INT const value1, B_INT const value2)
{
return((value1 < value2) ? value1 : value2 );
}
B_INT bmax(B_INT const value1, B_INT const value2)
{
return((value1 > value2) ? value1 : value2 );
}
B_INT babs(B_INT a)
{
if (a < 0) a=-a;
return a;
}
//-------------------------------------------------------------------/
//----------------- Bool_Engine_Error -------------------------------/
//-------------------------------------------------------------------/
Bool_Engine_Error::Bool_Engine_Error(const char* message, const char* header, int degree, int fatal)
{
_message = new char[LINELENGTH];
_header = new char[LINELENGTH];
if (message)
strcpy(_message, message);
else
strcpy(_message,"non specified");
if (header)
strcpy(_header, header);
else
strcpy(_header,"non specified");
_degree = degree;
_fatal = fatal;
}
Bool_Engine_Error::Bool_Engine_Error(const Bool_Engine_Error& a)
{
_message = new char[LINELENGTH];
_header = new char[LINELENGTH];
if (a._message)
strcpy(_message, a._message);
else
strcpy(_message,"non specified");
if (a._header)
strcpy(_header, a._header);
else
strcpy(_header,"non specified");
_degree = a._degree;
_fatal = a._fatal;
}
Bool_Engine_Error::~Bool_Engine_Error()
{
strcpy(_message,"");
strcpy(_header,"");
delete _message;
delete _header;
}
char* Bool_Engine_Error::GetErrorMessage()
{
return _message;
}
char* Bool_Engine_Error::GetHeaderMessage()
{
return _header;
}
int Bool_Engine_Error::GetErrorDegree()
{
return _degree;
}
int Bool_Engine_Error::GetFatal()
{
return _fatal;
}
//-------------------------------------------------------------------/
//----------------- Bool_Engine -------------------------------------/
//-------------------------------------------------------------------/
Bool_Engine::Bool_Engine()
{
_linkiter=new TDLI<KBoolLink>();
m_intersectionruns = 1;
m_orientationEntryMode = false;
m_doLinkHoles = true;
m_graphlist = new GraphList(this);
m_ACCUR = 1e-4;
m_WINDINGRULE = true;
m_GraphToAdd = NULL;
m_firstNodeToAdd = NULL;
m_lastNodeToAdd = NULL;
m_logfile = NULL;
#if KBOOL_LOG == 1
SetLog( true );
#else
SetLog( false );
#endif
}
Bool_Engine::~Bool_Engine()
{
if (m_logfile != NULL)
fclose (m_logfile);
delete _linkiter;
delete m_graphlist;
}
void Bool_Engine::SetLog( bool OnOff )
{
m_doLog = OnOff;
if ( m_doLog )
{
if ( m_logfile == NULL )
{
// create a new logfile
m_logfile = fopen(KBOOL_LOGFILE, "w");
if (m_logfile == NULL)
fprintf(stderr,"Bool_Engine: Unable to write to Boolean Engine logfile\n");
else
{
time_t timer;
struct tm * today;
timer = time(NULL);
today = localtime(&timer);
fprintf(m_logfile, "Logfile created on:\t\t\t%s", ctime( &timer ) );
}
}
}
else
{
if (m_logfile != NULL)
{
fclose (m_logfile);
m_logfile = NULL;
}
}
}
void Bool_Engine::SetState( const char* process )
{
Write_Log(process);
}
void Bool_Engine::error(const char *text,const char *title)
{
Write_Log("FATAL ERROR: ", title);
Write_Log("FATAL ERROR: ", text);
throw Bool_Engine_Error(" Fatal Error", "Fatal Error", 9, 1);
};
void Bool_Engine::info(const char *text, const char *title)
{
Write_Log("FATAL ERROR: ", title);
Write_Log("FATAL ERROR: ", text);
};
void Bool_Engine::SetMarge(double marge)
{
m_MARGE = marge;
Write_Log("Bool_Engine::m_MARGE = %f\n", m_MARGE);
}
double Bool_Engine::GetAccur()
{
return m_ACCUR;
}
void Bool_Engine::SetRoundfactor(double roundfac)
{
m_ROUNDFACTOR = roundfac;
Write_Log("Bool_Engine::m_ROUNDFACTOR = %f\n", m_ROUNDFACTOR);
}
double Bool_Engine::GetRoundfactor()
{
return m_ROUNDFACTOR;
}
double Bool_Engine::GetMarge()
{
return m_MARGE;
}
void Bool_Engine::SetDGrid(double dgrid)
{
m_DGRID = dgrid;
Write_Log("Bool_Engine::m_DGRID = %f\n", m_DGRID);
}
double Bool_Engine::GetDGrid()
{
return m_DGRID;
}
void Bool_Engine::SetGrid(B_INT grid)
{
m_GRID = grid;
Write_Log("Bool_Engine::m_GRID = %lld\n", m_GRID);
}
B_INT Bool_Engine::GetGrid()
{
return m_GRID;
}
void Bool_Engine::SetCorrectionAber(double aber)
{
m_CORRECTIONABER = aber;
Write_Log("Bool_Engine::m_CORRECTIONABER = %f\n", m_CORRECTIONABER);
}
double Bool_Engine::GetCorrectionAber()
{
return m_CORRECTIONABER;
}
void Bool_Engine::SetCorrectionFactor(double aber)
{
m_CORRECTIONFACTOR = aber;
Write_Log("Bool_Engine::m_CORRECTIONFACTOR = %f\n", m_CORRECTIONFACTOR );
}
double Bool_Engine::GetCorrectionFactor()
{
return m_CORRECTIONFACTOR;
}
void Bool_Engine::SetSmoothAber(double aber)
{
m_SMOOTHABER = aber;
Write_Log("Bool_Engine::m_SMOOTHABER = %f\n",m_SMOOTHABER );
}
double Bool_Engine::GetSmoothAber()
{
return m_SMOOTHABER;
}
void Bool_Engine::SetMaxlinemerge(double maxline)
{
m_MAXLINEMERGE = maxline;
Write_Log("Bool_Engine::m_MAXLINEMERGE = %f\n",m_MAXLINEMERGE );
}
double Bool_Engine::GetMaxlinemerge()
{
return m_MAXLINEMERGE;
}
void Bool_Engine::SetWindingRule(bool rule)
{
m_WINDINGRULE = rule;
}
bool Bool_Engine::GetWindingRule()
{
return m_WINDINGRULE;
}
void Bool_Engine::SetInternalMarge( B_INT marge )
{
m_MARGE = (double)marge/m_GRID/m_DGRID;
}
B_INT Bool_Engine::GetInternalMarge()
{
return (B_INT) ( m_MARGE*m_GRID*m_DGRID );
}
double Bool_Engine::GetInternalCorrectionAber()
{
return m_CORRECTIONABER*m_GRID*m_DGRID;
}
double Bool_Engine::GetInternalCorrectionFactor()
{
return m_CORRECTIONFACTOR*m_GRID*m_DGRID;
}
double Bool_Engine::GetInternalSmoothAber()
{
return m_SMOOTHABER*m_GRID*m_DGRID;
}
B_INT Bool_Engine::GetInternalMaxlinemerge()
{
return (B_INT) ( m_MAXLINEMERGE*m_GRID*m_DGRID );
}
#define TRIALS 30
bool Bool_Engine::Do_Operation(BOOL_OP operation)
{
#if KBOOL_DEBUG
GraphList* saveme = new GraphList( m_graphlist );
#endif
try
{
switch (operation)
{
case (BOOL_OR):
case (BOOL_AND):
case (BOOL_EXOR):
case (BOOL_A_SUB_B):
case (BOOL_B_SUB_A):
m_graphlist->Boolean(operation, m_intersectionruns);
break;
case (BOOL_CORRECTION):
m_graphlist->Correction();
break;
case (BOOL_MAKERING):
m_graphlist->MakeRings();
break;
case (BOOL_SMOOTHEN):
m_graphlist->Smoothen( GetInternalSmoothAber() );
break;
default:
{
error("Wrong operation","Command Error");
return false;
}
}
}
catch (Bool_Engine_Error& error)
{
#if KBOOL_DEBUG
delete m_graphlist;
m_graphlist = new GraphList( saveme );
m_graphlist->WriteGraphsKEY(this);
#endif
if (m_logfile != NULL)
{
fclose (m_logfile);
m_logfile = NULL;
}
info(error.GetErrorMessage(), "error");
throw error;
}
catch(...)
{
#if KBOOL_DEBUG
delete m_graphlist;
m_graphlist = new GraphList( saveme );
m_graphlist->WriteGraphsKEY(this);
#endif
if (m_logfile != NULL)
{
fclose (m_logfile);
m_logfile = NULL;
}
info("Unknown exception", "error");
throw ;
}
#if KBOOL_DEBUG
delete saveme;
#endif
return true;
}
bool Bool_Engine::StartPolygonAdd(GroupType A_or_B)
{
#if KBOOL_DEBUG
if (m_logfile != NULL)
fprintf(m_logfile, "-> StartPolygonAdd(%d)\n", A_or_B);
#endif
if (m_GraphToAdd != NULL)
return false;
Graph *myGraph = new Graph(this);
m_graphlist->insbegin(myGraph);
m_GraphToAdd = myGraph;
m_groupType = A_or_B;
return true;
}
bool Bool_Engine::AddPoint(double x, double y)
{
if (m_GraphToAdd == NULL){return false;}
double scaledx = x * m_DGRID * m_GRID;
double scaledy = y * m_DGRID * m_GRID;
if ( scaledx > MAXB_INT || scaledx < MINB_INT )
error("X coordinate of vertex to big", "" );
if ( scaledy > MAXB_INT || scaledy < MINB_INT )
error("Y coordinate of vertex to big", "" );
B_INT rintx = ((B_INT) (x * m_DGRID)) * m_GRID;
B_INT rinty = ((B_INT) (y * m_DGRID)) * m_GRID;
Node *myNode = new Node( rintx, rinty, this );
// adding first point to graph
if (m_firstNodeToAdd == NULL)
{
#if KBOOL_DEBUG
if (m_logfile != NULL)
{
fprintf(m_logfile, "-> AddPt() *FIRST* :");
fprintf(m_logfile, " input: x = %f, y = %f\n", x, y);
fprintf(m_logfile, " input: x = %I64d, y = %I64d\n", rintx, rinty) ;
}
#endif
m_firstNodeToAdd = (Node *) myNode;
m_lastNodeToAdd = (Node *) myNode;
}
else
{
#if KBOOL_DEBUG
if (m_logfile != NULL)
{
fprintf(m_logfile, "-> AddPt():");
fprintf(m_logfile, " input: x = %f, y = %f\n", x, y);
fprintf(m_logfile, " input: x = %I64d, y = %I64d\n", rintx, rinty) ;
}
#endif
m_GraphToAdd->AddLink(m_lastNodeToAdd, myNode);
m_lastNodeToAdd = (Node *) myNode;
}
return true;
}
bool Bool_Engine::EndPolygonAdd()
{
if (m_GraphToAdd == NULL) {return false;}
m_GraphToAdd->AddLink(m_lastNodeToAdd, m_firstNodeToAdd);
m_GraphToAdd->SetGroup(m_groupType);
m_GraphToAdd = NULL;
m_lastNodeToAdd = NULL;
m_firstNodeToAdd = NULL;
return true;
}
bool Bool_Engine::StartPolygonGet()
{
if (!m_graphlist->empty())
{
m_getGraph = (Graph*) m_graphlist->headitem();
m_getLink = m_getGraph->GetFirstLink();
m_getNode = m_getLink->GetBeginNode();
m_numPtsInPolygon = m_getGraph->GetNumberOfLinks();
m_numNodesVisited = 0;
return true;
}
else
{
return false;
}
}
bool Bool_Engine::PolygonHasMorePoints()
{
// see if first point
if (m_numNodesVisited == 0)
{
// don't need to touch the m_getNode
m_numNodesVisited++;
return true;
}
if (m_numNodesVisited < m_numPtsInPolygon)
{
// traverse to the next node
m_getNode = m_getLink->GetOther(m_getNode);
m_getLink = m_getLink->Forth(m_getNode);
m_numNodesVisited++;
return true;
}
else
{
return false;
}
}
void Bool_Engine::EndPolygonGet()
{
m_graphlist->removehead();
delete m_getGraph;
}
double Bool_Engine::GetPolygonXPoint()
{
return m_getNode->GetX()/m_GRID/m_DGRID;
}
double Bool_Engine::GetPolygonYPoint()
{
return m_getNode->GetY()/m_GRID/m_DGRID;
}
bool Bool_Engine::GetHoleSegment()
{
if (m_getLink->GetHole())
return true;
return false;
}
bool Bool_Engine::GetHoleConnectionSegment()
{
if (m_getLink->GetHoleLink())
return true;
return false;
}
kbEdgeType Bool_Engine::GetPolygonPointEdgeType()
{
// see if the point is the beginning of a false edge
if ( m_getLink->GetHoleLink() )
return KB_FALSE_EDGE;
else
// it's either an outside or inside edge
if ( m_getLink->GetHole() )
return KB_INSIDE_EDGE;
else
return KB_OUTSIDE_EDGE;
}
void Bool_Engine::Write_Log(const char *msg1)
{
if (m_logfile == NULL)
return;
fprintf(m_logfile,"%s \n",msg1);
}
void Bool_Engine::Write_Log(const char *msg1, const char*msg2)
{
if (m_logfile == NULL)
return;
fprintf(m_logfile,"%s %s\n",msg1, msg2);
}
void Bool_Engine::Write_Log(const char *fmt, double dval)
{
if (m_logfile == NULL)
return;
fprintf(m_logfile,fmt,dval);
}
void Bool_Engine::Write_Log(const char *fmt, B_INT bval)
{
if (m_logfile == NULL)
return;
fprintf(m_logfile,fmt,bval);
}
/*! \file ../src/graph.cpp
\brief Used to Intercect and other process functions
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: graph.cpp,v 1.13 2005/06/17 22:42:58 kbluck Exp $
*/
// Grpah is the structure used to store polygons
#ifdef __GNUG__
#pragma implementation
#endif
#include <math.h>
#include <assert.h>
#include "../include/booleng.h"
#include "../include/graph.h"
#include "../include/graphlst.h"
#include "../include/node.h"
// Prototype of function
int linkXYsorter(KBoolLink *, KBoolLink *);
int linkYXsorter(KBoolLink *, KBoolLink *);
int linkLsorter(KBoolLink *, KBoolLink *);
int linkYXtopsorter(KBoolLink *a, KBoolLink *b);
int linkGraphNumsorter(KBoolLink *_l1, KBoolLink* _l2);
// constructor, initialize with one link
// usage: Graph *a_graph = new Graph(a_link);
Graph::Graph(KBoolLink *a_link, Bool_Engine* GC )
{
_GC = GC;
_linklist=new DL_List<void*>();
_linklist->insbegin(a_link);
_bin = false;
}
// constructor, initialize graph with no contents
// usage: Graph *a_graph = new Graph();
Graph::Graph(Bool_Engine* GC)
{
_GC = GC;
_linklist=new DL_List<void*>();
_bin = false;
}
Graph::Graph( Graph* other )
{
_GC = other->_GC;
_linklist = new DL_List<void*>();
_bin = false;
int _nr_of_points = other->_linklist->count();
KBoolLink* _current = other->GetFirstLink();
Node* _last = _current->GetBeginNode();
Node* node = new Node( _current->GetBeginNode()->GetX(), _current->GetBeginNode()->GetY(), _GC );
Node* nodefirst = node;
for (int i = 0; i < _nr_of_points; i++)
{
// get the other node on the link
_last = _current->GetOther(_last);
// get the other link on the _last node
_current = _current->Forth(_last);
Node* node2 = new Node( _current->GetBeginNode()->GetX(), _current->GetBeginNode()->GetY(), _GC );
_linklist->insend( new KBoolLink( node, node2, _GC ) );
node = node2;
}
_linklist->insend( new KBoolLink( node, nodefirst, _GC ) );
}
// destructor
// deletes all object of the linklist
Graph::~Graph()
{
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
//first empty the graph
_LI.delete_all();
}
delete _linklist;
}
KBoolLink* Graph::GetFirstLink()
{
return (KBoolLink*) _linklist->headitem();
};
void Graph::Prepare( int intersectionruns )
{
_GC->SetState("Intersection");
bool found = true;
int run = 0;
while( run < intersectionruns && found )
{
found = CalculateCrossings(_GC->GetInternalMarge());
run++;
}
//WHY
// Round(_GC->Get_Grid());
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.foreach_mf(&KBoolLink::UnMark);// Reset Bin and Mark flag
}
_GC->SetState("Set group A/B Flags");
bool dummy = false;
if (_GC->GetWindingRule())
ScanGraph2( INOUT, dummy );
ScanGraph2( GENLR, dummy );
// writegraph();
_GC->SetState("Set operation Flags");
Set_Operation_Flags();
_GC->SetState("Remove doubles");
// Remove the marked links
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.tohead();
while(!_LI.hitroot())
{
if (_LI.item()->IsMarked())
{
delete _LI.item();
_LI.remove();
}
else
_LI++;
}
}
_GC->SetState("Remove inlinks");
Remove_IN_Links();
_GC->SetState("Finished prepare graph");
}
// x and y of the point will be rounded to the nearest
// xnew=N*grid and ynew=N*grid
void Graph::RoundInt(B_INT grid)
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.tohead();
while (!_LI.hitroot())
{
_LI.item()->GetBeginNode()->RoundInt(grid);
_LI.item()->GetEndNode()->RoundInt(grid);
_LI++;
}
}
// rotate graph minus 90 degrees or plus 90 degrees
void Graph::Rotate(bool plus90)
{
B_INT swap;
Node* last=NULL;
B_INT neg=-1;
if (plus90)
neg=1;
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.mergesort(linkXYsorter);
_LI.tohead();
while (!_LI.hitroot())
{
if (_LI.item()->GetBeginNode() != last)
{
swap=_LI.item()->GetBeginNode()->GetX();
_LI.item()->GetBeginNode()->SetX(-neg*(_LI.item()->GetBeginNode()->GetY()));
_LI.item()->GetBeginNode()->SetY(neg*swap);
last=_LI.item()->GetBeginNode();
}
_LI++;
}
}
bool Graph::RemoveNullLinks()
{
bool graph_is_modified = false;
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.tohead();
while (!_LI.hitroot())
{
if (_LI.item()->GetBeginNode() == _LI.item()->GetEndNode())
{
_LI.item()->MergeNodes(_LI.item()->GetBeginNode());
delete _LI.item();
_LI.remove();
graph_is_modified = true;
}
else
_LI++;
}
return (graph_is_modified);
}
// Add a link to the graph connection with
// other links is through the link his nodes
void Graph::AddLink(KBoolLink *a_link)
{
assert(a_link);
_linklist->insend(a_link);
}
// Add a link to the graph, by giving it two nodes
// the link is then made and added to the graph
void Graph::AddLink(Node *begin, Node *end)
{
assert(begin && end);
assert(begin != end);
AddLink(new KBoolLink(0, begin, end, _GC));
}
// Checks if there is a zeroline in the graph
bool Graph::AreZeroLines(B_INT Marge)
{
bool Found_it = false;
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.tohead();
while (!_LI.hitroot())
{
if (_LI.item()->IsZero(Marge))
{
Found_it = true;
break;
}
_LI++;
}
return Found_it;
}
// Delete links that do not fit the condition for given operation
void Graph::DeleteNonCond(BOOL_OP operation)
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.tohead();
while(!_LI.hitroot())
{
if ( !_LI.item()->IsMarked(operation))
{
delete _LI.item();
_LI.remove();
}
else
_LI++;
}
}
void Graph::HandleNonCond(BOOL_OP operation)
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.tohead();
while(!_LI.hitroot())
{
if ( !_LI.item()->IsMarked(operation))
{
_LI.item()->SetBeenHere();
_LI.item()->SetGraphNum( -1 );
}
_LI++;
}
}
// All lines in the graph wich have a length < _GC->Get_Marge() will be deleted
//
// input : a marge, standard on _GC->Get_Marge()
// return: true if lines in the graph are deleted
// : false if no lines in the graph are deleted
bool Graph::DeleteZeroLines(B_INT Marge)
{
// Is the graph modified ?
bool Is_Modified = false;
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
int Processed = _LI.count();
_LI.tohead();
while (Processed > 0)
{
Processed--;
if (_LI.item()->IsZero(Marge))
{
// the current link is zero, so make from both nodes one node
// and delete the current link from this graph
_LI.item()->MergeNodes(_LI.item()->GetBeginNode());
// if an item is deleted the cursor of the list is set to the next
// so no explicit forth is needed
delete _LI.item();
_LI.remove();
// we have to set Processed, because if a zero line is deleted
// another can be made zero by this deletion
Processed = _LI.count();
Is_Modified = true;
if (_LI.hitroot())
_LI.tohead();
}
else
_LI++;
if (_LI.hitroot())
_LI.tohead();
}
return Is_Modified;
}
// Collects a graph starting at currentnode or attached link
// follow graphs right around.
// since the input node is always a topleft node, we can see on
// a connected link if we or dealing with a hole or NON hole.
// for instance a top link of a hole that is horizontal, always
// is IN above the link and OUT underneath the link.
// this for a non hole the opposite
void Graph::CollectGraph(Node *current_node,BOOL_OP operation, bool detecthole,int graphnumber, bool& foundholes )
{
KBoolLink *currentlink;
KBoolLink *nextlink;
Node *next_node;
Node *MyFirst;
Node *Unlinked;
KBoolLink *MyFirstlink;
bool Hole;
LinkStatus whatside;
currentlink=current_node->GetNotFlat();
if (!currentlink)
{
char buf[100];
if (detecthole)
sprintf(buf,"no NON flat link Collectgraph for operation at %15.3lf , %15.3lf",
double(current_node->GetX()),double(current_node->GetY()));
else
sprintf(buf,"no NON flat link Collectgraph at %15.3lf , %15.3lf",
double(current_node->GetX()),double(current_node->GetY()));
throw Bool_Engine_Error(buf, "Error", 9, 0);
}
currentlink->SetBeenHere();
if (detecthole)
Hole = currentlink->IsHole(operation);
else
Hole = currentlink->GetHole(); //simple extract do not detect holes, but use hole flag.
currentlink->Redirect(current_node);
foundholes = Hole || foundholes;
//depending if we have a hole or not
//we take the left node or right node from the selected link (currentlink)
//this MEANS for holes go left around and for non holes go right around
//since the currentlink is already set to binhere, it will not go in that direction
if (Hole)
{
whatside = IS_LEFT;
if ( currentlink->GetEndNode()->GetX() > current_node->GetX())
current_node=currentlink->GetEndNode();
}
else
{
whatside = IS_RIGHT;
if ( currentlink->GetEndNode()->GetX() < current_node->GetX())
current_node=currentlink->GetEndNode();
}
currentlink->Redirect(current_node);
MyFirst=current_node; //remember this as the start
MyFirstlink=currentlink;
next_node = currentlink->GetEndNode();
// If this is a hole, Set as special link, this is the top link of this hole !
// from this link we have to make links to the link above later on.
if (Hole)
currentlink->SetTopHole(true);
//set also the link as being part of a hole
if (detecthole)
currentlink->SetHole(Hole);
currentlink->SetGraphNum(graphnumber);
// Walk over links and redirect them. taking most right links around
while (currentlink != NULL)
{
if ( Hole )
{
nextlink = next_node->GetMost(currentlink, IS_RIGHT, operation);
}
else
{
nextlink = next_node->GetMost(currentlink, IS_LEFT, operation);
// next works too if same is used in CollectGraphLast
//nextlink = next_node->GetMost(currentlink, IS_RIGHT, operation);
}
if (nextlink == NULL)
{ //END POINT MUST BE EQAUL TO BEGIN POINT
if (!next_node->Equal(MyFirst, 1))
{
throw Bool_Engine_Error("no next (endpoint != beginpoint)","graph", 9, 0);
//for god sake try this
//nextlink = next_node->GetMost(currentlink, whatside ,operation);
}
}
current_node = next_node;
if (nextlink!=NULL)
{
nextlink->Redirect(current_node);
nextlink->SetBeenHere();
next_node = nextlink->GetEndNode();
if ( current_node->GetNumberOfLinks() > 2)
{ // replace endnode of currentlink and beginnode of nextlink with new node
Unlinked = new Node(current_node, _GC);
currentlink->Replace(current_node,Unlinked);
nextlink->Replace(current_node,Unlinked);
}
if (detecthole)
nextlink->SetHole(Hole);
nextlink->SetGraphNum(graphnumber);
}
else
{
//close the found graph properly
if ( current_node->GetNumberOfLinks() > 2)
{ // replace endnode of currentlink and beginnode of nextlink with new node
Unlinked = new Node(current_node, _GC);
currentlink->Replace(current_node,Unlinked);
MyFirstlink->Replace(current_node,Unlinked);
}
}
currentlink = nextlink;
}
//END POINT MUST BE EQAUL TO BEGIN POINT
if (!current_node->Equal(MyFirst, 1))
{
throw Bool_Engine_Error("in collect graph endpoint != beginpoint", "Error", 9, 0);
}
}
void Graph::CollectGraphLast(Node *current_node,BOOL_OP operation, bool detecthole,int graphnumber, bool& foundholes )
{
KBoolLink *currentlink;
KBoolLink *nextlink;
Node *next_node;
Node *MyFirst;
Node *Unlinked;
KBoolLink *MyFirstlink;
bool Hole;
LinkStatus whatside;
currentlink=current_node->GetNotFlat();
if (!currentlink)
{
char buf[100];
if (detecthole)
sprintf(buf,"no NON flat link Collectgraph for operation at %15.3lf , %15.3lf",
double(current_node->GetX()),double(current_node->GetY()));
else
sprintf(buf,"no NON flat link Collectgraph at %15.3lf , %15.3lf",
double(current_node->GetX()),double(current_node->GetY()));
throw Bool_Engine_Error(buf, "Error", 9, 0);
}
currentlink->SetBeenHere();
if (detecthole)
Hole = currentlink->IsHole(operation);
else
Hole = currentlink->GetHole(); //simple extract do not detect holes, but use hole flag.
currentlink->Redirect(current_node);
foundholes = Hole || foundholes;
//depending if we have a hole or not
//we take the left node or right node from the selected link (currentlink)
//this MEANS for holes go left around and for non holes go right around
//since the currentlink is already set to binhere, it will not go in that direction
if (Hole)
{
whatside = IS_LEFT;
if ( currentlink->GetEndNode()->GetX() > current_node->GetX())
current_node=currentlink->GetEndNode();
}
else
{
whatside = IS_RIGHT;
if ( currentlink->GetEndNode()->GetX() < current_node->GetX())
current_node=currentlink->GetEndNode();
}
currentlink->Redirect(current_node);
MyFirst=current_node; //remember this as the start
MyFirstlink=currentlink;
next_node = currentlink->GetEndNode();
// If this is a hole, Set as special link, this is the top link of this hole !
// from this link we have to make links to the link above later on.
if (Hole)
currentlink->SetTopHole(true);
currentlink->SetGraphNum(graphnumber);
// Walk over links and redirect them. taking most right links around
while (currentlink != NULL)
{
if ( Hole )
{
if ( currentlink->GetHoleLink() )
{
//in case we entered the hole via the hole link just now, we followe the hole.
//This is taking as many holes as possible ( most right around)
nextlink = next_node->GetMostHole(currentlink, IS_RIGHT ,operation );
if ( !nextlink ) // hole done?
//if we did get to this hole via a holelink?, then we might now be on the return link.
//BTW it is also possible that holes are already found via a non linked hole path,
//in that case, we did go to the HoleLink here, and directly return on the other holelink.
nextlink = next_node->GetHoleLink(currentlink, true, operation );
if ( !nextlink )
{
//we did get to this hole via a holelink and we are on the returning holelink.
//So we left the hole collection, and continue with contours.
//Most Right is needed!
nextlink = next_node->GetMost(currentlink, IS_RIGHT, operation);
}
}
else
{
nextlink = next_node->GetHoleLink(currentlink, true, operation ); // other linked holes first
if ( !nextlink )
nextlink = next_node->GetMostHole(currentlink, IS_RIGHT, operation ); // other holes first
if ( !nextlink )
{
//We are leaving the hole.
//So we left the hole collection, and continue with contours.
//Most Right is needed!
nextlink = next_node->GetMost(currentlink, IS_RIGHT, operation);
}
}
}
else
{
//a hole link is preferred above a normal link. If not no holes would be linked in anyway.
nextlink = next_node->GetHoleLink(currentlink, true, operation );
if ( !nextlink )
//also if we can get to a hole directly within a contour, that is better (get as much as possible)
nextlink = next_node->GetMostHole(currentlink, IS_RIGHT, operation);
if ( !nextlink )
//if non of the above, we are still on the contour and take as must as possible to the left.
//Like that we take as many contour togethere as possible.
nextlink = next_node->GetMost(currentlink, IS_LEFT, operation);
// next works too if same is used in CollectGraphLast
//nextlink = next_node->GetMost(currentlink, IS_RIGHT, operation);
}
if (nextlink == NULL)
{ //END POINT MUST BE EQAUL TO BEGIN POINT
if (!next_node->Equal(MyFirst, 1))
{
throw Bool_Engine_Error("no next (endpoint != beginpoint)","graph", 9, 0);
//for god sake try this
//nextlink = next_node->GetMost(currentlink, whatside, operation);
}
}
else
{
// when holes are already know, use the hole information to
// go left are right around.
Hole = nextlink->GetHole() || nextlink->GetHoleLink();
}
current_node = next_node;
if (nextlink!=NULL)
{
nextlink->Redirect(current_node);
nextlink->SetBeenHere();
next_node = nextlink->GetEndNode();
if ( current_node->GetNumberOfLinks() > 2)
{ // replace endnode of currentlink and beginnode of nextlink with new node
Unlinked = new Node(current_node, _GC);
currentlink->Replace(current_node,Unlinked);
nextlink->Replace(current_node,Unlinked);
}
nextlink->SetGraphNum(graphnumber);
}
else
{
//close the found graph properly
if ( current_node->GetNumberOfLinks() > 2)
{ // replace endnode of currentlink and beginnode of nextlink with new node
Unlinked = new Node(current_node, _GC);
currentlink->Replace(current_node,Unlinked);
MyFirstlink->Replace(current_node,Unlinked);
}
}
currentlink = nextlink;
}
//END POINT MUST BE EQAUL TO BEGIN POINT
if (!current_node->Equal(MyFirst, 1))
{
throw Bool_Engine_Error("in collect graph endpoint != beginpoint", "Error", 9, 0);
}
}
//==============================================================================
//==============================================================================
// Extract bi-directional graphs from this graph
// Mark the graphs also as being a hole or not.
void Graph::Extract_Simples(BOOL_OP operation, bool detecthole, bool& foundholes )
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
if (_LI.empty()) return;
Node *begin;
int graphnumber=1;
_LI.mergesort(linkYXtopsorter);
_LI.tohead();
while (true)
{
begin = GetMostTopLeft(&_LI); // from all the most Top nodes,
// take the most left one
// to most or not to most, that is the question
if (!begin)
break;
try // collect the graph
{
if ( detecthole )
CollectGraph( begin,operation,detecthole,graphnumber++, foundholes );
else
//CollectGraph( begin,operation,detecthole,graphnumber++, foundholes );
CollectGraphLast( begin,operation,detecthole,graphnumber++, foundholes );
}
catch (Bool_Engine_Error& error)
{
_GC->info(error.GetErrorMessage(), "error");
throw error;
}
}
}
void Graph::Split(GraphList* partlist)
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
if (_LI.empty()) return;
Graph *part = NULL;
int graphnumber=0;
//sort the graph on graphnumber
_LI.mergesort(linkGraphNumsorter);
_LI.tohead();
while (!_LI.hitroot())
{
if ( _LI.item()->GetGraphNum() > 0 && graphnumber != _LI.item()->GetGraphNum())
{
graphnumber=_LI.item()->GetGraphNum();
part = new Graph(_GC);
partlist->insend(part);
}
KBoolLink* tmp=_LI.item();
if ( _LI.item()->GetGraphNum() > 0 )
{
part->AddLink(tmp);
}
else
{
delete tmp;
}
_LI.remove();
}
}
bool Graph::GetBeenHere()
{
return _bin;
}
// return total number of links in this graph
int Graph::GetNumberOfLinks()
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
return _LI.count();
}
//for all operations set the operation flags for the links
//based on the Group_Left_Right values
void Graph::Set_Operation_Flags()
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.tohead();
while(!_LI.hitroot())
{
_LI.item()->SetLineTypes();
_LI++;
}
}
// Remove unused (those not used for any operation) links
void Graph::Remove_IN_Links()
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.tohead();
for (int t = _LI.count() ; t > 0; t--)
{
// Is this link not used for any operation?
if (_LI.item()->IsUnused())
{
delete _LI.item();
_LI.remove();
}
else
_LI++;
}
}
void Graph::ResetBinMark()
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
if (_LI.empty()) return;
_LI.foreach_mf(&KBoolLink::UnMark);//reset bin and mark flag of each link
}
void Graph::ReverseAllLinks()
{
Node *dummy;
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.tohead();
while (!_LI.hitroot())
{
// swap the begin- and endnode of the current link
dummy = _LI.item()->GetBeginNode();
_LI.item()->SetBeginNode(_LI.item()->GetEndNode());
_LI.item()->SetEndNode(dummy);
_LI++;
}
}
void Graph::SetBeenHere(bool value)
{
_bin=value;
}
// ReSet the flags of the links
void Graph::Reset_flags()
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.foreach_mf(&KBoolLink::Reset_flags);
}
// ReSet the bin and mark flag of the links
void Graph::Reset_Mark_and_Bin()
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.foreach_mf(&KBoolLink::UnMark);//reset bin and mark flag of each link
}
// Set the group of the links to the same as newgroup
void Graph::SetGroup(GroupType newgroup)
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.tohead();
while (!_LI.hitroot())
{
_LI.item()->SetGroup(newgroup);
_LI++;
}
}
// Set the number of the links to the same as newnr
void Graph::SetNumber(const int newnr)
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.tohead();
while (!_LI.hitroot())
{
_LI.item()->SetGraphNum(newnr);
_LI++;
}
}
// This function will simplify a graph with the following rules
//
// This are the rules for symplifying the graphs
// 1. The following point is the same as the current one
// 2. The point after the following point is the same as the current one
// 3. The point after the following point lies on the same line as the current
//
// input : a marge
// return: true if graph is modified
// : false if graph is NOT simplified
bool Graph::Simplify( B_INT Marge )
{
bool graph_is_modified = false;
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
int Processed = _LI.count();
_LI.foreach_mf(&KBoolLink::UnMark);//reset bin and mark flag of each link
_LI.tohead();
GroupType mygroup=_LI.item()->Group();
// All items must be processed
while (Processed > 0)
{
// Gives the number of items to process
Processed--;
// Check if line is marked
// Links will be marked during the process
if (_LI.item()->IsMarked())
{
delete _LI.item();
_LI.remove();
graph_is_modified = true;
Processed = _LI.count();
if (_LI.hitroot())
_LI.tohead();
continue;
}
// Line is not marked, check if line is zero
if (_LI.item()->IsZero(Marge))
{
_LI.item()->MergeNodes(_LI.item()->GetBeginNode());
delete _LI.item();
_LI.remove();
graph_is_modified = true;
Processed = _LI.count();
if (_LI.hitroot())
_LI.tohead();
continue;
}
// begin with trying to simplify the link
{
// Line is not marked, not zero, so maybe it can be simplified
bool virtual_link_is_modified;
Node *new_begin, *new_end, *a_node;
KBoolLink *a_link;
_LI.item()->Mark();
new_begin = _LI.item()->GetBeginNode();
new_end = _LI.item()->GetEndNode();
// while virtual link is modified
do
{
virtual_link_is_modified = false;
// look in the previous direction
if ((a_link = new_begin->GetPrevLink()) != NULL)
{
a_node = a_link->GetBeginNode();
if (a_node->Simplify(new_begin,new_end,Marge))
{
new_begin->GetPrevLink()->Mark();
new_begin = a_node;
virtual_link_is_modified = true;
}
}
// look in the next direction
if ((a_link = new_end->GetNextLink()) != NULL)
{
a_node = a_link->GetEndNode();
if (a_node->Simplify(new_begin,new_end,Marge))
{
new_end->GetNextLink()->Mark();
new_end = a_node;
virtual_link_is_modified = true;
}
}
graph_is_modified = (bool) (graph_is_modified || virtual_link_is_modified);
} while (virtual_link_is_modified);
// was the link simplified
if ((_LI.item()->GetBeginNode() != new_begin) ||
(_LI.item()->GetEndNode() != new_end))
{
// YES !!!!!
int number = _LI.item()->GetGraphNum();
delete _LI.item();
_LI.remove();
if (_LI.hitroot())
_LI.tohead();
KBoolLink *newlink = new KBoolLink(number, new_begin, new_end, _GC);
newlink->SetGroup(mygroup);
_LI.insend(newlink);
Processed = _LI.count();
graph_is_modified = true;
continue;
}
_LI.item()->UnMark();
} // end of try to simplify
_LI++;
if (_LI.hitroot())
_LI.tohead();
}//end while all processed
return graph_is_modified;
}
/*
// This function will smoothen a graph with the following rules
//
// 0. Process graphs with more than 3 links only. (while more than 3)
// Otherwise some objects may end-up as lines or disappear completely.
// 1.
// a. ? Does begin-node lay on line(prevline.beginnode,endnode)
// -> merge beginnode to endnode
// b. ? Does end-node lay on line(beginnode,nextline.endnode)
// -> merge endnode to beginnode
// 2.
// a. ? Is distance between prevline.beginnode and endnode to short
// -> merge beginnode to endnode
// b. ? Is distance between beginnode and nextline.endnode to short
// -> merge endnode to beginnode
// 3.
// a. ? Does (this)beginnode lay in area of nextline
// AND does cross-node lay on nextline
// -> move endnode to crossing of prevline and nextline
// b. ? Does (this)endnode lay in area of prevline
// AND does cross-node lay on prevline
// -> move beginnode to crossing of prevline and nextline
// 4.
// ? Is this link too short
// ? Is prevline shorter than nextline
// Y -> ? Is prevlink shorter than maxlength
// -> merge endnode to beginnode
// N -> ? Is nextlink shorter than maxlength
// -> merge endnode to beginnode
//
//
// Types of glitches / lines to remove :
//
// \ / \ / \ /
// Z---A---B OR Z-------B---A => Z-------B
//
// (1)
//
// ----A C---- => ----A-----C----
// \ /
// (2) \ /
// B
//
// ---Z ---Z
// \ \
// (3) \ \
// \ B----------C-- => A---B----------C--
// \ /
// A
//
// --Z---A --Z__
// \ -__
// (4) B------------C-- => B------------C--
//
// linkLsorter(L1,L2)
// ret:
// +1 L1 < L2
// 0 L1 == L2
// -1 L1 > L2
//
*/
bool Graph::Smoothen( B_INT Marge )
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
if (_LI.count()<=3) // Don't modify it
return false;
Node *Z, *A, *B, *C, *cross_node = new Node(_GC);
KBoolLink *prevlink, *nextlink, *thislink;
KBoolLine prevline(_GC), nextline(_GC), thisline(_GC);
KBoolLine prevhelp(_GC), nexthelp(_GC);
KBoolLink LZB(new Node(_GC), new Node(_GC), _GC),
LAC(new Node(_GC), new Node(_GC), _GC);
double distance=0;
double prevdist,nextdist;
bool doprev, donext;
bool graph_is_modified = false;
bool kill = false; // for first instance
_LI.tohead();
int todo = _LI.count();
thislink=_LI.item();
B = thislink->GetEndNode();
nextlink = thislink->Forth(B);
// Type 1
while (todo>0)
{
if (kill==true)
{
// remove link from graph
_LI.toitem(thislink);
graph_is_modified = true;
delete _LI.item();
_LI.remove();
kill=false;
thislink=nextlink;
todo--;
if (_LI.count()<3)
break;
}
A = thislink->GetBeginNode();
B = thislink->GetEndNode();
if (A->ShorterThan(B,1))
{
A->Merge(B);
kill = true;
continue;
}
Z = thislink->Forth(A)->GetBeginNode();
C = thislink->Forth(B)->GetEndNode();
thisline.Set(thislink);
thisline.CalculateLineParameters();
nextlink = thislink->Forth(B);
if (thisline.PointInLine(Z,distance,0.0) == ON_AREA)
{ // Z--A--B => Z--B Merge this to previous
thislink->MergeNodes(B); // remove A
kill = true;
continue;
}
else if (thisline.PointInLine(C,distance,0.0) == ON_AREA)
{ // A--B--C => A--C Merge this to next
thislink->MergeNodes(A); // remove B
kill = true;
continue;
}
thislink=nextlink;
todo--;
}
kill=false;
todo = _LI.count();
_LI.mergesort(linkLsorter);
_LI.tohead();
while (todo>0)
{
if (kill==true)
{
delete _LI.item();
_LI.remove();
graph_is_modified = true;
kill = false;
//mergesort(linkLsorter);
_LI.mergesort(linkLsorter);
_LI.tohead();
todo = _LI.count();
if (todo<3) // A polygon, at least, has 3 sides
break;
}
// Keep this order!
thislink = _LI.item();
A = thislink->GetBeginNode();
B = thislink->GetEndNode();
prevlink = thislink->Forth(A);
nextlink = thislink->Forth(B);
Z = prevlink->GetBeginNode();
C = nextlink->GetEndNode();
if (A->ShorterThan(B,1))
{
A->Merge(B);
kill = true;
continue;
}
prevline.Set(prevlink);
prevline.CalculateLineParameters();
nextline.Set(nextlink);
nextline.CalculateLineParameters();
// Type 2
if (B->ShorterThan(Z,Marge))
{ // Z--A--B => Z--B Merge this to previous
thislink->MergeNodes(B); // remove A
kill = true;
continue;
}
else if (A->ShorterThan(C,Marge))
{ // A--B--C => A--C Merge this to next
thislink->MergeNodes(A); // remove B
kill = true;
continue;
}
*LZB.GetBeginNode()=*Z;
*LZB.GetEndNode()=*B;
*LAC.GetBeginNode()=*A;
*LAC.GetEndNode()=*C;
prevhelp.Set(&LZB);
nexthelp.Set(&LAC);
prevhelp.CalculateLineParameters();
nexthelp.CalculateLineParameters();
// Type 4
doprev = bool(prevhelp.PointInLine(A,prevdist,(double)Marge) == IN_AREA);
donext = bool(nexthelp.PointInLine(B,nextdist,(double)Marge) == IN_AREA);
doprev = bool(B->ShorterThan(Z,_GC->GetInternalMaxlinemerge()) && doprev);
donext = bool(A->ShorterThan(C,_GC->GetInternalMaxlinemerge()) && donext);
if (doprev && donext)
{
if (fabs(prevdist)<=fabs(nextdist))
thislink->MergeNodes(B); // remove A
else
thislink->MergeNodes(A); // remove B
kill = true;
continue;
}
else if (doprev)
{
thislink->MergeNodes(B); // remove A
kill = true;
continue;
}
else if (donext)
{
thislink->MergeNodes(A); // remove B
kill = true;
continue;
}
thisline.Set(thislink);
thisline.CalculateLineParameters();
// Type 1
if (thisline.PointInLine(Z,distance,0.0) == ON_AREA)
{ // Z--A--B => Z--B Merge this to previous
thislink->MergeNodes(B); // remove A
kill = true;
continue;
}
else if (thisline.PointInLine(C,distance,0.0) == ON_AREA)
{ // A--B--C => A--C Merge this to next
thislink->MergeNodes(A); // remove B
kill = true;
continue;
}
// Type 3
if (nextline.PointInLine(A,distance, (double) Marge)==IN_AREA)
{
if (nextline.Intersect2(cross_node,&prevline))
{
if (nextline.PointInLine(cross_node,distance,0.0)==IN_AREA)
{
B->Set(cross_node);
thislink->MergeNodes(B); // remove A
kill=true;
continue;
}
else
{
thislink->MergeNodes(A); // remove B
kill=true;
continue;
}
}
else
{
thislink->MergeNodes(A); // remove B
kill=true;
continue;
}
}
// Type 3
if (prevline.PointInLine(B,distance,(double)Marge)==IN_AREA)
{
if (prevline.Intersect2(cross_node,&nextline))
{
if (prevline.PointInLine(cross_node,distance,0.0)==IN_AREA)
{
A->Set(cross_node);
thislink->MergeNodes(A); // remove B
kill=true;
continue;
}
else
{
thislink->MergeNodes(B); // remove A
kill=true;
continue;
}
}
else
{
thislink->MergeNodes(B); // remove A
kill=true;
continue;
}
}
todo--;
_LI++;
} // end: while all processed
delete cross_node;
return graph_is_modified;
}
// Give the graphnumber of the first link in the graphlist
int Graph::GetGraphNum()
{
return ((KBoolLink*)_linklist->headitem())->GetGraphNum();
}
// get the node with the highest Y value
Node* Graph::GetTopNode()
{
B_INT max_Y = MAXB_INT;
Node* result;
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.tohead();
while (!_LI.hitroot())
{
if (!(_LI.item()->GetBeginNode()->GetY() < max_Y))
break;
_LI++;
}
result = _LI.item()->GetBeginNode();
return result;
}
// THE GRAPH MUST be SORTED before using this function
// mergesort(linkYXtopsorter);
// Get the mostleft top node from the graph for which the link flag is not set yet
Node* Graph::GetMostTopLeft(TDLI<KBoolLink>* _LI)
{
while (!_LI->hitroot())
{
if (!_LI->item()->BeenHere())
{
KBoolLink* a=_LI->item();
//find the top node of this link (sorted on top allready)
if (a->GetBeginNode()->GetY() > a->GetEndNode()->GetY())
return(a->GetBeginNode());
if (a->GetBeginNode()->GetY() < a->GetEndNode()->GetY())
return(a->GetEndNode());
else
return(a->GetBeginNode());
}
(*_LI)++;
}
return NULL;
}
// Take the linkslist over from a other graph
// The linklist of the other graph will be empty afterwards
void Graph::TakeOver(Graph *other)
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.takeover( other->_linklist);
}
// calculate crossing with scanbeams
bool Graph::CalculateCrossings(B_INT Marge)
{
// POINT <==> POINT
_GC->SetState("Node to Node");
bool found = false;
bool dummy = false;
found = Merge_NodeToNode(Marge) != 0;
if (_linklist->count() < 3)
return found;
// POINT <==> LINK
_GC->SetState("Node to KBoolLink 0");
found = ScanGraph2(NODELINK, dummy) != 0 || found;
_GC->SetState("Rotate -90");
Rotate(false);
_GC->SetState("Node to KBoolLink -90");
found = ScanGraph2(NODELINK, dummy) != 0 || found;
_GC->SetState("Rotate +90");
Rotate(true);
// LINK <==> LINK
_GC->SetState("intersect");
found = ScanGraph2(LINKLINK, dummy) != 0 || found;
/*
if (!checksort())
{ {
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.mergesort(linkXYsorter);
}
writeintersections();
writegraph(true);
}
*/
// Rotate(false);
// _GC->SetState("KBoolLink to KBoolLink -90");
// ScanGraph2(LINKLINK);
// Rotate(true);
writegraph(true);
_GC->Write_Log("Node to Node");
_GC->SetState("Node to Node");
found = Merge_NodeToNode(Marge) != 0 || found;
writegraph(true);
return found;
}
// neem de nodes die binnen de margeafstand bij elkaar liggen samen RICHARD
int Graph::Merge_NodeToNode(B_INT Marge)
{
//aantal punten dat verplaatst is
int merges = 0;
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
//unmark all links; markflag wordt gebruikt om aan te geven
//of een link (eigenlijk beginnode ervan) al verwerkt is
_LI.foreach_mf(&KBoolLink::UnMark);
//sort links on x value of beginnode
_LI.mergesort(linkXYsorter);
//extra iterator voor doorlopen links in graph
{
TDLI<KBoolLink> links=TDLI<KBoolLink>(_linklist);
Node *nodeOne, *nodeTwo;
//verwerk alle links (alle (begin)nodes)
for(_LI.tohead(); !_LI.hitroot(); _LI++)
{
nodeOne = _LI.item()->GetBeginNode();
// link (beginnode) al verwerkt?
if(!_LI.item()->IsMarked())
{
// wordt verwerkt dus markeer
_LI.item()->Mark();
// doorloop alle links vanaf huidige tot link buiten marge
links.toiter(&_LI);links++;
while (!links.hitroot())
{
nodeTwo = links.item()->GetBeginNode();
// marked?
if(!links.item()->IsMarked())
{
// x van beginnode vd link binnen marge?
if(babs(nodeOne->GetX()-nodeTwo->GetX()) <= Marge )
{
// y van beginnode vd link binnen marge?
// zijn twee node-object referenties wel verschillend?
if(babs(nodeOne->GetY()-nodeTwo->GetY()) <= Marge &&
(!(nodeOne == nodeTwo))
)
{
links.item()->Mark();
nodeOne->Merge(nodeTwo);
merges++;
}//y binnen marge en niet zelfde node
}//x binnen marge?
else
{
// link valt buiten marge; de rest vd links
// dus ook (omdat lijst gesorteerd is)
links.totail();
}
}//marked?
links++;
}//current -> ongeldig
}//verwerkt?
}//all links
}//om de extra iterator te verwijderen
}
RemoveNullLinks();
return merges;
}
int Graph::ScanGraph2(SCANTYPE scantype, bool& holes )
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
int found=0;
//sort links on x and y value of beginnode
_LI.mergesort(linkXYsorter);
writegraph( false );
//bin flag is used in scanbeam so reset
_LI.foreach_mf(&KBoolLink::SetNotBeenHere);
ScanBeam* scanbeam = new ScanBeam(_GC);
Node* _low;
Node* _high;
_LI.tohead();
while (!_LI.attail())
{
_low = _LI.item()->GetBeginNode();
//find new links for the new beam and remove the old links
if ( scanbeam->FindNew(scantype,&_LI, holes ) )
found++;
//find a new low node, this should be a node not eqaul to the current _low
do
{ _LI++;}
while (!_LI.hitroot() && (_low == _LI.item()->GetBeginNode()));
if (_LI.hitroot())
//if the last few links share the same beginnode
//we arive here
break;
else
_high=_LI.item()->GetBeginNode();
scanbeam->SetType(_low,_high);
if (scanbeam->RemoveOld(scantype,&_LI, holes ) )
found++;
}
delete scanbeam;
return found;
}
/*
// scanbeam->writebeam();
if (j%100 ==0)
{
long x;
long y;
char buf[80];
x=(long)_lowlink->GetBeginNode()->GetX();
y=(long)_lowlink->GetBeginNode()->GetY();
sprintf(buf," x=%I64d , y=%I64d here %I64d",x,y,scanbeam->count());
_GC->SetState(buf);
scanbeam->writebeam();
}
writegraph(false);
if (!checksort())
{
double x=_lowlink->GetBeginNode()->GetX();
checksort();
}
_LI++;
}
}
delete scanbeam;
return 0;
}
if (!checksort())
{
x=_lowlink->GetBeginNode()->GetX();
checksort();
}
if (x >= -112200)
{
// writegraph(true);
// scanbeam->writebeam();
}
*/
//=============================== Global Functions =============================
// Sorts the links on the X values
int linkXYsorter(KBoolLink *a, KBoolLink* b)
{
if ( a->GetBeginNode()->GetX() < b->GetBeginNode()->GetX())
return(1);
if ( a->GetBeginNode()->GetX() > b->GetBeginNode()->GetX())
return(-1);
//they are eqaul in x
if ( a->GetBeginNode()->GetY() < b->GetBeginNode()->GetY())
return(-1);
if ( a->GetBeginNode()->GetY() > b->GetBeginNode()->GetY())
return(1);
//they are eqaul in y
return(0);
}
// Sorts the links on the Y value of the beginnode
int linkYXsorter(KBoolLink *a, KBoolLink* b)
{
if ( a->GetBeginNode()->GetY() > b->GetBeginNode()->GetY())
return(1);
if ( a->GetBeginNode()->GetY() < b->GetBeginNode()->GetY())
return(-1);
if ( a->GetBeginNode()->GetX() > b->GetBeginNode()->GetX())
return(-1);
if ( a->GetBeginNode()->GetX() < b->GetBeginNode()->GetX())
return(1);
return(0);
}
// The sort function for sorting graph from shortest to longest (_l1 < _l2)
int linkLsorter(KBoolLink *_l1, KBoolLink* _l2)
{
B_INT dx1,dx2,dy1,dy2;
dx1 = (_l1->GetEndNode()->GetX() - _l1->GetBeginNode()->GetX());
dx1*=dx1;
dy1 = (_l1->GetEndNode()->GetY() - _l1->GetBeginNode()->GetY());
dy1*=dy1;
dx2 = (_l2->GetEndNode()->GetX() - _l2->GetBeginNode()->GetX());
dx2*=dx2;
dy2 = (_l2->GetEndNode()->GetY() - _l2->GetBeginNode()->GetY());
dy2*=dy2;
dx1+=dy1; dx2+=dy2;
if ( dx1 > dx2 )
return(-1);
if ( dx1 < dx2 )
return(1);
return(0);
}
// The sort function for the links in a graph (a.topnode < b.topnode)
// if the two links lay with the top nodes on eachother the most left will be selected
int linkYXtopsorter(KBoolLink *a, KBoolLink *b)
{
if (bmax(a->GetBeginNode()->GetY(),a->GetEndNode()->GetY()) < bmax(b->GetBeginNode()->GetY(),b->GetEndNode()->GetY()))
return -1;
if (bmax(a->GetBeginNode()->GetY(),a->GetEndNode()->GetY()) > bmax(b->GetBeginNode()->GetY(),b->GetEndNode()->GetY()))
return 1;
//equal
if (bmin(a->GetBeginNode()->GetX(),a->GetEndNode()->GetX()) < bmin(b->GetBeginNode()->GetX(),b->GetEndNode()->GetX()))
return -1;
if (bmin(a->GetBeginNode()->GetX(),a->GetEndNode()->GetX()) > bmin(b->GetBeginNode()->GetX(),b->GetEndNode()->GetX()))
return 1;
return 0;
}
// The sort function for sorting graph from shortest to longest (_l1 < _l2)
int linkGraphNumsorter(KBoolLink *_l1, KBoolLink* _l2)
{
if ( _l1->GetGraphNum() > _l2->GetGraphNum())
return(-1);
if ( _l1->GetGraphNum() < _l2->GetGraphNum())
return(1);
return(0);
}
// Perform an operation on the graph
void Graph::Boolean(BOOL_OP operation,GraphList* Result)
{
_GC->SetState("Performing Operation");
// At this moment we have one graph
// step one, split it up in single graphs, and mark the holes
// step two, make one graph again and link the holes
// step three, split up again and dump the result in Result
_GC->SetState("Extract simples first ");
ResetBinMark();
DeleteNonCond(operation);
HandleNonCond(operation);
bool foundholes = false;
try
{
WriteGraphKEY(_GC);
writegraph(true);
Extract_Simples(operation,true, foundholes);
}
catch (Bool_Engine_Error& error)
{
throw error;
}
// now we will link all the holes in de graphlist
// By the scanbeam method we will search all the links that are marked
// as topleft link of a the hole polygon, when we find them we will get the
// closest link, being the one higher in the beam.
// Next we will create a link and nodes toceoonect the hole into it outside contour
// or other hole.
_GC->SetState("Linking Holes");
if (_linklist->count() == 0)
//extract simples did leaf an empty graph
//so we are ready
return;
if ( foundholes && _GC->GetLinkHoles() )
{
//the first extract simples introduced nodes at the same location that are not merged.
//e.g. Butterfly polygons as two seperate polygons.
//The scanlines can not cope with this, so merge them, and later extract one more time.
Merge_NodeToNode(0);
_GC->Write_Log("LINKHOLES\n");
writegraph( false );
//link the holes into the non holes if there are any.
bool holes = false;
ScanGraph2(LINKHOLES, holes );
WriteGraphKEY(_GC);
writegraph(true);
if ( holes )
{
//to delete extra points
//those extra points are caused by link holes
//and are eqaul
DeleteZeroLines(1);
_GC->SetState("extract simples last");
ResetBinMark();
HandleNonCond(operation);
DeleteNonCond(operation);
Extract_Simples(operation,false, foundholes);
}
}
writegraph( true );
Split(Result);
}
// Perform an correction on the graph
void Graph::Correction( GraphList* Result, double factor )
{
// At this moment we have one graph
// step one, split it up in single graphs, and mark the holes
// step two, make one graph again and link the holes
// step three, split up again and dump the result in Result
_GC->SetState("Extract simple graphs");
//extract the (MERGE or OR) result from the graph
if (Simplify(_GC->GetGrid()))
if (GetNumberOfLinks() < 3)
return;
Graph* original=new Graph(_GC);
{
if (_linklist->empty()) return;
KBoolLink* _current = GetFirstLink();
Node *_first = new Node(_current->GetBeginNode(), _GC);
Node *_last = _current->GetBeginNode();
Node *_begin = _first;
Node *_end = _first;
int _nr_of_points = GetNumberOfLinks();
for (int i = 1; i < _nr_of_points; i++)
{
// get the other node on the link
_last = _current->GetOther(_last);
// make a node from this point
_end = new Node(_last, _GC);
// make a link between begin and end
original->AddLink(_begin, _end);
_begin=_end;
_current = _current->Forth(_last);
}
// make a link between the _begin and the first to close the graph
original->AddLink(_begin, _first);
}
SetNumber(1);
SetGroup(GROUP_A);
Prepare(1);
ResetBinMark();
//DeleteNonCond(BOOL_OR);
HandleNonCond(BOOL_OR);
bool foundholes = false;
Extract_Simples( BOOL_OR, true, foundholes );
Split(Result);
//Result contains the separate boundaries and holes
//ring creation should never be alternate rule, since it overlaps.
//So temprarely modify it.
bool rule = _GC->GetWindingRule();
_GC->SetWindingRule( true );
_GC->SetState("Create rings");
//first create a ring around all simple graphs
{
TDLI<Graph> IResult=TDLI<Graph>(Result);
GraphList *_ring = new GraphList(_GC);
{
//put into one graphlist
IResult.tohead();
int i;
int n=IResult.count();
for (i=0;i<n;i++)
{
{
IResult.item()->MakeClockWise();
IResult.item()->CreateRing_fast(_ring,fabs(factor));
// IResult.item()->CreateRing(_ring,fabs(factor));
}
delete(IResult.item());
IResult.remove();
//move ring graphlist to result
while (!_ring->empty())
{
//add to end
((Graph*)_ring->headitem())->MakeClockWise();
IResult.insend((Graph*)_ring->headitem());
_ring->removehead();
}
}
}
delete _ring;
//IResult contains all rings
//prepare the graphs for extracting the links of a certain operation
//set original graphlist to groupA and ring to groupB
int i=2;
IResult.tohead();
while (!IResult.hitroot())
{
IResult.item()->Reset_flags();
IResult.item()->SetGroup(GROUP_B);
IResult.item()->SetNumber(i);
i++;
IResult++;
}
}
//a ring shape can overlap itself, for alternate filling this is problem.
//doing a merge in winding rule makes this oke, since overlap is removed by it.
if ( !rule ) //alternate rule?
{
Prepare(1);
Boolean(BOOL_OR,Result);
TDLI<Graph> IResult=TDLI<Graph>(Result);
//IResult contains all rings
//prepare the graphs for extracting the links of a certain operation
//set original graphlist to groupA and ring to groupB
int i=2;
IResult.tohead();
while (!IResult.hitroot())
{
IResult.item()->Reset_flags();
IResult.item()->SetGroup(GROUP_B);
IResult.item()->SetNumber(i);
i++;
IResult++;
}
}
//restore filling rule
_GC->SetWindingRule( rule );
TakeOver(original);
Reset_flags();
SetNumber(1);
SetGroup(GROUP_A);
Result->MakeOneGraph(this); // adds all graph its links to original
// Result will be empty afterwords
//merge ring with original shapes for positive correction else subtract ring
//calculate intersections etc.
//SINCE correction will calculate intersections between
//ring and original _GC->Get_Marge() must be set a lot smaller then factor
//during the rest of this routine
//else wierd effects will be the result.
double Backup_Marge = _GC->GetMarge();
if (_GC->GetInternalMarge() > fabs(factor/100))
{
_GC->SetInternalMarge( (B_INT) fabs(factor/100));
//less then 1 is usless since all coordinates are integers
if (_GC->GetInternalMarge() < 1)
_GC->SetInternalMarge(1);
}
Prepare(1);
_GC->SetState("Add/Substract rings");
if (factor > 0)
Boolean(BOOL_OR,Result);
else
Boolean(BOOL_A_SUB_B,Result);
_GC->SetMarge( Backup_Marge);
//the result of the graph correction is in Result
delete original;
}
// Perform an operation on the graph
void Graph::MakeRing( GraphList* Result, double factor )
{
bool rule = _GC->GetWindingRule();
_GC->SetWindingRule( true );
// At this moment we have one graph
// step one, split it up in single graphs, and mark the holes
// step two, make one graph again and link the holes
// step three, split up again and dump the result in Result
_GC->SetState("Extract simple graphs");
//extract the (MERGE or OR) result from the graph
SetNumber(1);
Prepare(1);
ResetBinMark();
//DeleteNonCond(BOOL_OR);
HandleNonCond(BOOL_OR);
bool foundholes = false;
Extract_Simples( BOOL_OR, true, foundholes );
Split(Result);
//Iresult contains the separate boundaries and holes
//make a correction on the boundaries factor
//make a correction on the holes -factor
_GC->SetState("Create rings");
//first create a ring around all simple graphs
TDLI<Graph> IResult=TDLI<Graph>(Result);
GraphList *_ring = new GraphList(_GC);
{
IResult.tohead();
int i;
int n=IResult.count();
for (i=0;i<n;i++)
{
{
IResult.item()->MakeClockWise();
IResult.item()->CreateRing_fast(_ring,fabs(factor));
}
delete(IResult.item());
IResult.remove();
//move ring graphlist to result
while (!_ring->empty())
{
//add to end
((Graph*)_ring->headitem())->MakeClockWise();
IResult.insend((Graph*)_ring->headitem());
_ring->removehead();
}
}
}
delete _ring;
_GC->SetWindingRule( rule );
}
//create a ring shapes on every edge of the graph
void Graph::CreateRing( GraphList *ring, double factor )
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.tohead();
while( !_LI.hitroot())
{
Graph *shape=new Graph(_GC);
//generate shape around link
shape->Make_Rounded_Shape(_LI.item(),factor);
ring->insbegin(shape);
_LI++;
}
}
//create a ring shapes on every edge of the graph
void Graph::CreateRing_fast( GraphList *ring, double factor )
{
Node* begin;
KBoolLink* currentlink;
KBoolLine currentline(_GC);
KBoolLine firstline(_GC);
KBoolLink* nextlink;
KBoolLine nextline(_GC);
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.foreach_mf(&KBoolLink::UnMark);//reset bin and mark flag of each link
_LI.mergesort(linkYXsorter);
_LI.tohead();
begin = GetMostTopLeft(&_LI); // from all the most Top nodes,
// take the most left one
}
if (!begin)
return;
currentlink=begin->GetIncomingLink();
currentline.Set(currentlink);
currentline.CalculateLineParameters();
nextlink=begin->GetOutgoingLink();
nextline.Set(nextlink);
nextline.CalculateLineParameters();
firstline.Set(nextlink);
firstline.CalculateLineParameters();
while (nextlink)
{
Graph *shape=new Graph(_GC);
{
Node* _last_ins_left =0;
Node* _last_ins_right =0;
currentline.Create_Begin_Shape(&nextline,&_last_ins_left,&_last_ins_right,factor,shape);
while(true)
{
currentline=nextline;
currentlink=nextlink;
currentlink->SetBeenHere();
nextlink=currentlink->GetEndNode()->Follow(currentlink);
if (nextlink)
{
nextline.Set(nextlink);
nextline.CalculateLineParameters();
if (!currentline.Create_Ring_Shape(&nextline,&_last_ins_left,&_last_ins_right,factor,shape))
break;
}
else
break;
}
//finish this part
if (nextlink)
currentline.Create_End_Shape(&nextline,_last_ins_left,_last_ins_right,factor,shape);
else
currentline.Create_End_Shape(&firstline,_last_ins_left,_last_ins_right,factor,shape);
shape->MakeOneDirection();
shape->MakeClockWise();
}
//if the shape is very small first merge it with the previous shape
if (!ring->empty() && shape->Small( (B_INT) fabs(factor*3)))
{
TDLI<Graph> Iring = TDLI<Graph>(ring);
Iring.totail();
GraphList *_twoshapes=new GraphList(_GC);
_twoshapes->insbegin(shape);
_twoshapes->insbegin(Iring.item());
Iring.remove();
_twoshapes->Merge();
//move merged graphlist to ring
Iring.takeover(_twoshapes);
delete _twoshapes;
}
else
ring->insend(shape);
currentlink->SetBeenHere();
}
}
//create an arc and add it to the graph
//center of circle
//begin point of arc
//end point of arc
//radius of arc
//aberation for generating the segments
void Graph::CreateArc(Node* center, Node* begin, Node* end,double radius,bool clock,double aber)
{
double phi,dphi,dx,dy;
int Segments;
int i;
double ang1,ang2,phit;
Node* _last_ins;
Node* _current;
_last_ins=begin;
dx = (double) _last_ins->GetX() - center->GetX();
dy = (double) _last_ins->GetY() - center->GetY();
ang1=atan2(dy,dx);
if (ang1<0) ang1+=2.0*M_PI;
dx = (double) end->GetX() - center->GetX();
dy = (double) end->GetY() - center->GetY();
ang2=atan2(dy,dx);
if (ang2<0) ang2+=2.0*M_PI;
if (clock)
{ //clockwise
if (ang2 > ang1)
phit=2.0*M_PI-ang2+ ang1;
else
phit=ang1-ang2;
}
else
{ //counter_clockwise
if (ang1 > ang2)
phit=-(2.0*M_PI-ang1+ ang2);
else
phit=-(ang2-ang1);
}
//what is the delta phi to get an accurancy of aber
dphi=2*acos((radius-aber)/radius);
//set the number of segments
if (phit > 0)
Segments=(int)ceil(phit/dphi);
else
Segments=(int)ceil(-phit/dphi);
if (Segments <= 1)
Segments=1;
if (Segments > 6)
Segments=6;
dphi=phit/(Segments);
for (i=1; i<Segments; i++)
{
dx = (double) _last_ins->GetX() - center->GetX();
dy = (double) _last_ins->GetY() - center->GetY();
phi=atan2(dy,dx);
_current = new Node((B_INT) (center->GetX() + radius * cos(phi-dphi)),
(B_INT) (center->GetY() + radius * sin(phi-dphi)), _GC);
AddLink(_last_ins, _current);
_last_ins=_current;
}
// make a node from the endnode of link
AddLink(_last_ins, end);
}
void Graph::CreateArc(Node* center, KBoolLine* incoming, Node* end,double radius,double aber)
{
double distance=0;
if (incoming->PointOnLine(center, distance, _GC->GetAccur()) == RIGHT_SIDE)
CreateArc(center,incoming->GetEndNode(),end,radius,true,aber);
else
CreateArc(center,incoming->GetEndNode(),end,radius,false,aber);
}
void Graph::MakeOneDirection()
{
int _nr_of_points = _linklist->count();
KBoolLink* _current = (KBoolLink*)_linklist->headitem();
Node* _last = _current->GetBeginNode();
Node* dummy;
for (int i = 0; i < _nr_of_points; i++)
{
// get the other node on the link
_last = _current->GetOther(_last);
// get the other link on the node
_current = _current->Forth(_last);
if (_current->GetBeginNode() != _last)
{
// swap the begin- and endnode of the current link
dummy = _current->GetBeginNode();
_current->SetBeginNode(_current->GetEndNode());
_current->SetEndNode(dummy);
}
}
}
bool Graph::Small(B_INT howsmall)
{
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
_LI.tohead();
Node* bg=_LI.item()->GetBeginNode();
B_INT xmin=bg->GetX();
B_INT xmax=bg->GetX();
B_INT ymin=bg->GetY();
B_INT ymax=bg ->GetY();
while (!_LI.hitroot())
{
bg=_LI.item()->GetBeginNode();
// make _boundingbox bigger if the link makes the graph bigger
// Checking if point is in bounding-box with marge
xmin=bmin(xmin,bg->GetX());
xmax=bmax(xmax,bg->GetX());
ymin=bmin(ymin,bg->GetY());
ymax=bmax(ymax,bg->GetY());
_LI++;
}
B_INT dx=(xmax-xmin);
B_INT dy=(ymax-ymin);
if ((dx < howsmall) && (dy < howsmall) )
return true;
return false;
}
//create a circle at end and begin point
// and block in between
void Graph::Make_Rounded_Shape( KBoolLink* a_link, double factor)
{
double phi,dphi,dx,dy;
int Segments=6;
int i;
KBoolLine theline(a_link, _GC);
theline.CalculateLineParameters();
Node* _current;
Node *_first = new Node(a_link->GetBeginNode(), _GC);
Node *_last_ins = _first;
theline.Virtual_Point(_first,factor);
// make a node from this point
_current = new Node(a_link->GetEndNode(), _GC);
theline.Virtual_Point(_current,factor);
// make a link between the current and the previous and add this to graph
AddLink(_last_ins, _current);
_last_ins=_current;
// make a half circle around the clock with the opposite point as
// the middle point of the circle
dphi=M_PI/(Segments);
for (i=1; i<Segments; i++)
{
dx = (double) _last_ins->GetX() - a_link->GetEndNode()->GetX();
dy = (double) _last_ins->GetY() - a_link->GetEndNode()->GetY();
phi=atan2(dy,dx);
_current = new Node((B_INT) (a_link->GetEndNode()->GetX() + factor * cos(phi-dphi)),
(B_INT) (a_link->GetEndNode()->GetY() + factor * sin(phi-dphi)), _GC);
AddLink(_last_ins, _current);
_last_ins=_current;
}
// make a node from the endnode of link
_current = new Node(a_link->GetEndNode(), _GC);
theline.Virtual_Point(_current,-factor);
AddLink(_last_ins, _current);
_last_ins=_current;
// make a node from this beginnode of link
_current = new Node(a_link->GetBeginNode(), _GC);
theline.Virtual_Point(_current,-factor);
AddLink(_last_ins, _current);
_last_ins=_current;
for (i=1; i<Segments; i++)
{
dx = (double) _last_ins->GetX() - a_link->GetBeginNode()->GetX();
dy = (double) _last_ins->GetY() - a_link->GetBeginNode()->GetY();
phi=atan2(dy,dx);
_current = new Node((B_INT)(a_link->GetBeginNode()->GetX() + factor * cos(phi-dphi)),
(B_INT)(a_link->GetBeginNode()->GetY() + factor * sin(phi-dphi)), _GC);
AddLink(_last_ins, _current);
_last_ins=_current;
}
// make a link between the last and the first to close the graph
AddLink(_last_ins, _first);
};
//make the graph clockwise orientation,
//return if the graph needed redirection
bool Graph::MakeClockWise()
{
if ( _GC->GetOrientationEntryMode() )
return false;
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
if (_LI.empty()) return false;
KBoolLink *currentlink;
Node *begin;
_LI.foreach_mf(&KBoolLink::UnMark);//reset bin and mark flag of each link
_LI.mergesort(linkYXtopsorter);
_LI.tohead();
begin = GetMostTopLeft(&_LI); // from all the most Top nodes,
// take the most left one
currentlink=begin->GetNotFlat();
if (!currentlink)
{
char buf[100];
sprintf(buf,"no NON flat link MakeClockWise at %15.3lf , %15.3lf",
double(begin->GetX()),double(begin->GetY()));
throw Bool_Engine_Error(buf, "Error", 9, 0);
}
//test to see if the orientation is right or left
if (currentlink->GetBeginNode() == begin)
{
if ( currentlink->GetEndNode()->GetX() < begin->GetX())
{
//going left
//it needs redirection
ReverseAllLinks();
return true;
}
}
else
{
if ( currentlink->GetBeginNode()->GetX() > begin->GetX())
{ //going left
//it needs redirection
ReverseAllLinks();
return true;
}
}
return false;
}
bool Graph::writegraph(bool linked )
{
#if KBOOL_DEBUG == 1
FILE* file = _GC->GetLogFile();
if (file == NULL)
return true;
fprintf( file, "# graph\n" );
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
if (_LI.empty())
{
return true;
}
_LI.tohead();
while(!_LI.hitroot())
{
KBoolLink* curl = _LI.item();
fprintf( file, " linkbegin %I64d %I64d \n", curl->GetBeginNode()->GetX() , curl->GetBeginNode()->GetY() );
if (linked)
{
TDLI<KBoolLink> Inode(curl->GetBeginNode()->GetLinklist());
Inode.tohead();
while(!Inode.hitroot())
{
fprintf( file, " b %I64d %I64d \n", Inode.item()->GetBeginNode()->GetX() , Inode.item()->GetBeginNode()->GetY() );
fprintf( file, " e %I64d %I64d \n", Inode.item()->GetEndNode()->GetX() , Inode.item()->GetEndNode()->GetY() );
Inode++;
}
}
fprintf( file, " linkend %I64d %I64d \n", curl->GetEndNode()->GetX() , curl->GetEndNode()->GetY() );
if (linked)
{
TDLI<KBoolLink> Inode(curl->GetEndNode()->GetLinklist());
Inode.tohead();
while(!Inode.hitroot())
{
fprintf( file, " b %I64d %I64d \n", Inode.item()->GetBeginNode()->GetX() , Inode.item()->GetBeginNode()->GetY() );
fprintf( file, " e %I64d %I64d \n", Inode.item()->GetEndNode()->GetX() , Inode.item()->GetEndNode()->GetY() );
Inode++;
}
}
if ( curl->GetBeginNode() == curl->GetEndNode() )
fprintf( file, " null_link \n" );
fprintf( file, " group %d ", curl->Group() );
fprintf( file, " bin %d ", curl->BeenHere() );
fprintf( file, " mark %d ", curl->IsMarked() );
fprintf( file, " leftA %d ", curl->GetLeftA() );
fprintf( file, " rightA %d ", curl->GetRightA() );
fprintf( file, " leftB %d ", curl->GetLeftB() );
fprintf( file, " rightB %d \n", curl->GetRightB() );
fprintf( file, " or %d ", curl->IsMarked(BOOL_OR) );
fprintf( file, " and %d " , curl->IsMarked(BOOL_AND) );
fprintf( file, " exor %d " , curl->IsMarked(BOOL_EXOR) );
fprintf( file, " a_sub_b %d " , curl->IsMarked(BOOL_A_SUB_B) );
fprintf( file, " b_sub_a %d " , curl->IsMarked(BOOL_B_SUB_A) );
fprintf( file, " hole %d " , curl->GetHole() );
fprintf( file, " top_hole %d \n" , curl->IsTopHole() );
_LI++;
}
#endif
return true;
}
bool Graph::writeintersections()
{
#if KBOOL_DEBUG == 1
FILE* file = _GC->GetLogFile();
if (file == NULL)
return true;
fprintf( file, "# graph\n" );
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
if (_LI.empty())
{
return true;
}
_LI.tohead();
while(!_LI.hitroot())
{
KBoolLink* curl=_LI.item();
TDLI<KBoolLink> Inode(curl->GetBeginNode()->GetLinklist());
Inode.tohead();
if (Inode.count() > 2)
{
fprintf( file, " count %I64d", Inode.count() );
fprintf( file, " b %I64d %I64d \n\n", curl->GetBeginNode()->GetX() , curl->GetBeginNode()->GetY() );
}
_LI++;
}
#endif
return true;
}
bool Graph::checksort()
{
// if empty then just insert
if (_linklist->empty())
return true;
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
// put new item left of the one that is bigger
_LI.tohead();
KBoolLink* prev=_LI.item();
KBoolLink* cur=_LI.item();
_LI++;
while(!_LI.hitroot())
{
KBoolLink* aap=_LI.item();
if (linkXYsorter(prev,_LI.item())==-1)
{
cur=aap;
return false;
}
prev=_LI.item();
_LI++;
}
return true;
}
void Graph::WriteKEY( Bool_Engine* GC, FILE* file )
{
double scale = 1.0/GC->GetGrid()/GC->GetGrid();
bool ownfile = false;
if ( !file )
{
file = fopen("keyfile.key", "w");
ownfile = true;
fprintf(file,"\
HEADER 5; \
BGNLIB; \
LASTMOD {2-11-15 15:39:21}; \
LASTACC {2-11-15 15:39:21}; \
LIBNAME trial; \
UNITS; \
USERUNITS 0.0001; PHYSUNITS 1e-009; \
\
BGNSTR; \
CREATION {2-11-15 15:39:21}; \
LASTMOD {2-11-15 15:39:21}; \
STRNAME top; \
");
}
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
if (_LI.empty())
{
if ( ownfile )
{
fprintf(file,"\
ENDSTR top; \
ENDLIB; \
");
fclose (file);
}
return;
}
_LI.tohead();
KBoolLink* curl = _LI.item();
if ( _LI.item()->Group() == GROUP_A )
fprintf(file,"BOUNDARY; LAYER 0; DATATYPE 0;\n");
else
fprintf(file,"BOUNDARY; LAYER 1; DATATYPE 0;\n");
fprintf(file," XY %d; \n", _LI.count()+1 );
double firstx = curl->GetBeginNode()->GetX()*scale;
double firsty = curl->GetBeginNode()->GetY()*scale;
fprintf(file,"X %f;\t", firstx);
fprintf(file,"Y %f; \n", firsty);
_LI++;
while(!_LI.hitroot())
{
KBoolLink* curl = _LI.item();
fprintf(file,"X %f;\t", curl->GetBeginNode()->GetX()*scale);
fprintf(file,"Y %f; \n", curl->GetBeginNode()->GetY()*scale);
_LI++;
}
fprintf(file,"X %f;\t", firstx);
fprintf(file,"Y %f; \n", firsty);
fprintf(file,"ENDEL;\n");
if ( ownfile )
{
fprintf(file,"\
ENDSTR top; \
ENDLIB; \
");
fclose (file);
}
}
void Graph::WriteGraphKEY(Bool_Engine* GC)
{
#if KBOOL_DEBUG == 1
double scale = 1.0/GC->GetGrid()/GC->GetGrid();
FILE* file = fopen("keygraphfile.key", "w");
fprintf(file,"\
HEADER 5; \
BGNLIB; \
LASTMOD {2-11-15 15:39:21}; \
LASTACC {2-11-15 15:39:21}; \
LIBNAME trial; \
UNITS; \
USERUNITS 1; PHYSUNITS 1e-006; \
\
BGNSTR; \
CREATION {2-11-15 15:39:21}; \
LASTMOD {2-11-15 15:39:21}; \
STRNAME top; \
");
TDLI<KBoolLink> _LI=TDLI<KBoolLink>(_linklist);
if (_LI.empty())
{
fprintf(file,"\
ENDSTR top; \
ENDLIB; \
");
fclose (file);
return;
}
_LI.tohead();
KBoolLink* curl;
int _nr_of_points = _linklist->count();
for (int i = 0; i < _nr_of_points; i++)
{
curl = _LI.item();
if ( curl->Group() == GROUP_A )
fprintf(file,"PATH; LAYER 0;\n");
else
fprintf(file,"PATH; LAYER 1;\n");
fprintf(file," XY %d; \n", 2 );
fprintf(file,"X %f;\t", curl->GetBeginNode()->GetX()*scale);
fprintf(file,"Y %f; \n", curl->GetBeginNode()->GetY()*scale);
fprintf(file,"X %f;\t", curl->GetEndNode()->GetX()*scale);
fprintf(file,"Y %f; \n", curl->GetEndNode()->GetY()*scale);
_LI++;
fprintf(file,"ENDEL;\n");
}
fprintf(file,"\
ENDSTR top; \
ENDLIB; \
");
fclose (file);
#endif
}
/*! \file ../src/graphlst.cpp
\brief Implements a list of graphs
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: graphlst.cpp,v 1.8 2005/05/24 19:13:38 titato Exp $
*/
#ifdef __GNUG__
#pragma implementation
#endif
//#include "debugdrv.h"
#include "../include/booleng.h"
#include "../include/graphlst.h"
//extern Debug_driver* _debug_driver;
//this here is to initialize the static iterator of graphlist
//with NOLIST constructor
int graphsorterX( Graph *, Graph * );
int graphsorterY( Graph *, Graph * );
GraphList::GraphList(Bool_Engine* GC)
{
_GC=GC;
}
GraphList::GraphList( GraphList* other )
{
_GC = other->_GC;
TDLI<Graph> _LI = TDLI<Graph>( other );
_LI.tohead();
while (!_LI.hitroot())
{
insend( new Graph( _LI.item() ) );
_LI++;
}
}
GraphList::~GraphList()
{
TDLI<Graph> _LI=TDLI<Graph>(this);
//first empty the graph
_LI.delete_all();
}
//prepare the graphlist for the boolean operations
//group all graphs into ONE graph
void GraphList::Prepare(Graph* total)
{
if (empty())
return;
//round to grid and put in one graph
_GC->SetState("Simplify");
// Simplify all graphs in the list
Simplify( (double) _GC->GetGrid() );
if ( ! _GC->GetOrientationEntryMode() )
{
TDLI<Graph> _LI=TDLI<Graph>(this);
_LI.tohead();
while (!_LI.hitroot())
{
_LI.item()->MakeClockWise();
_LI++;
}
}
Renumber();
//the graplist contents will be transferred to one graph
MakeOneGraph(total);
}
// the function will make from all the graphs in the graphlist one graph,
// simply by throwing all the links in one graph, the graphnumbers will
// not be changed
void GraphList::MakeOneGraph(Graph* total)
{
TDLI<Graph> _LI=TDLI<Graph>(this);
_LI.tohead();
while(!_LI.hitroot())
{
total->TakeOver(_LI.item());
delete _LI.item();
_LI.remove();
}
}
//
// Renumber all the graphs
//
void GraphList::Renumber()
{
if ( _GC->GetOrientationEntryMode() )
{
TDLI<Graph> _LI=TDLI<Graph>(this);
_LI.tohead();
while (!_LI.hitroot())
{
if ( _LI.item()->GetFirstLink()->Group() == GROUP_A )
_LI.item()->SetNumber(1);
else
_LI.item()->SetNumber(2);
_LI++;
}
}
else
{
unsigned int Number = 1;
TDLI<Graph> _LI=TDLI<Graph>(this);
_LI.tohead();
while (!_LI.hitroot())
{
_LI.item()->SetNumber(Number++);
_LI++;
}
}
}
// Simplify the graphs
void GraphList::Simplify(double marge)
{
TDLI<Graph> _LI=TDLI<Graph>(this);
_LI.foreach_mf(&Graph::Reset_Mark_and_Bin);
_LI.tohead();
while (!_LI.hitroot())
{
if (_LI.item()->Simplify( (B_INT) marge))
{
if (_LI.item()->GetNumberOfLinks() < 3)
// delete this graph from the graphlist
{
delete _LI.item();
_LI.remove();
}
}
else
_LI++;
}
}
// Smoothen the graphs
void GraphList::Smoothen(double marge)
{
TDLI<Graph> _LI=TDLI<Graph>(this);
_LI.foreach_mf(&Graph::Reset_Mark_and_Bin);
_LI.tohead();
while (!_LI.hitroot())
{
if (_LI.item()->Smoothen( (B_INT) marge))
{
if (_LI.item()->GetNumberOfLinks() < 3)
// delete this graph from the graphlist
{
delete _LI.item();
_LI.remove();
}
}
else
_LI++;
}
}
// Turn off all markers in all the graphs
void GraphList::UnMarkAll()
{
TDLI<Graph> _LI=TDLI<Graph>(this);
_LI.foreach_mf(&Graph::Reset_Mark_and_Bin);
}
//==============================================================================
//
//======================== BOOLEAN FUNCTIONS ===================================
//
//==============================================================================
void GraphList::Correction()
{
TDLI<Graph> _LI=TDLI<Graph>(this);
int todo=_LI.count();
if ( _GC->GetInternalCorrectionFactor()) //not zero
{
_LI.tohead();
for(int i=0; i<todo ; i++)
{
//the input graph will be empty in the end
GraphList *_correct=new GraphList(_GC);
{
_LI.item()->MakeClockWise();
_LI.item()->Correction(_correct,_GC->GetInternalCorrectionFactor());
delete _LI.item();
_LI.remove();
//move corrected graphlist to result
while (!_correct->empty())
{
//add to end
_LI.insend((Graph*)_correct->headitem());
_correct->removehead();
}
}
delete _correct;
}
}
}
void GraphList::MakeRings()
{
TDLI<Graph> _LI=TDLI<Graph>(this);
int todo=_LI.count();
_LI.tohead();
for(int i=0; i<todo ; i++)
{
//the input graph will be empty in the end
GraphList *_ring=new GraphList(_GC);
{
_LI.item()->MakeClockWise();
_LI.item()->MakeRing(_ring,_GC->GetInternalCorrectionFactor());
delete _LI.item();
_LI.remove();
//move created rings graphs to this
while (!_ring->empty())
{
//add to end
((Graph*)_ring->headitem())->MakeClockWise();
_LI.insend((Graph*)_ring->headitem());
_ring->removehead();
}
}
delete _ring;
}
}
//merge the graphs in the list and return the merged result
void GraphList::Merge()
{
if (count()<=1)
return;
{
TDLI<Graph> _LI=TDLI<Graph>(this);
_LI.tohead();
while (!_LI.hitroot())
{
_LI.item()->SetGroup(GROUP_A);
_LI++;
}
}
Graph* _tomerge=new Graph(_GC);
Renumber();
//the graplist contents will be transferred to one graph
MakeOneGraph(_tomerge);
//the original is empty now
_tomerge->Prepare(1);
_tomerge->Boolean(BOOL_OR,this);
delete _tomerge;
}
#define TRIALS 30
#define SAVEME 1
//perform boolean operation on the graphs in the list
void GraphList::Boolean(BOOL_OP operation, int intersectionRunsMax )
{
_GC->SetState("Performing Boolean Operation");
if (count()==0)
return;
Graph* _prepared = new Graph(_GC);
if (empty())
return;
//round to grid and put in one graph
_GC->SetState("Simplify");
int intersectionruns = 1;
while ( intersectionruns <= intersectionRunsMax )
{
try
{
Prepare( _prepared );
if (_prepared->GetNumberOfLinks())
{
//calculate intersections etc.
_GC->SetState("prepare");
_prepared->Prepare( intersectionruns );
//_prepared->writegraph(true);
_prepared->Boolean(operation,this);
}
intersectionruns = intersectionRunsMax +1;
}
catch (Bool_Engine_Error& error)
{
#if KBOOL_DEBUG
_prepared->WriteGraphKEY(_GC);
#endif
intersectionruns++;
if ( intersectionruns == intersectionRunsMax )
{
_prepared->WriteGraphKEY(_GC);
_GC->info(error.GetErrorMessage(), "error");
throw error;
}
}
catch(...)
{
#if KBOOL_DEBUG
_prepared->WriteGraphKEY(_GC);
#endif
intersectionruns++;
if ( intersectionruns == intersectionRunsMax )
{
_prepared->WriteGraphKEY(_GC);
_GC->info("Unknown exception", "error");
throw;
}
}
}
delete _prepared;
}
void GraphList::WriteGraphs()
{
TDLI<Graph> _LI=TDLI<Graph>(this);
_LI.tohead();
while(!_LI.hitroot())
{
_LI.item()->writegraph( false );
_LI++;
}
}
void GraphList::WriteGraphsKEY( Bool_Engine* GC )
{
FILE* file = fopen("graphkeyfile.key", "w");
fprintf(file,"\
HEADER 5; \
BGNLIB; \
LASTMOD {2-11-15 15:39:21}; \
LASTACC {2-11-15 15:39:21}; \
LIBNAME trial; \
UNITS; \
USERUNITS 0.0001; PHYSUNITS 1e-009; \
\
BGNSTR; \
CREATION {2-11-15 15:39:21}; \
LASTMOD {2-11-15 15:39:21}; \
STRNAME top; \
");
TDLI<Graph> _LI=TDLI<Graph>(this);
_LI.tohead();
while(!_LI.hitroot())
{
_LI.item()->WriteKEY( GC, file );
_LI++;
}
fprintf(file,"\
ENDSTR top; \
ENDLIB; \
");
fclose (file);
}
/*! \file ../src/instonly.cpp
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: instonly.cpp,v 1.5 2005/05/24 19:13:38 titato Exp $
*/
#ifdef __GNUG__
#pragma option -Jgd
#include "../include/_dl_itr.h"
#include "../include/node.h"
#include "../include/record.h"
#include "../include/link.h"
#include "../include/_lnk_itr.h"
#include "../include/scanbeam.h"
#include "../include/graph.h"
#include "../include/graphlst.h"
//#include "../include/misc.h"
template class DL_Node<void *>;
template class DL_Iter<void *>;
template class DL_List<void *>;
template class DL_Node<int>;
template class DL_Iter<int>;
template class DL_List<int>;
template class TDLI<Node>;
template class TDLI<LPoint>;
template class TDLI<Record>;
template class TDLI<KBoolLink>;
template class TDLI<Graph>;
#endif
/*! \file ../src/line.cpp
\brief Mainly used for calculating crossings
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: line.cpp,v 1.10 2005/06/17 22:48:46 kbluck Exp $
*/
#ifdef __GNUG__
#pragma implementation
#endif
// Standard include files
#include <assert.h>
#include <math.h>
#include "../include/booleng.h"
// Include files for forward declarations
#include "../include/link.h"
#include "../include/node.h"
// header
#include "../include/line.h"
#include "../include/graph.h"
#include "../include/graphlst.h"
//
// The default constructor
//
KBoolLine::KBoolLine(Bool_Engine* GC)
{
m_GC=GC;
m_AA = 0.0;
m_BB = 0.0;
m_CC = 0.0;
m_link = 0;
linecrosslist = NULL;
m_valid_parameters = false;
}
KBoolLine::~KBoolLine()
{
if (linecrosslist)
delete linecrosslist;
}
//
// constructor with a link
//
KBoolLine::KBoolLine(KBoolLink *a_link,Bool_Engine* GC)
{
m_GC=GC;
// a_link must exist
assert(a_link);
// points may not be equal
// must be an if statement because if an assert is used there will
// be a macro expansion error
//if (a_link->GetBeginNode()->Equal(a_link->GetEndNode(), 1))
// assert(!a_link);
linecrosslist = NULL;
m_link = a_link;
m_valid_parameters = false;
}
// ActionOnTable1
// This function decide which action must be taken, after PointInLine
// has given the results of two points in relation to a line. See table 1 in the report
//
// input Result_beginnode:
// Result_endnode :
// The results can be LEFT_SIDE, RIGHT_SIDE, ON_AREA, IN_AREA
//
// return -1: Illegal combination
// 0: No action, no crosspoints
// 1: Investigate results points in relation to the other line
// 2: endnode is a crosspoint, no further investigation
// 3: beginnode is a crosspoint, no further investigation
// 4: beginnode and endnode are crosspoints, no further investigation
// 5: beginnode is a crosspoint, need further investigation
// 6: endnode is a crosspoint, need further investigation
int KBoolLine::ActionOnTable1(PointStatus Result_beginnode, PointStatus Result_endnode)
{
// Action 1.5 beginnode and endnode are crosspoints, no further investigation needed
if (
(Result_beginnode == IN_AREA)
&&
(Result_endnode == IN_AREA)
)
return 4;
// Action 1.1, there are no crosspoints, no action
if (
(
(Result_beginnode == LEFT_SIDE)
&&
(Result_endnode == LEFT_SIDE)
)
||
(
(Result_beginnode == RIGHT_SIDE)
&&
(Result_endnode == RIGHT_SIDE)
)
)
return 0;
// Action 1.2, maybe there is a crosspoint, further investigation needed
if (
(
(Result_beginnode == LEFT_SIDE)
&&
(
(Result_endnode == RIGHT_SIDE)
||
(Result_endnode == ON_AREA)
)
)
||
(
(Result_beginnode == RIGHT_SIDE)
&&
(
(Result_endnode == LEFT_SIDE)
||
(Result_endnode == ON_AREA)
)
)
||
(
(Result_beginnode == ON_AREA)
&&
(
(Result_endnode == LEFT_SIDE)
||
(Result_endnode == RIGHT_SIDE)
||
(Result_endnode == ON_AREA)
)
)
)
return 1;
// Action 1.3, there is a crosspoint, no further investigation
if (
(
(Result_beginnode == LEFT_SIDE)
||
(Result_beginnode == RIGHT_SIDE)
)
&&
(Result_endnode == IN_AREA)
)
return 2;
// Action 1.4 there is a crosspoint, no further investigation
if (
(Result_beginnode == IN_AREA)
&&
(
(Result_endnode == LEFT_SIDE)
||
(Result_endnode == RIGHT_SIDE)
)
)
return 3;
// Action 1.6 beginnode is a crosspoint, further investigation needed
if (
(Result_beginnode == IN_AREA)
&&
(Result_endnode == ON_AREA)
)
return 5;
// Action 1.7 endnode is a crosspoint, further investigation needed
if (
(Result_beginnode == ON_AREA)
&&
(Result_endnode == IN_AREA)
)
return 6;
// All other combinations are illegal
return -1;
}
// ActionOnTable2
// This function decide which action must be taken, after PointInLine
// has given the results of two points in relation to a line. It can only give a
// correct decision if first the relation of the points from the line
// are investigated in relation to the line wich can be constucted from the points.
//
// input Result_beginnode:
// Result_endnode :
// The results can be LEFT_SIDE, RIGHT_SIDE, ON_AREA, IN_AREA
//
// return -1: Illegal combination
// 0: No action, no crosspoints
// 1: Calculate crosspoint
// 2: endnode is a crosspoint
// 3: beginnode is a crosspoint
// 4: beginnode and endnode are crosspoints
int KBoolLine::ActionOnTable2(PointStatus Result_beginnode, PointStatus Result_endnode)
{
// Action 2.5, beginnode and eindpoint are crosspoints
if (
(Result_beginnode == IN_AREA)
&&
(Result_endnode == IN_AREA)
)
return 4;
// Action 2.1, there are no crosspoints
if (
(
(Result_beginnode == LEFT_SIDE)
&&
(
(Result_endnode == LEFT_SIDE)
||
(Result_endnode == ON_AREA)
)
)
||
(
(Result_beginnode == RIGHT_SIDE)
&&
(
(Result_endnode == RIGHT_SIDE)
||
(Result_endnode == ON_AREA)
)
)
||
(
(Result_beginnode == ON_AREA)
&&
(
(Result_endnode == LEFT_SIDE)
||
(Result_endnode == RIGHT_SIDE)
||
(Result_endnode == ON_AREA)
)
)
)
return 0;
// Action 2.2, there is a real intersect ion, which must be calculated
if (
(
(Result_beginnode == LEFT_SIDE)
&&
(Result_endnode == RIGHT_SIDE)
)
||
(
(Result_beginnode == RIGHT_SIDE)
&&
(Result_endnode == LEFT_SIDE)
)
)
return 1;
// Action 2.3, endnode is a crosspoint
if (
(
(Result_beginnode == LEFT_SIDE)
||
(Result_beginnode == RIGHT_SIDE)
||
(Result_beginnode == ON_AREA)
)
&&
(Result_endnode == IN_AREA)
)
return 2;
// Action 2.4, beginnode is a crosspoint
if (
(Result_beginnode == IN_AREA)
&&
(
(Result_endnode == LEFT_SIDE)
||
(Result_endnode == RIGHT_SIDE)
||
(Result_endnode == ON_AREA)
)
)
return 3;
// All other combinations are illegal
return -1;
}
//
// This fucntion will ad a crossing to this line and the other line
// the crossing will be put in the link, because the line will be destructed
// after use of the variable
//
void KBoolLine::AddLineCrossing(B_INT X, B_INT Y, KBoolLine *other_line)
{
// the other line must exist
assert(other_line);
// the links of the lines must exist
assert(other_line->m_link && m_link);
other_line->AddCrossing(AddCrossing(X,Y));
}
// Calculate the Y when the X is given
//
B_INT KBoolLine::Calculate_Y(B_INT X)
{
// link must exist to get info about the nodes
assert(m_link);
CalculateLineParameters();
if (m_AA != 0)
return (B_INT)(-(m_AA * X + m_CC) / m_BB);
else
// horizontal line
return m_link->GetBeginNode()->GetY();
}
B_INT KBoolLine::Calculate_Y_from_X(B_INT X)
{
// link must exist to get info about the nodes
assert(m_link);
assert(m_valid_parameters);
if (m_AA != 0)
return (B_INT) ((-(m_AA * X + m_CC) / m_BB)+0.5);
else
// horizontal line
return m_link->GetBeginNode()->GetY();
}
void KBoolLine::Virtual_Point(LPoint *a_point,double distance)
{
// link must exist to get info about the nodes
assert(m_link);
assert(m_valid_parameters);
//calculate the distance using the slope of the line
//and rotate 90 degrees
a_point->SetY((B_INT)(a_point->GetY() + (distance * -(m_BB))));
a_point->SetX((B_INT)(a_point->GetX() - (distance * m_AA )));
}
//
// Calculate the lineparameters for the line if nessecary
//
void KBoolLine::CalculateLineParameters()
{
// linkmust exist to get beginnode AND endnode
assert(m_link);
// if not valid_parameters calculate the parameters
if (!m_valid_parameters)
{
Node *bp, *ep;
double length;
// get the begin and endnode via the link
bp = m_link->GetBeginNode();
ep = m_link->GetEndNode();
// bp AND ep may not be the same
if (bp == ep)
assert (bp != ep);
m_AA = (double) (ep->GetY() - bp->GetY()); // A = (Y2-Y1)
m_BB = (double) (bp->GetX() - ep->GetX()); // B = (X1-X2)
// the parameters A end B can now be normalized
length = sqrt(m_AA*m_AA + m_BB*m_BB);
if(length ==0)
m_GC->error("length = 0","CalculateLineParameters");
m_AA = (m_AA / length);
m_BB = (m_BB / length);
m_CC = -((m_AA * bp->GetX()) + (bp->GetY() * m_BB));
m_valid_parameters = true;
}
}
// Checks if a line intersect with another line
// inout Line : another line
// Marge: optional, standard on MARGE (declared in MISC.CPP)
//
// return true : lines are crossing
// false: lines are not crossing
//
int KBoolLine::CheckIntersect (KBoolLine * lijn, double Marge)
{
double distance=0;
// link must exist
assert(m_link);
// lijn must exist
assert(lijn);
// points may not be equal
// must be an if statement because if an assert is used there will
// be a macro expansion error
if (m_link->GetBeginNode() == m_link->GetEndNode())
assert(!m_link);
int Take_Action1, Take_Action2, Total_Result;
Node *bp, *ep;
PointStatus Result_beginnode,Result_endnode;
bp = lijn->m_link->GetBeginNode();
ep = lijn->m_link->GetEndNode();
Result_beginnode = PointInLine(bp,distance,Marge);
Result_endnode = PointInLine(ep,distance,Marge);
Take_Action1 = ActionOnTable1(Result_beginnode,Result_endnode);
switch (Take_Action1)
{
case 0: Total_Result = false ; break;
case 1: {
bp = m_link->GetBeginNode();
ep = m_link->GetEndNode();
Result_beginnode = lijn->PointInLine(bp,distance,Marge);
Result_endnode = lijn->PointInLine(ep,distance,Marge);
Take_Action2 = ActionOnTable2(Result_beginnode,Result_endnode);
switch (Take_Action2)
{
case 0: Total_Result = false; break;
case 1: case 2: case 3: case 4: Total_Result = true; break;
default: Total_Result = false; assert( Total_Result );
}
}; break; // This break belongs to the switch(Take_Action1)
case 2: case 3: case 4: case 5: case 6: Total_Result = true; break;
default: Total_Result = false; assert( Total_Result );
}
return Total_Result; //This is the final decision
}
//
// Get the beginnode from the line
// usage: Node *anode = a_line.GetBeginNode()
//
Node *KBoolLine::GetBeginNode()
{
// link must exist
assert(m_link);
return m_link->GetBeginNode();
}
//
// Get the endnode from the line
// usage: Node *anode = a_line.GetEndNode()
//
Node *KBoolLine::GetEndNode()
{
// link must exist
assert(m_link);
return m_link->GetEndNode();
}
// Intersects two lines
// input Line : another line
// Marge: optional, standard on MARGE
//
// return 0: If there are no crossings
// 1: If there is one crossing
// 2: If there are two crossings
int KBoolLine::Intersect(KBoolLine * lijn, double Marge)
{
double distance=0;
// lijn must exist
assert(lijn);
// points may not be equal
// must be an if statement because if an assert is used there will
// be a macro expansion error
if (m_link->GetBeginNode() == m_link->GetEndNode())
assert(!m_link);
Node *bp, *ep;
PointStatus Result_beginnode,Result_endnode;
int Take_Action1, Take_Action2, Number_of_Crossings = 0;
// Get the nodes from lijn via the link
bp = lijn->m_link->GetBeginNode();
ep = lijn->m_link->GetEndNode();
Result_beginnode = PointInLine(bp,distance,Marge);
Result_endnode = PointInLine(ep,distance,Marge);
Take_Action1 = ActionOnTable1(Result_beginnode,Result_endnode);
// The first switch will insert a crosspoint immediatly
switch (Take_Action1)
{
// for the cases see the returnvalue of ActionTable1
case 2: case 6: AddCrossing(ep);
Number_of_Crossings = 1;
break;
case 3: case 5: AddCrossing(bp);
Number_of_Crossings = 1;
break;
case 4: AddCrossing(bp);
AddCrossing(ep);
Number_of_Crossings = 2;
break;
}
// This switch wil investigate the points of this line in relation to lijn
switch (Take_Action1)
{
// for the cases see the returnvalue of ActionTable1
case 1: case 5: case 6:
{
// Get the nodes from this line via the link
bp = m_link->GetBeginNode();
ep = m_link->GetEndNode();
Result_beginnode = lijn->PointInLine(bp,distance,Marge);
Result_endnode = lijn->PointInLine(ep,distance,Marge);
Take_Action2 = ActionOnTable2(Result_beginnode,Result_endnode);
switch (Take_Action2)
{
// for the cases see the returnvalue of ActionTable2
case 1: { // begin of scope to calculate the intersection
double X, Y, Denominator;
CalculateLineParameters();
Denominator = (m_AA * lijn->m_BB) - (lijn->m_AA * m_BB);
// Denominator may not be 0
assert(Denominator != 0.0);
// Calculate intersection of both linesegments
X = ((m_BB * lijn->m_CC) - (lijn->m_BB * m_CC)) / Denominator;
Y = ((lijn->m_AA * m_CC) - (m_AA * lijn->m_CC)) / Denominator;
//make a decent rounding to B_INT
AddLineCrossing((B_INT)X,(B_INT)Y,lijn);
} // end of scope to calculate the intersection
Number_of_Crossings++;
break;
case 2: lijn->AddCrossing(ep);
Number_of_Crossings++;
break;
case 3: lijn->AddCrossing(bp);
Number_of_Crossings++;
break;
case 4: lijn->AddCrossing(bp);
lijn->AddCrossing(ep);
Number_of_Crossings = 2;
break;
}
}; break; // This break belongs to the outer switch
}
return Number_of_Crossings; //This is de final number of crossings
}
// Intersects two lines there must be a crossing
int KBoolLine::Intersect_simple(KBoolLine * lijn)
{
// lijn must exist
assert(lijn);
double X, Y, Denominator;
Denominator = (m_AA * lijn->m_BB) - (lijn->m_AA * m_BB);
// Denominator may not be 0
if (Denominator == 0.0)
m_GC->error("colliniar lines","line");
// Calculate intersection of both linesegments
X = ((m_BB * lijn->m_CC) - (lijn->m_BB * m_CC)) / Denominator;
Y = ((lijn->m_AA * m_CC) - (m_AA * lijn->m_CC)) / Denominator;
AddLineCrossing((B_INT)X,(B_INT)Y,lijn);
return(0);
}
// Intersects two lines there must be a crossing
bool KBoolLine::Intersect2(Node* crossing,KBoolLine * lijn)
{
// lijn must exist
assert(lijn);
double X, Y, Denominator;
Denominator = (m_AA * lijn->m_BB) - (lijn->m_AA * m_BB);
// Denominator may not be 0
if (Denominator == 0.0)
return false;
// Calculate intersection of both linesegments
X = ((m_BB * lijn->m_CC) - (lijn->m_BB * m_CC)) / Denominator;
Y = ((lijn->m_AA * m_CC) - (m_AA * lijn->m_CC)) / Denominator;
crossing->SetX((B_INT)X);
crossing->SetY((B_INT)Y);
return true;
}
//
// test if a point lies in the linesegment. If the point isn't on the line
// the function returns a value that indicates on which side of the
// line the point is (in linedirection from first point to second point
//
// returns LEFT_SIDE, when point lies on the left side of the line
// RIGHT_SIDE, when point lies on the right side of the line
// ON_AREA, when point lies on the infinite line within a range
// IN_AREA, when point lies in the area of the linesegment
// the returnvalues are declared in (LINE.H)
PointStatus KBoolLine::PointInLine(Node *a_node, double& Distance, double Marge)
{
Distance=0;
//Punt must exist
assert(a_node);
// link must exist to get beginnode and endnode via link
assert(m_link);
// get the nodes form the line via the link
Node *bp, *ep;
bp = m_link->GetBeginNode();
ep = m_link->GetEndNode();
// both node must exist
assert(bp && ep);
// node may not be the same
assert(bp != ep);
//quick test if point is begin or endpoint
if (a_node == bp || a_node == ep)
return IN_AREA;
int Result_of_BBox=false;
PointStatus Result_of_Online;
// Checking if point is in bounding-box with marge
B_INT xmin=bmin(bp->GetX(),ep->GetX());
B_INT xmax=bmax(bp->GetX(),ep->GetX());
B_INT ymin=bmin(bp->GetY(),ep->GetY());
B_INT ymax=bmax(bp->GetY(),ep->GetY());
if ( a_node->GetX() >= (xmin - Marge) && a_node->GetX() <= (xmax + Marge) &&
a_node->GetY() >= (ymin - Marge) && a_node->GetY() <= (ymax + Marge) )
Result_of_BBox=true;
// Checking if point is on the infinite line
Result_of_Online = PointOnLine(a_node, Distance, Marge);
// point in boundingbox of the line and is on the line then the point is IN_AREA
if ((Result_of_BBox) && (Result_of_Online == ON_AREA))
return IN_AREA;
else
return Result_of_Online;
}
//
// test if a point lies on the line. If the point isn't on the line
// the function returns a value that indicates on which side of the
// line the point is (in linedirection from first point to second point
//
// returns LEFT_SIDE, when point lies on the left side of the line
// ON_AREA, when point lies on the infinite line within a range
// RIGHT_SIDE, when point lies on the right side of the line
// LEFT_SIDE , RIGHT_SIDE , ON_AREA
PointStatus KBoolLine::PointOnLine(Node *a_node, double& Distance, double Marge)
{
Distance=0;
// a_node must exist
assert(a_node);
// link must exist to get beginnode and endnode
assert(m_link);
// get the nodes from the line via the link
Node *bp, *ep;
bp = m_link->GetBeginNode();
ep = m_link->GetEndNode();
// both node must exist
assert(bp && ep);
// node may not be queal
assert(bp!=ep);
//quick test if point is begin or endpoint
if (a_node == bp || a_node == ep)
return ON_AREA;
CalculateLineParameters();
// calculate the distance of a_node in relation to the line
Distance = (m_AA * a_node->GetX())+(m_BB * a_node->GetY()) + m_CC;
if (Distance < -Marge)
return LEFT_SIDE;
else
{
if (Distance > Marge)
return RIGHT_SIDE;
else
return ON_AREA;
}
}
//
// Sets lines parameters
// usage: a_line.Set(a_pointer_to_a_link);
//
void KBoolLine::Set(KBoolLink *a_link)
{
// points must exist
assert(a_link);
// points may not be equal
// must be an if statement because if an assert is used there will
// be a macro expansion error
// if (a_link->GetBeginNode()->Equal(a_link->GetEndNode(),MARGE)) assert(!a_link);
linecrosslist = NULL;
m_link = a_link;
m_valid_parameters = false;
}
KBoolLink* KBoolLine::GetLink()
{
return m_link;
}
//
// makes a line same as these
// usage : line1 = line2;
//
KBoolLine& KBoolLine::operator=(const KBoolLine& a_line)
{
m_AA = a_line.m_AA;
m_BB = a_line.m_BB;
m_CC = a_line.m_CC;
m_link = a_line.m_link;
linecrosslist = NULL;
m_valid_parameters = a_line.m_valid_parameters;
return *this;
}
Node* KBoolLine::OffsetContour(KBoolLine* const nextline,Node* _last_ins, double factor,Graph *shape)
{
KBoolLink* offs_currentlink;
KBoolLine offs_currentline(m_GC);
KBoolLink* offs_nextlink;
KBoolLine offs_nextline(m_GC);
Node* offs_end;
Node* offs_bgn_next;
Node* offs_end_next;
// make a node from this point
offs_end = new Node(GetEndNode(), m_GC);
Virtual_Point(offs_end,factor);
offs_currentlink=new KBoolLink(0, _last_ins,offs_end, m_GC);
offs_currentline.Set(offs_currentlink);
offs_bgn_next = new Node(nextline->m_link->GetBeginNode(), m_GC);
nextline->Virtual_Point(offs_bgn_next,factor);
offs_end_next = new Node(nextline->m_link->GetEndNode(), m_GC);
nextline->Virtual_Point(offs_end_next,factor);
offs_nextlink=new KBoolLink(0, offs_bgn_next, offs_end_next, m_GC);
offs_nextline.Set(offs_nextlink);
offs_currentline.CalculateLineParameters();
offs_nextline.CalculateLineParameters();
offs_currentline.Intersect2(offs_end,&offs_nextline);
// make a link between the current and the previous and add this to graph
shape->AddLink(offs_currentlink);
delete offs_nextlink;
return(offs_end);
}
Node* KBoolLine::OffsetContour_rounded(KBoolLine* const nextline,Node* _last_ins, double factor,Graph *shape)
{
KBoolLink* offs_currentlink;
KBoolLine offs_currentline(m_GC);
KBoolLink* offs_nextlink;
KBoolLine offs_nextline(m_GC);
Node* offs_end;
Node* medial_axes_point= new Node(m_GC);
Node* bu_last_ins = new Node(_last_ins, m_GC);
Node* offs_bgn_next;
Node* offs_end_next;
// make a node from this point
offs_end = new Node(GetEndNode(), m_GC);
*_last_ins = *GetBeginNode();
Virtual_Point(_last_ins,factor);
Virtual_Point(offs_end,factor);
offs_currentlink=new KBoolLink(0, _last_ins,offs_end, m_GC);
offs_currentline.Set(offs_currentlink);
offs_bgn_next = new Node(nextline->m_link->GetBeginNode(), m_GC);
nextline->Virtual_Point(offs_bgn_next,factor);
offs_end_next = new Node(nextline->m_link->GetEndNode(), m_GC);
nextline->Virtual_Point(offs_end_next,factor);
offs_nextlink=new KBoolLink(0, offs_bgn_next, offs_end_next, m_GC);
offs_nextline.Set(offs_nextlink);
offs_currentline.CalculateLineParameters();
offs_nextline.CalculateLineParameters();
offs_currentline.Intersect2(medial_axes_point,&offs_nextline);
double result_offs=sqrt( pow((double)GetEndNode()->GetY()-medial_axes_point->GetY(),2) +
pow((double)GetEndNode()->GetX()-medial_axes_point->GetX(),2) );
if ( result_offs < fabs(m_GC->GetRoundfactor()*factor))
{
*_last_ins=*bu_last_ins;
*offs_end=*medial_axes_point;
delete medial_axes_point;
delete bu_last_ins;
// make a link between the current and the previous and add this to graph
delete offs_nextlink;
shape->AddLink(offs_currentlink);
return(offs_end);
}
else
{ //let us create a circle
*_last_ins=*bu_last_ins;
delete medial_axes_point;
delete bu_last_ins;
Node* endarc= new Node(offs_bgn_next, m_GC);
shape->AddLink(offs_currentlink);
delete offs_nextlink;
shape->CreateArc(GetEndNode(), &offs_currentline, endarc,fabs(factor),m_GC->GetInternalCorrectionAber());
return(endarc);
}
}
bool KBoolLine::OkeForContour(KBoolLine* const nextline,double factor,Node* LastLeft,Node* LastRight, LinkStatus& _outproduct)
{
assert(m_link);
assert(m_valid_parameters);
assert(nextline->m_link);
assert(nextline->m_valid_parameters);
factor = fabs(factor);
// PointStatus status=ON_AREA;
double distance=0;
Node offs_end_next(nextline->m_link->GetEndNode(), m_GC);
_outproduct= m_link->OutProduct(nextline->m_link,m_GC->GetAccur());
switch (_outproduct)
{
// current line lies on leftside of prev line
case IS_RIGHT :
{
nextline->Virtual_Point(&offs_end_next,-factor);
// status=
nextline->PointOnLine(LastRight, distance, m_GC->GetAccur());
if (distance > factor)
{ PointOnLine(&offs_end_next, distance, m_GC->GetAccur());
if (distance > factor)
return(true);
}
}
break;
// current line lies on rightside of prev line
case IS_LEFT :
{
nextline->Virtual_Point(&offs_end_next,factor);
// status=
nextline->PointOnLine(LastLeft, distance, m_GC->GetAccur());
if (distance < -factor)
{ PointOnLine(&offs_end_next, distance, m_GC->GetAccur());
if (distance <-factor)
return(true);
}
}
break;
// current line lies on prev line
case IS_ON :
{
return(true);
}
}//end switch
return(false);
}
bool KBoolLine::Create_Ring_Shape(KBoolLine* nextline,Node** _last_ins_left,Node** _last_ins_right,double factor,Graph *shape)
{
Node* _current;
LinkStatus _outproduct=IS_ON;
if (OkeForContour(nextline,factor,*_last_ins_left,*_last_ins_right,_outproduct))
{
switch (_outproduct)
{
// Line 2 lies on leftside of this line
case IS_RIGHT :
{
*_last_ins_left =OffsetContour_rounded(nextline,*_last_ins_left,factor,shape);
*_last_ins_right =OffsetContour(nextline,*_last_ins_right,-factor,shape);
}
break;
case IS_LEFT :
{
*_last_ins_left =OffsetContour(nextline,*_last_ins_left,factor,shape);
*_last_ins_right =OffsetContour_rounded(nextline,*_last_ins_right,-factor,shape);
}
break;
// Line 2 lies on this line
case IS_ON :
{
// make a node from this point
_current = new Node(m_link->GetEndNode(), m_GC);
Virtual_Point(_current,factor);
// make a link between the current and the previous and add this to graph
shape->AddLink(*_last_ins_left, _current);
*_last_ins_left=_current;
_current = new Node(m_link->GetEndNode(), m_GC);
Virtual_Point(_current,-factor);
shape->AddLink(*_last_ins_right, _current);
*_last_ins_right=_current;
}
break;
}//end switch
return(true);
}
/* else
{
switch (_outproduct)
{
// Line 2 lies on leftside of this line
case IS_RIGHT :
{
*_last_ins_left =OffsetContour_rounded(nextline,*_last_ins_left,factor,Ishape);
*_last_ins_right =OffsetContour(nextline,*_last_ins_right,-factor,Ishape);
}
break;
case IS_LEFT :
{
*_last_ins_left =OffsetContour(nextline,*_last_ins_left,factor,Ishape);
*_last_ins_right =OffsetContour_rounded(nextline,*_last_ins_right,-factor,Ishape);
}
break;
// Line 2 lies on this line
case IS_ON :
{
// make a node from this point
_current = new Node(m_link->GetEndNode());
Virtual_Point(_current,factor);
// make a link between the current and the previous and add this to graph
Ishape->AddLink(*_last_ins_left, _current);
*_last_ins_left=_current;
_current = new Node(m_link->GetEndNode());
Virtual_Point(_current,-factor);
Ishape->AddLink(*_last_ins_right, _current);
*_last_ins_right=_current;
}
break;
}//end switch
return(true);
}
*/
return(false);
}
void KBoolLine::Create_Begin_Shape(KBoolLine* nextline,Node** _last_ins_left,Node** _last_ins_right,double factor,Graph *shape)
{
factor = fabs(factor);
LinkStatus _outproduct;
_outproduct= m_link->OutProduct(nextline->m_link,m_GC->GetAccur());
switch (_outproduct)
{
case IS_RIGHT :
{
*_last_ins_left = new Node(m_link->GetEndNode(), m_GC);
Virtual_Point(*_last_ins_left,factor);
*_last_ins_right = new Node(nextline->m_link->GetBeginNode(), m_GC);
nextline->Virtual_Point(*_last_ins_right,-factor);
shape->AddLink(*_last_ins_left, *_last_ins_right);
*_last_ins_left=OffsetContour_rounded(nextline,*_last_ins_left,factor,shape);
}
break;
case IS_LEFT :
{
*_last_ins_left = new Node(nextline->m_link->GetBeginNode(), m_GC);
nextline->Virtual_Point(*_last_ins_left,factor);
*_last_ins_right = new Node(m_link->GetEndNode(), m_GC);
Virtual_Point(*_last_ins_right,-factor);
shape->AddLink(*_last_ins_left, *_last_ins_right);
*_last_ins_right=OffsetContour_rounded(nextline,*_last_ins_right,-factor,shape);
}
break;
// Line 2 lies on this line
case IS_ON :
{
*_last_ins_left = new Node(nextline->m_link->GetBeginNode(), m_GC);
Virtual_Point(*_last_ins_left,factor);
*_last_ins_right = new Node(nextline->m_link->GetBeginNode(), m_GC);
Virtual_Point(*_last_ins_right,-factor);
shape->AddLink(*_last_ins_left, *_last_ins_right);
}
break;
}//end switch
}
void KBoolLine::Create_End_Shape(KBoolLine* nextline,Node* _last_ins_left,Node* _last_ins_right,double factor,Graph *shape)
{
Node* _current;
factor = fabs(factor);
LinkStatus _outproduct;
_outproduct= m_link->OutProduct(nextline->m_link,m_GC->GetAccur());
switch (_outproduct)
{
case IS_RIGHT :
{
_current = new Node(m_link->GetEndNode(), m_GC);
Virtual_Point(_current,-factor);
shape->AddLink(_last_ins_right, _current);
_last_ins_right=_current;
_last_ins_left=OffsetContour_rounded(nextline,_last_ins_left,factor,shape);
shape->AddLink(_last_ins_left,_last_ins_right);
}
break;
case IS_LEFT :
{
_current = new Node(m_link->GetEndNode(), m_GC);
Virtual_Point(_current,factor);
shape->AddLink(_last_ins_left, _current);
_last_ins_left=_current;
_last_ins_right=OffsetContour_rounded(nextline,_last_ins_right,-factor,shape);
shape->AddLink(_last_ins_right, _last_ins_left);
}
break;
// Line 2 lies on this line
case IS_ON :
{
_current = new Node(m_link->GetEndNode(), m_GC);
Virtual_Point(_current,factor);
shape->AddLink(_last_ins_left, _current);
_last_ins_left=_current;
_current = new Node(m_link->GetEndNode(), m_GC);
Virtual_Point(_current,-factor);
shape->AddLink(_last_ins_right, _current);
_last_ins_right=_current;
shape->AddLink(_last_ins_left, _last_ins_right);
}
break;
}//end switch
}
//
// Generate from the found crossings a part of the graph
//
bool KBoolLine::ProcessCrossings(TDLI<KBoolLink>* _LI)
{
Node *last; KBoolLink *dummy;
// assert (beginnode && endnode);
if (!linecrosslist) return false;
if (linecrosslist->empty()) return false;
if (linecrosslist->count()>1) SortLineCrossings();
m_link->GetEndNode()->RemoveLink(m_link);
last=m_link->GetEndNode();
// Make new links :
while (!linecrosslist->empty())
{
dummy=new KBoolLink(m_link->GetGraphNum(),(Node*) linecrosslist->tailitem(),last, m_GC);
dummy->SetBeenHere();
dummy->SetGroup(m_link->Group());
_LI->insbegin(dummy);
last=(Node*)linecrosslist->tailitem();
linecrosslist->removetail();
}
// Recycle this link :
last->AddLink(m_link);
m_link->SetEndNode(last);
delete linecrosslist;
linecrosslist=NULL;
return true;
}
/*
// Sorts the links on the X values
int NodeXYsorter(Node* a, Node* b)
{
if ( a->GetX() < b->GetX())
return(1);
if ( a->GetX() > b->GetX())
return(-1);
//they are eqaul in x
if ( a->GetY() < b->GetY())
return(-1);
if ( a->GetY() > b->GetY())
return(1);
//they are eqaul in y
return(0);
}
//
// Generate from the found crossings a part of the graph
// this routine is used in combination with the scanbeam class
// the this link most stay at the same place in the sorted graph
// The link is split into peaces wich are inserted sorted into the graph
// on beginnode.
// The mostleft link most become the new link for the beam record
// therefore the mostleft new/old link is returned to become the beam record link
// also the part returned needs to have the bin flag set to the original value it had in the beam
KBoolLink* KBoolLine::ProcessCrossingsSmart(TDLI<KBoolLink>* _LI)
{
Node *lastinserted;
KBoolLink *new_link;
KBoolLink *returnlink;
assert (beginnode && endnode);
if (!linecrosslist) return this;
if (linecrosslist->empty()) return this;
if (linecrosslist->count()>1)
{
SortLineCrossings();
}
int inbeam;
//most left at the beginnode or endnode
if (NodeXYsorter(beginnode,endnode)==1)
{
//re_use this link
endnode->RemoveLink(this);
linecrosslist->insend(endnode); //the last link to create is towards this node
endnode=(Node*) linecrosslist->headitem();
endnode->AddLink(this);
inbeam=NodeXYsorter(_LI->item()->beginnode,beginnode);
switch (inbeam)
{
case -1:
case 0:
bin=true;
break;
case 1:
bin=false;
break;
}
returnlink=this;
lastinserted=endnode;
linecrosslist->removehead();
// Make new links starting at endnode
while (!linecrosslist->empty())
{
new_link=new KBoolLink(graphnum,lastinserted,(Node*) linecrosslist->headitem());
new_link->group=group;
int inbeam=NodeXYsorter(_LI->item()->beginnode,lastinserted);
switch (inbeam)
{
case -1:
{
double x,y,xl,yl;
char buf[80];
x=((Node*)(linecrosslist->headitem()))->GetX();
y=((Node*)(linecrosslist->headitem()))->GetY();
xl=_LI->item()->beginnode->GetX();
yl=_LI->item()->beginnode->GetY();
sprintf(buf," x=%f , y=%f inserted before %f,%f",x,y,xl,yl);
_messagehandler->info(buf,"scanbeam");
new_link->bin=true;
}
break;
case 0:
new_link->bin=true;
returnlink=new_link;
break;
case 1:
new_link->bin=false;
break;
}
//insert a link into the graph that is already sorted on beginnodes of the links.
//starting at a given position
// if empty then just insert
if (_LI->empty())
_LI->insend(new_link);
else
{
// put new item left of the one that is bigger are equal
int i=0;
int insert=0;
while(!_LI->hitroot())
{
if ((insert=linkXYsorter(new_link,_LI->item()))!=-1)
break;
(*_LI)++;
i++;
}
_LI->insbefore_unsave(new_link);
if (insert==0 && _LI->item()->beginnode!=new_link->beginnode)
//the begin nodes are equal but not the same merge them into one node
{ Node* todelete=_LI->item()->beginnode;
new_link->beginnode->Merge(todelete);
delete todelete;
}
//set back iter
(*_LI) << (i+1);
}
lastinserted=(Node*)linecrosslist->headitem();
linecrosslist->removehead();
}
}
else
{
//re_use this link
endnode->RemoveLink(this);
linecrosslist->insend(endnode); //the last link to create is towards this node
endnode=(Node*) linecrosslist->headitem();
endnode->AddLink(this);
inbeam=NodeXYsorter(_LI->item()->beginnode,endnode);
switch (inbeam)
{
case -1:
case 0:
bin=true;
break;
case 1:
bin=false;
break;
}
returnlink=this;
lastinserted=endnode;
linecrosslist->removehead();
// Make new links starting at endnode
while (!linecrosslist->empty())
{
new_link=new KBoolLink(graphnum,lastinserted,(Node*) linecrosslist->headitem());
new_link->group=group;
inbeam=NodeXYsorter(_LI->item()->beginnode,(Node*) linecrosslist->headitem());
switch (inbeam)
{
case -1:
case 0:
new_link->bin=true;
break;
case 1:
new_link->bin=false;
break;
}
inbeam=NodeXYsorter(_LI->item()->beginnode,lastinserted);
switch (inbeam)
{
case -1:
{
double x,y,xl,yl;
char buf[80];
x=lastinserted->GetX();
y=lastinserted->GetY();
xl=_LI->item()->beginnode->GetX();
yl=_LI->item()->beginnode->GetY();
sprintf(buf," x=%f , y=%f inserted before %f,%f",x,y,xl,yl);
_messagehandler->info(buf,"scanbeam");
}
break;
case 0:
break;
case 1:
returnlink=new_link;
break;
}
//insert a link into the graph that is already sorted on beginnodes of the links.
//starting at a given position
// if empty then just insert
if (_LI->empty())
_LI->insend(new_link);
else
{
// put new item left of the one that is bigger are equal
int i=0;
int insert=0;
while(!_LI->hitroot())
{
if ((insert=linkXYsorter(new_link,_LI->item()))!=-1)
break;
(*_LI)++;
i++;
}
_LI->insbefore_unsave(new_link);
if (insert==0 && _LI->item()->beginnode!=new_link->beginnode)
//the begin nodes are equal but not the same merge them into one node
{ Node* todelete=_LI->item()->beginnode;
new_link->beginnode->Merge(todelete);
delete todelete;
}
//set back iter
(*_LI) << (i+1);
}
lastinserted=(Node*)linecrosslist->headitem();
linecrosslist->removehead();
}
}
delete linecrosslist;
linecrosslist=NULL;
return returnlink;
}
*/
static int NODE_X_ASCENDING_L (Node* a, Node* b)
{
if(b->GetX() > a->GetX()) return(1);
else
if(b->GetX() == a->GetX()) return(0);
return(-1);
}
static int NODE_X_DESCENDING_L(Node* a, Node* b)
{
if(a->GetX() > b->GetX()) return(1);
else
if(a->GetX() == b->GetX()) return(0);
return(-1);
}
static int NODE_Y_ASCENDING_L (Node* a, Node* b)
{
if(b->GetY() > a->GetY()) return(1);
else
if(b->GetY() == a->GetY()) return(0);
return(-1);
}
static int NODE_Y_DESCENDING_L(Node* a, Node* b)
{
if(a->GetY() > b->GetY()) return(1);
else
if(a->GetY() == b->GetY()) return(0);
return(-1);
}
//
// This function finds out which sortfunction to use with sorting
// the crossings.
//
void KBoolLine::SortLineCrossings()
{
TDLI<Node> I(linecrosslist);
B_INT dx, dy;
dx=babs(m_link->GetEndNode()->GetX() - m_link->GetBeginNode()->GetX());
dy=babs(m_link->GetEndNode()->GetY() - m_link->GetBeginNode()->GetY());
if (dx > dy)
{ // thislink is more horizontal then vertical
if (m_link->GetEndNode()->GetX() > m_link->GetBeginNode()->GetX())
I.mergesort(NODE_X_ASCENDING_L);
else
I.mergesort(NODE_X_DESCENDING_L);
}
else
{ // this link is more vertical then horizontal
if (m_link->GetEndNode()->GetY() > m_link->GetBeginNode()->GetY())
I.mergesort(NODE_Y_ASCENDING_L);
else
I.mergesort(NODE_Y_DESCENDING_L);
}
}
//
// Adds a cross Node to this. a_node may not be deleted before processing the crossings
//
void KBoolLine::AddCrossing(Node *a_node)
{
if (a_node==m_link->GetBeginNode() || a_node==m_link->GetEndNode()) return;
if (!linecrosslist)
{
linecrosslist=new DL_List<void*>();
linecrosslist->insend(a_node);
}
else
{
TDLI<Node> I(linecrosslist);
if (!I.has(a_node))
I.insend(a_node);
}
}
//
// see above
//
Node* KBoolLine::AddCrossing(B_INT X, B_INT Y)
{
Node* result=new Node(X,Y, m_GC);
AddCrossing(result);
return result;
}
DL_List<void*>* KBoolLine::GetCrossList()
{
if (linecrosslist)
return linecrosslist;
return NULL;
}
bool KBoolLine::CrossListEmpty()
{
if (linecrosslist)
return linecrosslist->empty();
return true;
}
/*
bool KBoolLine::HasInCrossList(Node *n)
{
if(linecrosslist!=NULL)
{
TDLI<Node> I(linecrosslist);
return I.has(n);
}
return false;
}
*/
/*! \file ../src/link.cpp
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: link.cpp,v 1.10 2005/06/17 22:54:37 kbluck Exp $
*/
#ifdef __GNUG__
#pragma implementation
#endif
#include "../include/booleng.h"
#include "../include/link.h"
#include "../include/line.h"
#include <math.h>
#include <assert.h>
#include "../include/node.h"
#include "../include/graph.h"
#include "../include/graphlst.h"
int linkXYsorter(KBoolLink *, KBoolLink *);
//
// Default constructor
//
KBoolLink::KBoolLink(Bool_Engine* GC)
{
_GC=GC;
Reset();
}
//
// This constructor makes this link a valid part of a graph
//
KBoolLink::KBoolLink(int graphnr, Node *begin, Node *end, Bool_Engine* GC)
{
_GC=GC;
Reset();
// Set the references of the node and of this link correct
begin->AddLink(this);
end->AddLink(this);
m_beginnode = begin;
m_endnode = end;
m_graphnum = graphnr;
}
//
// This constructor makes this link a valid part of a graph
//
KBoolLink::KBoolLink(Node *begin, Node *end, Bool_Engine* GC)
{
_GC=GC;
Reset();
// Set the references of the node and of this link correct
begin->AddLink(this);
end->AddLink(this);
m_beginnode=begin;
m_endnode=end;
m_graphnum=0;
}
//
// Destructor
//
KBoolLink::~KBoolLink()
{
UnLink();
}
//
// Checks whether the current algorithm has been on this link
//
bool KBoolLink::BeenHere()
{
if (m_bin) return true;
return false;
}
void KBoolLink::TakeOverOperationFlags( KBoolLink* link )
{
m_merge_L = link->m_merge_L;
m_a_substract_b_L = link->m_a_substract_b_L;
m_b_substract_a_L = link->m_b_substract_a_L;
m_intersect_L = link->m_intersect_L;
m_exor_L = link->m_exor_L;
m_merge_R = link->m_merge_R;
m_a_substract_b_R = link->m_a_substract_b_R;
m_b_substract_a_R = link->m_b_substract_a_R;
m_intersect_R = link->m_intersect_R;
m_exor_R = link->m_exor_R;
}
//
// Returns the next link from the argument
//
KBoolLink* KBoolLink::Forth(Node *node)
{
assert(node==m_beginnode || node==m_endnode);
return node->GetOtherLink(this);
}
//
// Returns the Beginnode
//
Node *KBoolLink::GetBeginNode()
{
return m_beginnode;
}
//
// Returns the endnode
//
Node* KBoolLink::GetEndNode()
{
return m_endnode;
}
Node* KBoolLink::GetLowNode()
{
return ( ( m_beginnode->GetY() < m_endnode->GetY() ) ? m_beginnode : m_endnode );
}
Node* KBoolLink::GetHighNode()
{
return ( ( m_beginnode->GetY() > m_endnode->GetY() ) ? m_beginnode : m_endnode );
}
//
// Returns the graphnumber
//
int KBoolLink::GetGraphNum()
{
return m_graphnum;
}
bool KBoolLink::GetInc()
{
return m_Inc;
// if (Inc) return true;
// return false;
}
void KBoolLink::SetInc(bool inc)
{
m_Inc = inc;
// Inc=0;
// if (inc) Inc=1;
}
bool KBoolLink::GetLeftA()
{
return m_LeftA;
}
void KBoolLink::SetLeftA(bool la)
{
m_LeftA = la;
}
bool KBoolLink::GetLeftB()
{
return m_LeftB;
}
void KBoolLink::SetLeftB(bool lb)
{
m_LeftB = lb;
}
bool KBoolLink::GetRightA()
{
return m_RightA;
}
void KBoolLink::SetRightA(bool ra)
{
m_RightA = ra;
}
bool KBoolLink::GetRightB()
{
return m_RightB;
}
void KBoolLink::SetRightB(bool rb)
{
m_RightB = rb;
}
//
// This function is very popular by GP-faults
// It returns the node different from a
//
Node* KBoolLink::GetOther(const Node *const a)
{
return ( (a != m_beginnode) ? m_beginnode : m_endnode);
}
//
// Is this marked for given operation
//
bool KBoolLink::IsMarked(BOOL_OP operation)
{
switch (operation)
{
case(BOOL_OR): return m_merge_L || m_merge_R;
case(BOOL_AND): return m_intersect_L || m_intersect_R;
case(BOOL_A_SUB_B): return m_a_substract_b_L || m_a_substract_b_R;
case(BOOL_B_SUB_A): return m_b_substract_a_L || m_b_substract_a_R;
case(BOOL_EXOR): return m_exor_L || m_exor_R;
default: return false;
}
}
bool KBoolLink::IsMarkedLeft(BOOL_OP operation)
{
switch (operation)
{
case(BOOL_OR): return m_merge_L;
case(BOOL_AND): return m_intersect_L;
case(BOOL_A_SUB_B): return m_a_substract_b_L;
case(BOOL_B_SUB_A): return m_b_substract_a_L;
case(BOOL_EXOR): return m_exor_L;
default: return false;
}
}
bool KBoolLink::IsMarkedRight(BOOL_OP operation)
{
switch (operation)
{
case(BOOL_OR): return m_merge_R;
case(BOOL_AND): return m_intersect_R;
case(BOOL_A_SUB_B): return m_a_substract_b_R;
case(BOOL_B_SUB_A): return m_b_substract_a_R;
case(BOOL_EXOR): return m_exor_R;
default: return false;
}
}
//
// Is this a hole for given operation
// beginnode must be to the left
bool KBoolLink::IsHole(BOOL_OP operation)
{
bool topsideA,topsideB;
if (m_beginnode->GetX() < m_endnode->GetX()) //going to the right?
{ topsideA = m_RightA; topsideB = m_RightB; }
else
{ topsideA = m_LeftA; topsideB = m_LeftB; }
switch (operation)
{
case(BOOL_OR): return ( !topsideB && !topsideA );
case(BOOL_AND): return ( !topsideB || !topsideA );
case(BOOL_A_SUB_B): return ( topsideB || !topsideA );
case(BOOL_B_SUB_A): return ( topsideA || !topsideB );
case(BOOL_EXOR): return !( (topsideB && !topsideA) || (!topsideB && topsideA) );
default: return false;
}
}
//
// Is this a part of a hole
//
bool KBoolLink::GetHole()
{
return (m_hole);
}
void KBoolLink::SetHole(bool h)
{
m_hole = h;
}
//
// Is this not marked at all
//
bool KBoolLink::IsUnused()
{
return
!(m_merge_L || m_merge_R ||
m_a_substract_b_L || m_a_substract_b_R ||
m_b_substract_a_L || m_b_substract_a_R ||
m_intersect_L || m_intersect_R ||
m_exor_L || m_exor_R );
}
bool KBoolLink::IsZero(B_INT marge)
{
return (m_beginnode->Equal(m_endnode,marge)) ;
}
bool KBoolLink::ShorterThan(B_INT marge)
{
return (m_beginnode->ShorterThan(m_endnode,marge)) ;
}
//
// Mark this link
//
void KBoolLink::Mark()
{
m_mark = true;
}
#ifndef ABS
#define ABS(a) (((a)<0) ? -(a) : (a))
#endif
//
// This makes from the begin and endnode one node (argument begin_or_end_node)
// The references to this link in the node will also be deleted
// After doing that, link link can be deleted or be recycled.
//
void KBoolLink::MergeNodes(Node *const begin_or_end_node)
{
// assert(beginnode && endnode);
// assert ((begin_or_end_node == beginnode)||(begin_or_end_node == endnode));
m_beginnode->RemoveLink(this);
m_endnode->RemoveLink(this);
if (m_endnode != m_beginnode)
{ // only if beginnode and endnode are different nodes
begin_or_end_node->Merge(GetOther(begin_or_end_node));
}
m_endnode = NULL;
m_beginnode=NULL;
}
//
// Return the position of the second link compared to this link
// Result = IS_ON | IS_LEFT | IS_RIGHT
// Here Left and Right is defined as being left or right from
// the this link towards the center (common) node
//
LinkStatus KBoolLink::OutProduct(KBoolLink* const two,double accur)
{
Node* center;
double distance;
if (two->GetBeginNode()->Equal(two->GetEndNode(), 1))
assert(!two);
if (GetBeginNode()->Equal(GetEndNode(), 1))
assert(!this);
KBoolLine* temp_line = new KBoolLine(this, _GC);
//the this link should connect to the other two link at at least one node
if (m_endnode == two->m_endnode || m_endnode == two->m_beginnode)
center = m_endnode;
else
{ center = m_beginnode;
// assert(center==two->endnode || center==two->beginnode);
}
//here something tricky
// the factor 10000.0 is needed to asure that the pointonline
// is more accurate in this case compared to the intersection for graphs
int uitp = temp_line->PointOnLine(two->GetOther(center), distance, accur);
delete temp_line;
/*double uitp= (_x - first._x) * (third._y - _y) -
(_y - first._y) * (third._x - _x);
if (uitp>0) return IS_LEFT;
if (uitp<0) return IS_RIGHT;
return IS_ON;*/
//depending on direction of this link (going to or coming from centre)
if (center == m_endnode)
{
if (uitp==LEFT_SIDE)
return IS_LEFT;
if (uitp==RIGHT_SIDE)
return IS_RIGHT;
}
else //center=beginnode
{
if (uitp==LEFT_SIDE)
return IS_RIGHT;
if (uitp==RIGHT_SIDE)
return IS_LEFT;
}
return IS_ON;
}
//
// Return the position of the third link compared to this link and
// the second link
// Result = IS_ON | IS_LEFT | IS_RIGHT
//
LinkStatus KBoolLink::PointOnCorner(KBoolLink* const two, KBoolLink* const third)
{
LinkStatus
TwoToOne, // Position of two to this line
ThirdToOne, // Position of third to this line
ThirdToTwo, // Position of third to two
Result;
//m Node* center;
//the this link should connect to the other two link at at least one node
//m if (endnode==two->endnode || endnode==two->beginnode)
//m center=endnode;
//m else
//m { center=beginnode;
// assert(center==two->endnode || center==two->beginnode);
//m }
// assert(center==third->endnode || center==third->beginnode);
// Calculate the position of the links compared to eachother
TwoToOne = OutProduct(two,_GC->GetAccur());
ThirdToOne= OutProduct(third,_GC->GetAccur());
//center is used in outproduct to give de direction of two
// this is why the result should be swapped
ThirdToTwo= two->OutProduct(third,_GC->GetAccur());
if (ThirdToTwo==IS_RIGHT)
ThirdToTwo=IS_LEFT;
else if (ThirdToTwo==IS_LEFT)
ThirdToTwo=IS_RIGHT;
// Select the result
switch(TwoToOne)
{
// Line 2 lies on leftside of this line
case IS_LEFT : if ((ThirdToOne==IS_RIGHT) || (ThirdToTwo==IS_RIGHT)) return IS_RIGHT;
else if ((ThirdToOne==IS_LEFT) && (ThirdToTwo==IS_LEFT)) return IS_LEFT;
else Result=IS_ON; break;
// Line 2 lies on this line
case IS_ON : if ((ThirdToOne==IS_RIGHT) && (ThirdToTwo==IS_RIGHT)) return IS_RIGHT;
else if ((ThirdToOne==IS_LEFT) && (ThirdToTwo==IS_LEFT)) return IS_LEFT;
// else if ((ThirdToOne==IS_RIGHT) && (ThirdToTwo==IS_LEFT)) return IS_RIGHT;
// else if ((ThirdToOne==IS_LEFT) && (ThirdToTwo==IS_RIGHT)) return IS_LEFT;
else Result=IS_ON; break;
// Line 2 lies on right side of this line
case IS_RIGHT :if ((ThirdToOne==IS_RIGHT) && (ThirdToTwo==IS_RIGHT)) return IS_RIGHT;
else if ((ThirdToOne==IS_LEFT) || (ThirdToTwo==IS_LEFT)) return IS_LEFT;
else Result=IS_ON; break;
default: Result = IS_ON; assert( false );
}
return Result;
}
//
// Remove the reference from this link to a_node
//
void KBoolLink::Remove(Node *a_node)
{
(m_beginnode == a_node) ? m_beginnode = NULL : m_endnode = NULL;
}
//
// Replace oldnode by newnode and correct the references
//
void KBoolLink::Replace(Node *oldnode, Node *newnode)
{
if (m_beginnode == oldnode)
{ m_beginnode->RemoveLink(this); // remove the reference to this
newnode->AddLink(this); // let newnode refer to this
m_beginnode = newnode; // let this refer to newnode
}
else
{ //assert(endnode==oldnode);
m_endnode->RemoveLink(this);
newnode->AddLink(this);
m_endnode = newnode;
}
}
//
// Reset all values
//
void KBoolLink::Reset()
{
m_beginnode = 0;
m_endnode = 0;
Reset_flags();
}
//
// Reset all flags
//
void KBoolLink::Reset_flags()
{
m_bin = false; // Marker for walking over the graph
m_hole = false; // Is this a part of hole ?
m_hole_top = false; // link that is toplink of hole?
m_group = GROUP_A; // Does this belong to group A or B ( o.a. for boolean operations between graphs)
m_LeftA = false; // Is left in polygongroup A
m_RightA= false; // Is right in polygon group A
m_LeftB = false; // Is left in polygon group B
m_RightB= false; // Is right in polygongroup B
m_mark = false; // General purose marker, internally unused
m_holelink=false;
m_merge_L = m_merge_R = false; // Marker for Merge
m_a_substract_b_L = m_a_substract_b_R = false; // Marker for substract
m_b_substract_a_L = m_b_substract_a_R = false; // Marker for substract
m_intersect_L = m_intersect_R = false; // Marker for intersect
m_exor_L = m_exor_R= false; // Marker for Exor
}
//
// Refill this link by the arguments
//
void KBoolLink::Reset(Node *begin, Node *end,int graphnr)
{
// Remove all the previous references
UnLink();
Reset();
// Set the references of the node and of this link correct
begin->AddLink(this);
end->AddLink(this);
m_beginnode = begin;
m_endnode = end;
if (graphnr!=0)
m_graphnum = graphnr;
}
void KBoolLink::Set(Node *begin, Node *end)
{
m_beginnode = begin;
m_endnode = end;
}
void KBoolLink::SetBeenHere()
{
m_bin = true;
}
void KBoolLink::SetNotBeenHere()
{
m_bin = false;
}
void KBoolLink::SetBeginNode(Node* new_node)
{
m_beginnode = new_node;
}
void KBoolLink::SetEndNode(Node* new_node)
{
m_endnode = new_node;
}
//
// Sets the graphnumber to argument num
//
void KBoolLink::SetGraphNum( int num )
{
m_graphnum=num;
}
GroupType KBoolLink::Group()
{
return m_group;
}
//
// Reset the groupflag to argument groep
//
void KBoolLink::SetGroup(GroupType groep)
{
m_group= groep;
}
//
// Remove all references to this link and from this link
//
void KBoolLink::UnLink()
{
if (m_beginnode)
{ m_beginnode->RemoveLink(this);
if (!m_beginnode->GetNumberOfLinks()) delete m_beginnode;
}
m_beginnode=NULL;
if (m_endnode)
{ m_endnode->RemoveLink(this);
if (!m_endnode->GetNumberOfLinks()) delete m_endnode;
}
m_endnode=NULL;
}
void KBoolLink::UnMark()
{
m_mark = false;
m_bin = false;
}
void KBoolLink::SetMark(bool value)
{
m_mark = value;
}
//
// general purpose mark checker
//
bool KBoolLink::IsMarked() { return m_mark; }
void KBoolLink::SetTopHole(bool value) { m_hole_top = value; }
bool KBoolLink::IsTopHole() { return m_hole_top; }
//
// Calculates the merge/substact/exor/intersect flags
//
void KBoolLink::SetLineTypes()
{
m_merge_R =
m_a_substract_b_R =
m_b_substract_a_R =
m_intersect_R =
m_exor_R =
m_merge_L =
m_a_substract_b_L =
m_b_substract_a_L =
m_intersect_L =
m_exor_L = false;
//if left side is in group A and B then it is for the merge
m_merge_L = m_LeftA || m_LeftB;
m_merge_R = m_RightA || m_RightB;
//both in mean does not add to result.
if (m_merge_L && m_merge_R)
m_merge_L = m_merge_R = false;
m_a_substract_b_L = m_LeftA && !m_LeftB;
m_a_substract_b_R = m_RightA && !m_RightB;
//both in mean does not add to result.
if (m_a_substract_b_L && m_a_substract_b_R)
m_a_substract_b_L = m_a_substract_b_R = false;
m_b_substract_a_L = m_LeftB && !m_LeftA;
m_b_substract_a_R = m_RightB && !m_RightA;
//both in mean does not add to result.
if (m_b_substract_a_L && m_b_substract_a_R)
m_b_substract_a_L = m_b_substract_a_R = false;
m_intersect_L = m_LeftB && m_LeftA;
m_intersect_R = m_RightB && m_RightA;
//both in mean does not add to result.
if (m_intersect_L && m_intersect_R)
m_intersect_L = m_intersect_R = false;
m_exor_L = !( (m_LeftB && m_LeftA) || (!m_LeftB && !m_LeftA) );
m_exor_R = !( (m_RightB && m_RightA) || (!m_RightB && !m_RightA) );
//both in mean does not add to result.
if (m_exor_L && m_exor_R)
m_exor_L = m_exor_R = false;
}
//put in direction with a_node as beginnode
void KBoolLink::Redirect(Node* a_node)
{
if (a_node != m_beginnode)
{
// swap the begin- and endnode of the current link
Node* dummy = m_beginnode;
m_beginnode = m_endnode;
m_endnode = dummy;
bool swap = m_LeftA;
m_LeftA = m_RightA;
m_RightA= swap;
swap = m_LeftB;
m_LeftB = m_RightB;
m_RightB= swap;
swap = m_merge_L ;
m_merge_L = m_merge_R;
m_merge_R = swap;
swap = m_a_substract_b_L;
m_a_substract_b_L = m_a_substract_b_R;
m_a_substract_b_R = swap;
swap = m_b_substract_a_L;
m_b_substract_a_L = m_b_substract_a_R;
m_b_substract_a_R = swap;
swap = m_intersect_L;
m_intersect_L = m_intersect_R;
m_intersect_R = swap;
swap = m_exor_L;
m_exor_L = m_exor_R;
m_exor_R = swap;
}
}
/*! \file ../src/lpoint.cpp
\brief Definition of GDSII LPoint type structure
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: lpoint.cpp,v 1.4 2005/05/24 19:13:39 titato Exp $
*/
#ifdef __GNUG__
#pragma implementation
#endif
#include "../include/lpoint.h"
#include <math.h>
// Constructors
LPoint::LPoint()
{
_x = 0;
_y = 0;
}
LPoint::LPoint(B_INT const X, B_INT const Y)
{
_x = X;
_y = Y;
}
LPoint::LPoint(LPoint* const a_point)
{
if (!a_point)
throw Bool_Engine_Error("Cannot copy a NULL Point Object.\n\nCould not create a LPoint Object.",
"Fatal Creation Error", 0, 1);
_x = a_point->_x;
_y = a_point->_y;
}
B_INT LPoint::GetX()
{
return _x;
}
B_INT LPoint::GetY()
{
return _y;
}
void LPoint::SetX(B_INT a_point_x)
{
_x = a_point_x;
}
void LPoint::SetY(B_INT a_point_y)
{
_y = a_point_y;
}
LPoint LPoint::GetPoint()
{
return *this;
}
void LPoint::Set(const B_INT X,const B_INT Y)
{
_x = X;
_y = Y;
}
void LPoint::Set(const LPoint &a_point)
{
_x = a_point._x;
_y =a_point._y;
}
bool LPoint::Equal(const LPoint a_point, B_INT Marge)
{
B_INT delta_x, delta_y;
delta_x = babs((_x - a_point._x));
delta_y = babs((_y - a_point._y));
if ((delta_x <= Marge) && (delta_y <= Marge))
return true;
else
return false;
}
bool LPoint::Equal(const B_INT X, const B_INT Y, B_INT Marge)
{
return (bool)((babs(_x - X) <= Marge) && (babs(_y - Y) <= Marge));
}
bool LPoint::ShorterThan(const LPoint a_point, B_INT Marge)
{
double a,b;
a = (double) (a_point._x - _x);
a*= a;
b = (double) (a_point._y - _y);
b*= b;
return (bool) ( (a+b) <= Marge*Marge ? true : false ) ;
}
bool LPoint::ShorterThan(const B_INT X, const B_INT Y, B_INT Marge)
{
double a,b;
a = (double) (X - _x);
a*= a;
b = (double) (Y - _y);
b*= b;
return (bool) ( a+b <= Marge*Marge ? true : false ) ;
}
// overload the assign (=) operator
// usage : a_point = another_point;
LPoint &LPoint::operator=(const LPoint &other_point)
{
_x = other_point._x;
_y = other_point._y;
return *this;
}
// overload the + operator
// usage : a_point = point1 + point2;
LPoint &LPoint::operator+(const LPoint &other_point)
{
_x += other_point._x;
_y += other_point._y;
return *this;
}
// overload the - operator
// usage : a_point = point1 - point2;
LPoint &LPoint::operator-(const LPoint &other_point)
{
_x -= other_point._x;
_y -= other_point._y;
return *this;
}
// overload the * operator
// usage: a_point = point1 * 100;
LPoint &LPoint::operator*(int factor)
{
_x *= factor;
_y *= factor;
return *this;
}
// overload the / operator
// usage: a_point = point1 / 100;
LPoint &LPoint::operator/(int factor)
{
_x /= factor;
_y /= factor;
return *this;
}
// overload the compare (==) operator
// usage: if (point1 == point2) { };
int LPoint::operator==(const LPoint &other_point) const
{
return ((other_point._x == _x) && (other_point._y == _y));
}
// overload the diffrent (!=) operator
// usage: if (point1 != point2) { };
int LPoint::operator!=(const LPoint &other_point) const
{
return ((other_point._x != _x) || (other_point._y != _y));
}
WXDIR = $(WXWIN)
TARGET = libkbool.a
all: $(TARGET)
include makefile.include
$(TARGET): $(OBJECTS) makefile.include
ar ruv $@ $(OBJECTS)
ranlib $@
clean:
rm -f *.bak
rm -f *.o
rm -f $(TARGET)
WXDIR = $(WXWIN)
TARGET = libkbool.a
all: $(TARGET)
include makefile.include
$(TARGET): $(OBJECTS) makefile.include
ar ruv $@ $(OBJECTS)
ranlib $@
clean:
rm -f *.bak
rm -f *.o
rm -f $(TARGET)
OBJECTS =\
booleng.o\
graph.o\
graphlst.o\
line.o\
link.o\
lpoint.o\
node.o\
record.o\
scanbeam.o
WXDIR = $(WXWIN)
TARGET = libkbool.a
all: $(TARGET)
include makefile.include
$(TARGET): $(OBJECTS) makefile.include
ar ruv $@ $(OBJECTS)
ranlib $@
clean:
rm -f *.bak
rm -f *.o
rm -f $(TARGET)
/*! \file ../src/node.cpp
\brief Holds a GDSII node structure
\author Probably Klaas Holwerda
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: node.cpp,v 1.7 2005/06/17 23:01:03 kbluck Exp $
*/
#ifdef __GNUG__
#pragma implementation
#endif
#include "../include/node.h"
#include "../include/link.h"
#include "../include/line.h"
#include <math.h>
//this here is to initialize the static iterator of node
//with NOLIST constructor
//TDLI<KBoolLink> Node::_linkiter=TDLI<KBoolLink>(_GC);
Node::Node(Bool_Engine* GC) : LPoint(0,0)
{
_GC=GC;
_linklist=new DL_List<void*>();
}
Node::Node(B_INT const X, B_INT const Y, Bool_Engine* GC) : LPoint(X,Y)
{
_GC=GC;
_linklist=new DL_List<void*>();
}
Node::Node(LPoint* const a_point, Bool_Engine* GC) : LPoint(a_point)
{
_GC=GC;
_linklist=new DL_List<void*>();
}
//Node::Node(Node * const other) : LPoint(other)
Node::Node(Node * const other, Bool_Engine* GC)
{
_GC=GC;
_x = other->_x;
_y = other->_y;
_linklist=new DL_List<void*>();
}
Node& Node::operator=(const Node &other_node)
{
_x = other_node._x;
_y = other_node._y;
return *this;
}
// x and y of the point will be rounded to the nearest
// xnew=N*grid and ynew=N*grid
void Node::RoundInt(B_INT grid)
{
_x=(B_INT) floor((_x + grid * 0.5) / grid) * grid;
_y=(B_INT) floor((_y + grid * 0.5) / grid) * grid;
}
Node::~Node()
{
delete _linklist;
}
DL_List<void*>* Node::GetLinklist()
{
return _linklist;
}
void Node::AddLink(KBoolLink *a_link)
{
// assert(a_link);
_linklist->insbegin(a_link);
}
KBoolLink* Node::GetIncomingLink()
{
if (((KBoolLink*)_linklist->headitem())->GetEndNode() == this)
return (KBoolLink*)_linklist->headitem();
else
return (KBoolLink*)_linklist->tailitem();
}
KBoolLink* Node::GetOutgoingLink()
{
if (((KBoolLink*)_linklist->headitem())->GetBeginNode() == this)
return (KBoolLink*)_linklist->headitem();
else
return (KBoolLink*)_linklist->tailitem();
}
//
// Returns the number of connected links
//
int Node::GetNumberOfLinks()
{
return _linklist->count();
}
KBoolLink* Node::GetOtherLink(KBoolLink* prev)
{
if (prev==(KBoolLink*)_linklist->headitem())
return (KBoolLink*)_linklist->tailitem();
if (prev==(KBoolLink*)_linklist->tailitem())
return (KBoolLink*)_linklist->headitem();
return NULL;
}
int Node::Merge(Node *other)
{
if (this==other) //they are already merged dummy
return 0;
_GC->_linkiter->Attach(_linklist);
int Counter;
// used to delete Iterator on other->_linklist
// otherwise there can't be a takeover, because for takeover there can't
// be an iterator on other->_linklist;
{
TDLI<KBoolLink> Iother(other->_linklist);
KBoolLink* temp;
Counter = Iother.count();
Iother.tohead();
while (!Iother.hitroot())
{
temp=Iother.item();
//need to test both nodes because it may be a zero length link
if (temp->GetEndNode()==other)
temp->SetEndNode(this);
if (temp->GetBeginNode()==other)
temp->SetBeginNode(this);
Iother++;
}
_GC->_linkiter->takeover(&Iother);
}
_GC->_linkiter->Detach();
//at this moment the other nodes has no link pointing to it so it needs to be deleted
delete other;
return Counter;
}
void Node::RemoveLink(KBoolLink *a_link)
{
// assert(a_link);
_GC->_linkiter->Attach(_linklist);
if (_GC->_linkiter->toitem(a_link)) // find the link
_GC->_linkiter->remove();
_GC->_linkiter->Detach();
}
// This function will determinate if the given three points
// can be simplified to two points
//
// input : three nodes, the first and the second must be points of
// a line in correct order, the third point is a point of another
// line.
// output: -
// return: true if points can be simplified
// false if points can't be simplified
bool Node::Simplify(Node *First, Node *Second, B_INT Marge)
{
double distance=0;
// The first and second point are a zero line, if so we can
// make a line between the first and third point
if (First->Equal(Second,Marge))
return true;
// Are the first and third point equal, if so
// we can delete the second point
if (First->Equal(this, Marge))
return true;
// Used tmp_link.set here, because the link may not be linked in the graph,
// because the point of the graphs are used, after use of the line we have
//to set the link to zero so the nodes will not be destructed by exit of the function
KBoolLink tmp_link(_GC);
tmp_link.Set(First,Second);
KBoolLine tmp_line(_GC);
tmp_line.Set(&tmp_link);
// If third point is on the same line which is made from the first
// and second point then we can delete the second point
if (tmp_line.PointOnLine(this,distance, (double) Marge) == ON_AREA)
{
tmp_link.Set(NULL,NULL);
return true;
}
//
//
tmp_link.Set(Second,this);
tmp_line.Set(&tmp_link);
if (tmp_line.PointOnLine(First,distance, (double) Marge) == ON_AREA)
{
tmp_link.Set(NULL,NULL);
return true;
}
tmp_link.Set(NULL,NULL);
return false;
}
KBoolLink* Node::GetNextLink()
{
int Aantal = _linklist->count();
// assert (Aantal != 0);
// there is one link, so there is no previous link
if (Aantal == 1)
return NULL;
int Marked_Counter = 0;
KBoolLink *the_link = NULL;
// count the marked links
_GC->_linkiter->Attach(_linklist);
_GC->_linkiter->tohead();
while (!_GC->_linkiter->hitroot())
{
if (_GC->_linkiter->item()->IsMarked())
Marked_Counter++;
else
{
if (!the_link)
the_link = _GC->_linkiter->item();
}
(*_GC->_linkiter)++;
}
_GC->_linkiter->Detach();
if (Aantal - Marked_Counter != 1)
// there arent two unmarked links
return NULL;
else
{
if (the_link->GetBeginNode() == this)
return the_link;
else
return NULL;
}
}
KBoolLink* Node::GetPrevLink()
{
int Aantal;
if (!_linklist)
return NULL;
Aantal = _linklist->count();
// assert (Aantal != 0);
// there is one link, so there is no previous link
if (Aantal == 1)
return NULL;
int Marked_Counter = 0;
KBoolLink *the_link = NULL;
_GC->_linkiter->Attach(_linklist);
// count the marked links
_GC->_linkiter->tohead();
while (!_GC->_linkiter->hitroot())
{
if (_GC->_linkiter->item()->IsMarked())
Marked_Counter++;
else
{
if (!the_link)
the_link = _GC->_linkiter->item();
}
(*_GC->_linkiter)++;
}
_GC->_linkiter->Detach();
if (Aantal - Marked_Counter != 1)
// there arent two unmarked links
return NULL;
else
{
if (the_link->GetEndNode() == this)
return the_link;
else
return NULL;
}
}
bool Node::SameSides( KBoolLink* const prev , KBoolLink* const link, BOOL_OP operation )
{
bool directedLeft;
bool directedRight;
if ( prev->GetEndNode() == this ) //forward direction
{
directedLeft = prev->IsMarkedLeft( operation );
directedRight = prev->IsMarkedRight( operation );
if ( link->GetBeginNode() == this ) //forward direction
{
return directedLeft == link->IsMarkedLeft( operation ) &&
directedRight == link->IsMarkedRight( operation );
}
return directedLeft == link->IsMarkedRight( operation ) &&
directedRight == link->IsMarkedLeft( operation );
}
directedLeft = prev->IsMarkedRight( operation );
directedRight = prev->IsMarkedLeft( operation );
if ( link->GetBeginNode() == this ) //forward direction
{
return directedLeft == link->IsMarkedLeft( operation ) &&
directedRight == link->IsMarkedRight( operation );
}
return directedLeft == link->IsMarkedRight( operation ) &&
directedRight == link->IsMarkedLeft( operation );
}
// on the node get the link
// is the most right or left one
// This function is used to collect the simple graphs from a graph
KBoolLink* Node::GetMost( KBoolLink* const prev ,LinkStatus whatside, BOOL_OP operation )
{
KBoolLink *reserve=0;
KBoolLink *Result = NULL,*link;
Node* prevbegin = prev->GetOther(this);
if (_linklist->count() == 2) // only two links to this node take the one != prev
{
if ( (link = (KBoolLink*)_linklist->headitem()) == prev ) //this is NOT the one to go on
link = (KBoolLink*)_linklist->tailitem();
if (!link->BeenHere() && SameSides( prev, link, operation ) )
//we are back where we started (bin is true) return Null
return link;
return(0);
}
_GC->_linkiter->Attach(_linklist);
_GC->_linkiter->tohead();
//more then 2 links to the Node
while(!_GC->_linkiter->hitroot())
{
link = _GC->_linkiter->item();
if ( !link->BeenHere() &&
SameSides( prev, link, operation ) &&
link != prev //should be set to bin already
)
{
if (prevbegin == link->GetOther(this) )//pointers equal
//we are going back in the same direction on a parallel link
//only take this possibility if nothing else is possible
reserve = link;
else
{ //this link is in a different direction
if (!Result)
Result = link; //first one found sofar
else
{
if (prev->PointOnCorner(Result, link) == whatside )
//more to the whatside than take this one
Result = link;
}
}
}
(*_GC->_linkiter)++;
}
// if there is a next link found return it
// else if a parallel link is found return that one
// else return NULL
_GC->_linkiter->Detach();
return ((Result) ? Result : reserve);
}
// on the node get the link
// is the most right or left one
// This function is used to collect the simple graphs from a graph
KBoolLink* Node::GetMostHole( KBoolLink* const prev, LinkStatus whatside, BOOL_OP operation )
{
KBoolLink *reserve=0;
KBoolLink *Result=NULL,*link;
Node* prevbegin = prev->GetOther(this);
if (_linklist->count() == 2) // only two links to this node take the one != prev
{
if ( (link = (KBoolLink*)_linklist->headitem()) == prev ) //this is NOT the one to go on
link = (KBoolLink*)_linklist->tailitem();
if ( link->GetHole() && !link->GetHoleLink() && !link->BeenHere() && SameSides( prev, link, operation ) )
//we are back where we started (bin is true) return Null
return link;
return(0);
}
_GC->_linkiter->Attach(_linklist);
_GC->_linkiter->tohead();
//more then 2 links to the Node
while(!_GC->_linkiter->hitroot())
{
link = _GC->_linkiter->item();
if ( !link->BeenHere() &&
link->GetHole() &&
!link->GetHoleLink() &&
SameSides( prev, link, operation ) &&
link != prev //should be set to bin already
)
{
if (prevbegin == link->GetOther(this) )//pointers equal
//we are going back in the same direction on a parallel link
//only take this possibility if nothing else is possible
reserve = link;
else
{ //this link is in a different direction
if (!Result)
Result = link; //first one found sofar
else
{
if (prev->PointOnCorner(Result, link) == whatside )
//more to the whatside than take this one
Result = link;
}
}
}
(*_GC->_linkiter)++;
}
// if there is a next link found return it
// else if a parallel link is found return that one
// else return NULL
_GC->_linkiter->Detach();
return ((Result) ? Result : reserve);
}
// this function gets the highest not flat link
KBoolLink* Node::GetHoleLink( KBoolLink* const prev, bool checkbin, BOOL_OP operation )
{
KBoolLink *Result=NULL,*link;
_GC->_linkiter->Attach(_linklist);
for(_GC->_linkiter->tohead();!_GC->_linkiter->hitroot();(*_GC->_linkiter)++)
{
link=_GC->_linkiter->item();
if ( link->GetHoleLink() &&
( !checkbin || ( checkbin && !link->BeenHere()) ) &&
SameSides( prev, link, operation )
)
{
Result=link;
break;
}
}
_GC->_linkiter->Detach();
return (Result);
}
// this function gets the highest not flat link
KBoolLink* Node::GetNotFlat()
{
KBoolLink *Result=NULL,*link;
_GC->_linkiter->Attach(_linklist);
double tangold = 0.0;
double tangnew = 0.0;
for(_GC->_linkiter->tohead();!_GC->_linkiter->hitroot();(*_GC->_linkiter)++)
{
link=_GC->_linkiter->item();
if (!_GC->_linkiter->item()->BeenHere())
{
B_INT dx=link->GetOther(this)->GetX()-_x;
B_INT dy=link->GetOther(this)->GetY()-_y;
if (dx!=0)
{
tangnew=fabs( (double) dy / (double) dx );
}
else
{
tangnew=MAXDOUBLE;
}
if (!Result)
{
//this link is in a different direction
Result=link; //first one found sofar
tangold=tangnew;
}
else
{
if(tangnew < tangold)
{
//this one is higher (more horizontal) then the old Result
Result=link;
tangold=tangnew;
}
}
}
}
// if there is a next link found return it
// else if a parallel link is found return that one
// else return NULL
_GC->_linkiter->Detach();
return (Result);
}
// on the node get the link that is not BIN
// and that has the same graphnumber and is in same direction
KBoolLink *Node::Follow(KBoolLink* const prev )
{
KBoolLink *temp;
_GC->_linkiter->Attach(_linklist);
_GC->_linkiter->tohead();
while(!_GC->_linkiter->hitroot())
{
if (( _GC->_linkiter->item() != prev ) &&
( !_GC->_linkiter->item()->BeenHere()) &&
( _GC->_linkiter->item()->GetGraphNum() == prev->GetGraphNum()) &&
(
( (prev->GetEndNode() == this) &&
(_GC->_linkiter->item()->GetEndNode() !=this)
)
||
( (prev->GetBeginNode() == this) &&
(_GC->_linkiter->item()->GetBeginNode() !=this)
)
)
)
{
temp=_GC->_linkiter->item();
_GC->_linkiter->Detach();
return(temp);
}
(*_GC->_linkiter)++;
}
_GC->_linkiter->Detach();
return (0);
}
// this function gets the highest (other node) link ascending from the node
// that has the bin flag set as the argument binset
// if no such link exists return 0
KBoolLink* Node::GetBinHighest(bool binset)
{
KBoolLink *Result=NULL,*link;
_GC->_linkiter->Attach(_linklist);
double tangold = 0.0;
double tangnew = 0.0;
for(_GC->_linkiter->tohead();!_GC->_linkiter->hitroot();(*_GC->_linkiter)++)
{
link=_GC->_linkiter->item();
if (_GC->_linkiter->item()->BeenHere() == binset)
{
B_INT dx=link->GetOther(this)->GetX()-_x;
B_INT dy=link->GetOther(this)->GetY()-_y;
if (dx!=0)
{
tangnew = (double) dy / (double) dx;
}
else if (dy > 0)
{
tangnew = MAXDOUBLE;
}
else
{
tangnew = -MAXDOUBLE;
}
if (!Result)
{
Result = link; //first one found sofar
tangold = tangnew;
}
else
{
if(tangnew > tangold)
{
//this one is higher then the old Result
Result = link;
tangold = tangnew;
}
}
}
}
// if there is a link found return it
// else return NULL
_GC->_linkiter->Detach();
return (Result);
}
/*! \file ../src/record.cpp
\author Probably Klaas Holwerda or Julian Smart
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: record.cpp,v 1.5 2005/05/24 19:13:39 titato Exp $
*/
#ifdef __GNUG__
#pragma implementation
#endif
#include "../include/booleng.h"
#include "../include/record.h"
#include "../include/node.h"
#include <stdlib.h>
#include <math.h>
#define LNK _line.GetLink()
//int r_index=-1;
//void* _Record_Pool[30];
//void DeleteRecordPool()
//{
// while (r_index!=-1)
// {
// free( _Record_Pool[r_index--]);
// }
//}
Record::~Record()
{
}
//void* Record::operator new(size_t size)
//{
//
// if (r_index!=-1)
// {
// return _Record_Pool[r_index--];
// }
//
// return malloc(size);
//}
//void Record::operator delete(void* recordptr)
//{
//
// if (r_index < 28)
// {
// _Record_Pool[++r_index]= recordptr;
// return;
// }
//
// free (recordptr);
//}
//void Record::deletepool()
//{
//
// while (r_index!=-1)
// {
// free( _Record_Pool[r_index--]);
// }
//}
Record::Record(KBoolLink* link,Bool_Engine* GC)
:_line(GC)
{
_GC=GC;
_dir=GO_RIGHT;
_a=0;
_b=0;
_line.Set(link);
_line.CalculateLineParameters();
}
//when the dimensions of a link for a record changes, its line parameters need to be recalculated
void Record::SetNewLink(KBoolLink* link)
{
_line.Set(link);
_line.CalculateLineParameters();
}
//for beams calculate the ysp on the low scanline
void Record::Calc_Ysp(Node* low)
{
if ((LNK->GetEndNode() == low) || (LNK->GetBeginNode() == low))
{
_ysp=low->GetY();
return;
}
if (LNK->GetEndNode()->GetX() == LNK->GetBeginNode()->GetX())
_ysp=low->GetY(); //flatlink only in flatbeams
else if (LNK->GetEndNode()->GetX() == low->GetX())
_ysp=LNK->GetEndNode()->GetY();
else if (LNK->GetBeginNode()->GetX() == low->GetX())
_ysp=LNK->GetBeginNode()->GetY();
else
_ysp=_line.Calculate_Y_from_X(low->GetX());
}
//to set the _dir for new links in the beam
void Record::Set_Flags()
{
if (LNK->GetEndNode()->GetX()==LNK->GetBeginNode()->GetX()) //flatlink ?
{ //only happens in flat beams
if (LNK->GetEndNode()->GetY() < LNK->GetBeginNode()->GetY())
_dir=GO_RIGHT;
else
_dir=GO_LEFT;
}
else
{
if (LNK->GetEndNode()->GetX() > LNK->GetBeginNode()->GetX())
_dir=GO_RIGHT;
else
_dir=GO_LEFT;
}
}
KBoolLink* Record::GetLink()
{
return LNK;
}
B_INT Record::Ysp()
{
return _ysp;
}
void Record::SetYsp(B_INT ysp)
{
_ysp=ysp;
}
DIRECTION Record::Direction()
{
return DIRECTION(_dir);
}
bool Record::Calc_Left_Right(Record* record_above_me)
{
bool par=false;
if (!record_above_me) //null if no record above
{ _a=0;_b=0; }
else
{
_a=record_above_me->_a;
_b=record_above_me->_b;
}
switch (_dir&1)
{
case GO_LEFT : if (LNK->Group() == GROUP_A)
{
LNK->SetRightA((bool)(_a>0));
if (_GC->GetWindingRule())
LNK->GetInc() ? _a++ : _a--;
else
{ //ALTERNATE
if (_a)
_a=0;
else
_a=1;
}
LNK->SetLeftA((bool)(_a>0));
LNK->SetLeftB((bool)(_b>0));
LNK->SetRightB((bool)(_b>0));
}
else
{
LNK->SetRightA((bool)(_a > 0));
LNK->SetLeftA((bool)(_a>0));
LNK->SetRightB((bool)(_b>0));
if (_GC->GetWindingRule())
LNK->GetInc() ? _b++ : _b--;
else //ALTERNATE
{
if (_b)
_b=0;
else
_b=1;
}
LNK->SetLeftB((bool)(_b>0));
}
break;
case GO_RIGHT : if (LNK->Group() == GROUP_A)
{
LNK->SetLeftA((bool)(_a>0));
if (_GC->GetWindingRule())
LNK->GetInc() ? _a++ : _a--;
else
{ //ALTERNATE
if (_a)
_a=0;
else
_a=1;
}
LNK->SetRightA((bool)(_a>0));
LNK->SetLeftB((bool)(_b>0));
LNK->SetRightB((bool)(_b>0));
}
else
{
LNK->SetRightA((bool)(_a>0));
LNK->SetLeftA((bool)(_a>0));
LNK->SetLeftB((bool)(_b>0));
if (_GC->GetWindingRule())
LNK->GetInc() ? _b++ : _b--;
else
{ //ALTERNATE
if (_b)
_b=0;
else
_b=1;
}
LNK->SetRightB((bool)(_b>0));
}
break;
default : _GC->error("Undefined Direction of link","function IScanBeam::Calc_Set_Left_Right()");
break;
}
//THE NEXT WILL WORK for MOST windingrule polygons,
//even when not taking into acount windingrule
// not all
/*
switch (_dir&1)
{
case GO_LEFT : if (LNK->Group() == GROUP_A)
{
LNK->SetRightA((bool)(_a>0));
if (booleng->Get_WindingRule())
LNK->GetInc() ? _a++ : _a--;
else
_a--;
LNK->SetLeftA((bool)(_a>0));
LNK->SetLeftB((bool)(_b>0));
LNK->SetRightB((bool)(_b>0));
}
else
{
LNK->SetRightA((bool)(_a > 0));
LNK->SetLeftA((bool)(_a>0));
LNK->SetRightB((bool)(_b>0));
if (booleng->Get_WindingRule())
LNK->GetInc() ? _b++ : _b--;
else
_b--;
LNK->SetLeftB((bool)(_b>0));
}
break;
case GO_RIGHT : if (LNK->Group() == GROUP_A)
{
LNK->SetLeftA((bool)(_a>0));
if (booleng->Get_WindingRule())
LNK->GetInc() ? _a++ : _a--;
else
_a++;
LNK->SetRightA((bool)(_a>0));
LNK->SetLeftB((bool)(_b>0));
LNK->SetRightB((bool)(_b>0));
}
else
{
LNK->SetRightA((bool)(_a>0));
LNK->SetLeftA((bool)(_a>0));
LNK->SetLeftB((bool)(_b>0));
if (booleng->Get_WindingRule())
LNK->GetInc() ? _b++ : _b--;
else
_b++;
LNK->SetRightB((bool)(_b>0));
}
break;
default : _messagehandler->error("Undefined Direction of link","function IScanBeam::Calc_Set_Left_Right()");
break;
}
*/
//if the records are parallel (same begin/endnodes)
//the above link a/b flag are adjusted to the current a/b depth
if (record_above_me && Equal(record_above_me))
{
par=true;
LNK->Mark();
record_above_me->_a=_a;
record_above_me->_b=_b;
if (Direction()== GO_LEFT)
{
//set the bottom side of the above link
if (record_above_me->Direction()== GO_LEFT)
{
record_above_me->LNK->SetLeftA(LNK->GetLeftA());
record_above_me->LNK->SetLeftB(LNK->GetLeftB());
}
else
{
record_above_me->LNK->SetRightA(LNK->GetLeftA());
record_above_me->LNK->SetRightB(LNK->GetLeftB());
}
}
else
{
//set the bottom side of the above link
if (record_above_me->Direction()== GO_LEFT)
{
record_above_me->LNK->SetLeftA(LNK->GetRightA());
record_above_me->LNK->SetLeftB(LNK->GetRightB());
}
else
{
record_above_me->LNK->SetRightA(LNK->GetRightA());
record_above_me->LNK->SetRightB(LNK->GetRightB());
}
}
}
return par;
}
bool Record::Equal(Record *a)
{
return((bool)( ( LNK->GetOther(a->LNK->GetBeginNode()) == a->LNK->GetEndNode()) &&
( LNK->GetOther(a->LNK->GetEndNode()) == a->LNK->GetBeginNode()) ));
}
KBoolLine* Record::GetLine()
{
return &_line;
}
/*! \file ../src/scanbeam.cpp
\author Probably Klaas Holwerda or Julian Smart
Copyright: 2001-2004 (C) Probably Klaas Holwerda
Licence: wxWidgets Licence
RCS-ID: $Id: scanbeam.cpp,v 1.10 2005/06/17 23:05:18 kbluck Exp $
*/
#ifdef __GNUG__
#pragma implementation
#endif
// class scanbeam
// this class represents de space between two scanlines
#include "../include/scanbeam.h"
#include <math.h>
#include <assert.h>
#include "../include/booleng.h"
#include "../include/graph.h"
#include "../include/node.h"
//this here is to initialize the static iterator of scanbeam
//with NOLIST constructor
int recordsorter(Record* , Record* );
int recordsorter_ysp_angle(Record* , Record* );
int recordsorter_ysp_angle_back(Record* rec1, Record* rec2);
ScanBeam::ScanBeam(Bool_Engine* GC):DL_List<Record*>()
{
_GC = GC;
_type=NORMAL;
_BI.Attach(this);
}
ScanBeam::~ScanBeam()
{
//first delete all record still in the beam
_BI.Detach();
remove_all( true );
//DeleteRecordPool();
}
void ScanBeam::SetType(Node* low,Node* high)
{
if (low->GetX() < high->GetX())
_type=NORMAL;
else
_type=FLAT;
}
/*
//catch node to link crossings
// must be sorted on ysp
int ScanBeam::FindCloseLinksAndCross(TDLI<KBoolLink>* _I,Node* _lowf)
{
int merges = 0;
Record* record;
TDLI<Record> _BBI=TDLI<Record>(this);
if (_BI.count() > 1)
{
//first search a link towards this node
for(_BI.tohead(); !_BI.hitroot(); _BI++)
{
record=_BI.item();
if( (record->GetLink()->GetBeginNode()==_lowf) ||
(record->GetLink()->GetEndNode() ==_lowf)
)
break;
}
//NOTICE if the node "a_node" is not inside a record
//for instance to connected flat links (flatlinks not in beam)
//then IL will be at end (those will be catched at 90 degrees rotation)
if (_BI.hitroot())
{
return(merges);
}
//from IL search back for close links
_BBI.toiter(&_BI);
_BBI--;
while(!_BBI.hitroot())
{
record=_BBI.item();
if (record->Ysp() != _lowf->GetY())
break;
// the distance to the low node is smaller then the MARGE
if( (record->GetLink()->GetBeginNode()!=_lowf) &&
(record->GetLink()->GetEndNode() !=_lowf)
)
{ // the link is not towards the low node
record->GetLink()->AddCrossing(_lowf);
record->SetNewLink(record->GetLink()->ProcessCrossingsSmart(_I));
merges++;
}
_BBI--;
}
//from IL search forward for close links
_BBI.toiter(&_BI);
_BBI++;
while(!_BBI.hitroot())
{
record=_BBI.item();
if (record->Ysp() != _lowf->GetY())
// if (record->Ysp() < _lowf->GetY()-MARGE)
break;
// the distance to the low node is smaller then the MARGE
if( (record->GetLink()->GetBeginNode()!=_lowf) &&
(record->GetLink()->GetEndNode() !=_lowf)
)
{ // the link is not towards the low node
record->GetLink()->AddCrossing(_lowf);
record->SetNewLink(record->GetLink()->ProcessCrossingsSmart(_I));
merges++;
}
_BBI++;
}
}
return merges;
}
*/
/*
bool ScanBeam::Update(TDLI<KBoolLink>* _I,Node* _lowf)
{
bool found=false;
KBoolLink* link;
_BI.tohead();
while (!_BI.hitroot())
{
Record* record=_BI.item();
record->Calc_Ysp(_type,_low);
_BI++;
}
FindCloseLinksAndCross(_I,_lowf);
_BI.tohead();
while (!_BI.hitroot())
{
Record* record=_BI.item();
//records containing links towards the new low node
//are links to be marked for removal
if ((record->GetLink()->GetEndNode() == _lowf) ||
(record->GetLink()->GetBeginNode() == _lowf)
)
{
//cross here the links that meat eachother now
delete _BI.item();
_BI.remove();
//cross here the links that meat eachother now
_BI--;
if (!_BI.hitroot() && (_BI.count() > 1))
{
Record* prev=_BI.item();
_BI++;
if (!_BI.hitroot())
{
if (!_BI.item()->Equal(prev)) // records NOT parallel
if (_BI.item()->GetLine()->Intersect(prev->GetLine(),MARGE))
{
//they did cross, integrate the crossings in the graph
//this may modify the links already part of the record
//this is why they are returned in set for the record
_BI.item()->SetNewLink(_BI.item()->GetLink()->ProcessCrossingsSmart(_I));
prev->SetNewLink(prev->GetLink()->ProcessCrossingsSmart(_I));
}
}
}
else
_BI++;
}
else
_BI++;
}
//writebeam();
//ONLY links towards the low node are possible to be added
//the bin flag will be set if it fits in the beam
//so for following beams it will not be checked again
while ( bool(link=_lowf->GetBinHighest(false)) )
{
Record* record=new Record(link);
// yp_new will always be the y of low node since all new links are
// from this node
record->SetYsp(_lowf->GetY());
record->Set_Flags(_type);
//need to calculate ysn to be able to sort this record in the right order
//this is only used when the insert node is equal for both records
// ins_smart and cross neighbour directly
// if empty then just insert
if (empty())
insend(record);
else
{
// put new item left of the one that is bigger
_BI.tohead();
while(!_BI.hitroot())
{
if (recordsorter_ysp_angle(record,_BI.item())==1)
break;
_BI++;
}
_BI.insbefore(record);
_BI--;_BI--; //just before the new record inserted
if (!_BI.hitroot())
{
Record* prev=_BI.item();
_BI++; //goto the new record inserted
if (!_BI.item()->Equal(prev)) // records NOT parallel
{
if (_BI.item()->GetLine()->Intersect(prev->GetLine(),MARGE))
{
//this may modify the links already part of the record
//this is why they are returned in set for the record
_BI.item()->SetNewLink(_BI.item()->GetLink()->ProcessCrossingsSmart(_I));
prev->SetNewLink(prev->GetLink()->ProcessCrossingsSmart(_I));
}
}
}
else
_BI++;
Record* prev=_BI.item(); //the new record
_BI++;
if (!_BI.hitroot() && !_BI.item()->Equal(prev)) // records NOT parallel
{
Record* cur=_BI.item();
if (cur->GetLine()->Intersect(prev->GetLine(),MARGE))
{
//this may modify the links already part of the record
//this is why they are returned in set for the record
cur->SetNewLink(cur->GetLink()->ProcessCrossingsSmart(_I));
prev->SetNewLink(prev->GetLink()->ProcessCrossingsSmart(_I));
}
}
}
//remember this to calculate in/out values for each new link its polygon again.
GNI->insend(record->GetLink()->GetGraphNum());
found=true;
record->GetLink()->SetBeenHere();
}
FindCloseLinksAndCross(_I,_lowf);
//writebeam();
return(found);
}
*/
bool ScanBeam::FindNew(SCANTYPE scantype,TDLI<KBoolLink>* _I, bool& holes )
{
bool foundnew = false;
_low = _I->item()->GetBeginNode();
KBoolLink* link;
//if (!checksort())
// SortTheBeam();
lastinserted=0;
//ONLY links towards the low node are possible to be added
//the bin flag will be set if it fits in the beam
//so for following beams it will not be checked again
while ( (link = _low->GetBinHighest(false)) != NULL )
{
if ( (link->GetEndNode()->GetX() == link->GetBeginNode()->GetX()) //flatlink in flatbeam
&& ((scantype == NODELINK) || (scantype == LINKLINK) || (scantype == LINKHOLES))
)
{
switch(scantype)
{
case NODELINK:
{
//all vertical links in flatbeam are ignored
//normal link in beam
Record* record=new Record(link,_GC);
// yp_new will always be the y of low node since all new links are
// from this node
record->SetYsp(_low->GetY());
record->Set_Flags();
// put new item left of the one that is lower in the beam
// The last one inserted in this loop, is already left of the current
// iterator position. So the new links are inerted in proper order.
link->SetRecordNode( _BI.insbefore(record) );
_BI--;
foundnew = Process_PointToLink_Crossings() !=0 || foundnew;
delete record;
_BI.remove();
break;
}
case LINKLINK:
//is the new record a flat link
{
KBoolLine flatline = KBoolLine(link, _GC);
foundnew = Process_LinkToLink_Flat(&flatline) || foundnew;
//flatlinks are not part of the beams, still they are used to find new beams
//they can be processed now if the beginnode does not change, since this is used to
//to find new beams. and its position does not change
//ProcessCrossings does take care of this
flatline.ProcessCrossings(_I);
break;
}
case LINKHOLES : //holes are never to flatlinks
assert( true );
default:
break;
}
}
else
{
//normal link in beam
Record* record = new Record(link,_GC);
// yp_new will always be the y of low node since all new links are
// from this node
record->SetYsp(_low->GetY());
record->Set_Flags();
// put new item left of the one that is lower in the beam
// The last one inserted in this loop, is already left of the current
// iterator position. So the new links are inserted in proper order.
link->SetRecordNode( _BI.insbefore(record) );
lastinserted++;
//_GC->Write_Log( "after insert" );
writebeam();
switch(scantype)
{
case NODELINK:
_BI--;
foundnew = Process_PointToLink_Crossings() !=0 || foundnew;
_BI++;
break;
case INOUT:
{
_BI--;
//now we can set the _inc flag
Generate_INOUT(record->GetLink()->GetGraphNum());
_BI++;
}
break;
case GENLR:
{
//now we can set the a/b group flags based on the above link
_BI--;
_BI--;
Record* above=0;
if (!_BI.hitroot())
above=_BI.item();
_BI++;
//something to do for winding rule
if (record->Calc_Left_Right(above))
{
delete record;
_BI.remove();
lastinserted--;
}
else
_BI++;
}
break;
case LINKHOLES:
_BI--;
holes = ProcessHoles(true,_I) || holes;
_BI++;
break;
default:
break;
}
}
link->SetBeenHere();
}
writebeam();
return foundnew;
}
bool ScanBeam::RemoveOld(SCANTYPE scantype,TDLI<KBoolLink>* _I, bool& holes )
{
bool found = false;
bool foundnew = false;
DL_Iter<Record*> _BBI=DL_Iter<Record*>();
bool attached=false;
_low = _I->item()->GetBeginNode();
switch(scantype)
{
case INOUT:
case GENLR:
case LINKHOLES:
if (_type==NORMAL )
{
if (_low->GetBinHighest(true)) //is there something to remove
{
if ( scantype == LINKHOLES )
{
_BI.tohead();
while (!_BI.hitroot())
{
Record* record=_BI.item();
//records containing links towards the new low node
//are links to be removed
if ((record->GetLink()->GetEndNode() == _low) ||
(record->GetLink()->GetBeginNode() == _low)
)
{
holes = ProcessHoles(false,_I) || holes;
}
_BI++;
}
}
_BI.tohead();
while (!_BI.hitroot())
{
Record* record=_BI.item();
//records containing links towards the new low node
//are links to be removed
if ((record->GetLink()->GetEndNode() == _low) ||
(record->GetLink()->GetBeginNode() == _low)
)
{
if (attached) //there is a bug
{
_BBI.Detach();
if (!checksort())
SortTheBeam( true );
_BI.tohead();
attached=false;
}
delete _BI.item();
_BI.remove();
found=true;
}
else if (found) //only once in here
{
attached=true;
found=false;
_BBI.Attach(this);
_BBI.toiter(&_BI); //this is the position new records will be inserted
//recalculate ysp for the new scanline
record->Calc_Ysp(_low);
_BI++;
}
else
{
//recalculate ysp for the new scanline
record->Calc_Ysp(_low);
_BI++;
}
}
if (attached)
{
_BI.toiter(&_BBI);
_BBI.Detach();
}
}
else
{
_BBI.Attach(this);
_BBI.toroot();
_BI.tohead();
while (!_BI.hitroot())
{
Record* record=_BI.item();
record->Calc_Ysp(_low);
if (!found && (record->Ysp() < _low->GetY()))
{
found=true;
_BBI.toiter(&_BI);
}
_BI++;
}
_BI.toiter(&_BBI);
_BBI.Detach();
}
}
else
{ //because the previous beam was flat the links to remove are
//below the last insert position
if (_low->GetBinHighest(true)) //is there something to remove
{
if ( scantype == LINKHOLES )
{
_BI.tohead();
while (!_BI.hitroot())
{
Record* record=_BI.item();
//records containing links towards the new low node
//are links to be removed
if ((record->GetLink()->GetEndNode() == _low) ||
(record->GetLink()->GetBeginNode() == _low)
)
{
holes = ProcessHoles(false,_I) || holes;
}
_BI++;
}
}
//on record back bring us to the last inserted record
//or if nothing was inserted the record before the last deleted record
//if there was no record before the last deleted record this means
//we where at the beginning of the beam, so at root
//_BI << (lastinserted+1);
//_BI--;
//if (_BI.hitroot()) //only possible when at the begin of the beam
_BI.tohead();
while (!_BI.hitroot())
{
Record* record=_BI.item();
//records containing links towards the new low node
//are links to be removed
if ((record->GetLink()->GetEndNode() == _low) ||
(record->GetLink()->GetBeginNode() == _low)
)
{
delete _BI.item();
_BI.remove();
found=true;
}
else if (found) //only once in here
break;
else if (record->Ysp() < _low->GetY())
//if flatlinks are not in the beam nothing will be found
//this will bring us to the right insertion point
break;
else
_BI++;
}
}
else
{
//on record back bring us to the last inserted record
//or if nothing was inserted the record before the last deleted record
//if there was no record before the last deleted record this means
//we where at the beginning of the beam, so at root
//_BI << (lastinserted+ 1);
//_BI--;
//if (_BI.hitroot()) //only possible when at the begin of the beam
_BI.tohead();
while (!_BI.hitroot())
{
Record* record=_BI.item();
if (record->Ysp() < _low->GetY())
break;
_BI++;
}
}
}
break;
case NODELINK:
case LINKLINK:
{
if (_type == NORMAL)
{
Calc_Ysp();
if (scantype==LINKLINK)
foundnew = Process_LinkToLink_Crossings() !=0 || foundnew;
else
SortTheBeam( false );
}
//else beam is already sorted because the added/removed flat links
//do not change the ysp of links already there, new non flat links
//are inserted in order, as result the beam stays sorted
if (_low->GetBinHighest(true)) //is there something to remove
{
_BI.tohead();
while (!_BI.hitroot())
{
Record* record=_BI.item();
//records containing links towards the new low node
//are links to be removed
if ((record->GetLink()->GetEndNode() == _low) ||
(record->GetLink()->GetBeginNode() == _low)
)
{
KBoolLine* line=record->GetLine();
if (scantype==NODELINK)
foundnew = Process_PointToLink_Crossings() !=0 || foundnew;
line->ProcessCrossings(_I);
delete _BI.item();
_BI.remove();
found=true;
}
//because the beam is sorted on ysp, stop when nothing can be there to remove
//and the right insertion point for new links has been found
else if ((record->Ysp() < _low->GetY()))
break;
else
_BI++;
}
}
else
{
_BI.tohead();
while (!_BI.hitroot())
{
Record* record=_BI.item();
//because the beam is sorted on ysp, stop when
//the right insertion point for new links has been found
if ((record->Ysp() < _low->GetY()))
break;
_BI++;
}
}
}
break;
default:
break;
}
return foundnew;
}
/*
bool ScanBeam::RemoveOld(SCANTYPE scantype,TDLI<KBoolLink>* _I, bool& holes )
{
bool found = false;
bool foundnew = false;
DL_Iter<Record*> _BBI=DL_Iter<Record*>();
bool attached=false;
_low = _I->item()->GetBeginNode();
switch(scantype)
{
case INOUT:
case GENLR:
case LINKHOLES:
if (_type==NORMAL )
{
KBoolLink* link = _low->GetBinHighest(true);
if ( link ) //is there something to remove
{
link->SetRecordNode( NULL );
if ( scantype == LINKHOLES )
{
_BI.tohead();
while (!_BI.hitroot())
{
Record* record = _BI.item();
//records containing links towards the new low node
//are links to be removed
if ((record->GetLink()->GetEndNode() == _low) ||
(record->GetLink()->GetBeginNode() == _low)
)
{
holes = ProcessHoles(false,_I) || holes;
}
_BI++;
}
}
_BI.tohead();
while (!_BI.hitroot())
{
Record* record=_BI.item();
//records containing links towards the new low node
//are links to be removed
if ((record->GetLink()->GetEndNode() == _low) ||
(record->GetLink()->GetBeginNode() == _low)
)
{
delete _BI.item();
_BI.remove();
found=true;
}
else if (found) //only once in here
{
attached=true;
found=false;
//recalculate ysp for the new scanline
record->Calc_Ysp(_low);
_BI++;
}
else
{
//recalculate ysp for the new scanline
record->Calc_Ysp(_low);
_BI++;
}
}
}
else
{
_BI.tohead();
while (!_BI.hitroot())
{
Record* record=_BI.item();
record->Calc_Ysp(_low);
_BI++;
}
}
}
else
{ //because the previous beam was flat the links to remove are
//below the last insert position
KBoolLink* link;
link = _low->GetBinHighest(true);
if( link )//is there something to remove
{
link->SetRecordNode( NULL );
bool linkf = false;
_BI.tohead();
while (!_BI.hitroot())
{
Record* record = _BI.item();
if (record->GetLink() == link)
linkf = true;
_BI++;
}
if ( !linkf )
_BI.tohead();
if ( scantype == LINKHOLES )
{
_BI.tohead();
while (!_BI.hitroot())
{
Record* record=_BI.item();
//records containing links towards the new low node
//are links to be removed
if ((record->GetLink()->GetEndNode() == _low) ||
(record->GetLink()->GetBeginNode() == _low)
)
{
holes = ProcessHoles(false,_I) || holes;
}
_BI++;
}
}
//_BI.tonode( link->GetRecordNode() );
//delete _BI.item();
//_BI.remove();
//on record back bring us to the last inserted record
//or if nothing was inserted the record before the last deleted record
//if there was no record before the last deleted record this means
//we where at the beginning of the beam, so at root
//_BI << (lastinserted+1);
//_BI--;
//if (_BI.hitroot()) //only possible when at the begin of the beam
//found=false;
_BI.tohead();
while (!_BI.hitroot())
{
Record* record=_BI.item();
//records containing links towards the new low node
//are links to be removed
if ((record->GetLink()->GetEndNode() == _low) ||
(record->GetLink()->GetBeginNode() == _low)
)
{
if ( link != record->GetLink() )
{
break;
}
if ( link->GetRecordNode() != _BI.node() )
{
delete _BI.item();
_BI.remove();
}
else
{
delete _BI.item();
_BI.remove();
}
found=true;
}
else if (found) //only once in here
break;
else if (record->Ysp() < _low->GetY())
//if flatlinks are not in the beam nothing will be found
//this will bring us to the right insertion point
break;
else
_BI++;
}
}
else
{
//on record back bring us to the last inserted record
//or if nothing was inserted the record before the last deleted record
//if there was no record before the last deleted record this means
//we where at the beginning of the beam, so at root
//_BI << (lastinserted+ 1);
//_BI--;
//if (_BI.hitroot()) //only possible when at the begin of the beam
_BI.tohead();
while (!_BI.hitroot())
{
Record* record=_BI.item();
if (record->Ysp() < _low->GetY())
break;
_BI++;
}
}
}
break;
case NODELINK:
case LINKLINK:
{
if (_type == NORMAL)
{
Calc_Ysp();
if (scantype==LINKLINK)
foundnew = Process_LinkToLink_Crossings() !=0 || foundnew;
else
SortTheBeam( false );
}
//else beam is already sorted because the added/removed flat links
//do not change the ysp of links already there, new non flat links
//are inserted in order, as result the beam stays sorted
if (_low->GetBinHighest(true)) //is there something to remove
{
_BI.tohead();
while (!_BI.hitroot())
{
Record* record=_BI.item();
//records containing links towards the new low node
//are links to be removed
if ((record->GetLink()->GetEndNode() == _low) ||
(record->GetLink()->GetBeginNode() == _low)
)
{
KBoolLine* line=record->GetLine();
if (scantype==NODELINK)
foundnew = Process_PointToLink_Crossings() !=0 || foundnew;
line->ProcessCrossings(_I);
delete _BI.item();
_BI.remove();
found=true;
}
//because the beam is sorted on ysp, stop when nothing can be there to remove
//and the right insertion point for new links has been found
else if ((record->Ysp() < _low->GetY()))
break;
else
_BI++;
}
}
else
{
_BI.tohead();
while (!_BI.hitroot())
{
Record* record=_BI.item();
//because the beam is sorted on ysp, stop when
//the right insertion point for new links has been found
if ((record->Ysp() < _low->GetY()))
break;
_BI++;
}
}
}
break;
default:
break;
}
return foundnew;
}
*/
void ScanBeam::SortTheBeam( bool backangle )
{
if ( backangle )
_BI.mergesort( recordsorter_ysp_angle_back );
else
_BI.mergesort( recordsorter_ysp_angle );
}
void ScanBeam::Calc_Ysp()
{
_BI.tohead();
while (!_BI.hitroot())
{
Record* record=_BI.item();
// KBoolLink* link=_BI.item()->GetLink();
record->Calc_Ysp(_low);
_BI++;
}
}
// this function will set for all the records which contain a link with the
// corresponding graphnumber the inc flag.
// The inc flag's function is to see in a beam if we go deeper in the graph or not
void ScanBeam::Generate_INOUT(int graphnumber)
{
DIRECTION first_dir = GO_LEFT;
int diepte = 0;
DL_Iter<Record*> _BBI = DL_Iter<Record*>();
_BBI.Attach(this);
for( _BBI.tohead(); !_BBI.hitroot(); _BBI++ )
{
// recalculate _inc again
if ( _BBI.item()->GetLink()->GetGraphNum()==graphnumber)
{ //found a link that belongs to the graph
if (diepte==0)
{ // first link found or at depth zero again
// the direction is important since this is used to find out
// if we go further in or out for coming links
first_dir=_BBI.item()->Direction();
_BBI.item()->GetLink()->SetInc(true);
diepte=1;
}
else
{ // according to depth=1 links set depth
// verhoog of verlaag diepte
if (_BBI.item()->Direction() == first_dir)
{
diepte++;
_BBI.item()->GetLink()->SetInc(true);
}
else
{
diepte--;
_BBI.item()->GetLink()->SetInc(false);
}
}
}
if ( _BBI.item() == _BI.item()) break; //not need to do the rest, will come in a later beam
}
_BBI.Detach();
}
// function ProcessHoles
//
// this function will search the closest link to a hole
// step one, search for a link that is marked (this is a hole)
// step two, this is tricky, the closest link is the previous link in
// the beam, but only in the beam that contains the highest node
// from the marked link.
// why ? : if the marked link has for the begin and end node different
// x,y values, see below as link C
// B
// A +---------+
// +----------+
// ___--+
// ___---
// +--- C
//
// when we at first detect link C we would link it to link A, should work he
// but; we always link a hole at its topleft node, so the highest node
// and then we can't link to A but we should link to B
// so when we found the link, we will look if the node that will come
// in a later beam will be higher than the current, if so we will wait
// till that node comes around otherwise we will link this node to the
// closest link (prev in beam)
bool ScanBeam::ProcessHoles( bool atinsert, TDLI<KBoolLink>* _LI )
{
// The scanbeam must already be sorted at this moment
Node *topnode;
bool foundholes = false;
Record* record = _BI.item();
KBoolLink* link = record->GetLink();
if (!record->GetLine()->CrossListEmpty())
{
SortTheBeam( atinsert );
// link the holes in the graph to a link above.
// a the link where the linecrosslist is not empty, means that
// there are links which refer to this link (must be linked to this link)
// make new nodes and links and set them, re-use the old link, so the links
// that still stand in the linecrosslist will not be lost.
// There is a hole that must be linked to this link !
TDLI<Node> I(record->GetLine()->GetCrossList());
I.tohead();
while(!I.hitroot())
{
topnode = I.item();
I.remove();
KBoolLine line(_GC);
line.Set(link);
B_INT Y = line.Calculate_Y(topnode->GetX());
// Now we'll create new nodes and new links to make the link between
// the graphs.
//holes are always linked in a non hole or hole
//for a non hole this link will be to the right
//because non holes are right around
//for holes this will be to the right also,
//because they are left around but the link is always on the
//bottom of the hole
// linkA linkD
// o-------->--------NodeA------->------------o
// | |
// | |
// linkB v ^ linkBB
// | |
// | |
// outgoing* | | incoming*
// o------<---------topnode--------<----------o
//
// all holes are oriented left around
Node * leftnode; //left node of clossest link
(link->GetBeginNode()->GetX() < link->GetEndNode()->GetX()) ?
leftnode = link->GetBeginNode():
leftnode = link->GetEndNode();
Node *node_A = new Node(topnode->GetX(),Y, _GC);
KBoolLink *link_A = new KBoolLink(0, leftnode, node_A, _GC);
KBoolLink *link_B = new KBoolLink(0, node_A, topnode, _GC);
KBoolLink *link_BB = new KBoolLink(0, topnode, node_A, _GC);
KBoolLink *link_D = _BI.item()->GetLink();
link_D->Replace(leftnode,node_A);
_LI->insbegin(link_A);
_LI->insbegin(link_B);
_LI->insbegin(link_BB);
//mark those two segments as hole linking segments
link_B->SetHoleLink(true);
link_BB->SetHoleLink(true);
//is where we come from/link to a hole
bool closest_is_hole = link->GetHole();
// if the polygon linked to, is a hole, this hole here
// just gets bigger, so we take over the links its hole marking.
link_A->SetHole(closest_is_hole);
link_B->SetHole(closest_is_hole);
link_BB->SetHole(closest_is_hole);
// we have only one operation at the time, taking
// over the operation flags is enough, since the linking segments will
// be part of that output for any operation done.
link_A->TakeOverOperationFlags( link );
link_B->TakeOverOperationFlags( link );
link_BB->TakeOverOperationFlags( link );
}
}
if (link->IsTopHole() )
{
SortTheBeam( atinsert );
writebeam();
}
if (link->IsTopHole() && !_BI.athead() )
{
// now we check if this hole should now be linked, or later
// we always link on the node with the maximum y value, Why ? because i like it !
// to link we put the node of the hole into the crosslist of the closest link !
assert( record->Direction() == GO_LEFT );
// he goes to the left
if (atinsert)
{
if ( link->GetBeginNode()->GetY() <= link->GetEndNode()->GetY() )
{
topnode = link->GetEndNode();
//the previous link in the scanbeam == the closest link to the hole in vertical
//direction PUT this node into this link
_BI--;
_BI.item()->GetLine()->AddCrossing(topnode);
_BI++;
//reset tophole flag, hole has been processed
link->SetTopHole(false);
foundholes = true;
}
}
else //remove stage of links from te beam
{
//the tophole link was NOT linked at the insert stage, so it most be linked now
topnode = _BI.item()->GetLink()->GetBeginNode();
//the previous link in the scanbeam == the closest link to the hole in vertical
//direction PUT this node into this link
_BI--;
_BI.item()->GetLine()->AddCrossing(topnode);
_BI++;
//reset mark to flag that this hole has been processed
link->SetTopHole(false);
foundholes = true;
}
}
return foundholes;
}
//sort the records on Ysp if eqaul, sort on tangent at ysp
int recordsorter_ysp_angle(Record* rec1, Record* rec2)
{
if (rec1->Ysp() > rec2->Ysp() )
return(1);
if (rec1->Ysp() < rec2->Ysp() )
return(-1);
//it seems they are equal
B_INT rightY1;
if (rec1->Direction()==GO_LEFT)
rightY1 = rec1->GetLink()->GetBeginNode()->GetY();
else
rightY1 = rec1->GetLink()->GetEndNode()->GetY();
B_INT rightY2;
if (rec2->Direction()==GO_LEFT)
rightY2 = rec2->GetLink()->GetBeginNode()->GetY();
else
rightY2 = rec2->GetLink()->GetEndNode()->GetY();
if ( rightY1 > rightY2 )
return(1);
if ( rightY1 < rightY2 )
return(-1);
return(0);
}
//sort the records on Ysp if eqaul, sort on tangent at ysp
int recordsorter_ysp_angle_back(Record* rec1, Record* rec2)
{
if (rec1->Ysp() > rec2->Ysp() )
return(1);
if (rec1->Ysp() < rec2->Ysp() )
return(-1);
//it seems they are equal
B_INT leftY1;
if ( rec1->Direction() == GO_RIGHT )
leftY1 = rec1->GetLink()->GetBeginNode()->GetY();
else
leftY1 = rec1->GetLink()->GetEndNode()->GetY();
B_INT leftY2;
if ( rec2->Direction() == GO_RIGHT )
leftY2 = rec2->GetLink()->GetBeginNode()->GetY();
else
leftY2 = rec2->GetLink()->GetEndNode()->GetY();
if ( leftY1 > leftY2 )
return(1);
if ( leftY1 < leftY2 )
return(-1);
return(0);
}
// swap functie for cocktailsort ==> each swap means an intersection of links
bool swap_crossing_normal(Record *a, Record *b)
{
if (!a->Equal(b)) // records NOT parallel
{
a->GetLine()->Intersect_simple( b->GetLine() );
return true;
}
return false;
}
int ScanBeam::Process_LinkToLink_Crossings()
{
// sort on y value of next intersection; and find the intersections
return _BI.cocktailsort( recordsorter_ysp_angle_back, swap_crossing_normal );
}
//catch node to link crossings
// must be sorted on ysp
int ScanBeam::Process_PointToLink_Crossings()
{
int merges = 0;
Record* record;
if (_BI.count() > 1)
{
DL_Iter<Record*> IL = DL_Iter<Record*>(this);
IL.toiter(&_BI);
//from IL search back for close links
IL--;
while(!IL.hitroot())
{
record=IL.item();
if (record->Ysp() > _low->GetY()+ _GC->GetInternalMarge())
break;
// the distance to the lo/hi node is smaller then the _GC->GetInternalMarge()
if( (record->GetLink()->GetBeginNode()!= _low) &&
(record->GetLink()->GetEndNode() != _low)
)
{ // the link is not towards the lohi node
record->GetLine()->AddCrossing(_low);
merges++;
}
IL--;
}
//from IL search forward for close links
IL.toiter(&_BI);
IL++;
while(!IL.hitroot())
{
record=IL.item();
if (record->Ysp() < _low->GetY()- _GC->GetInternalMarge())
break;
// the distance to the lohi node is smaller then the booleng->Get_Marge()
if( (record->GetLink()->GetBeginNode()!=_low) &&
(record->GetLink()->GetEndNode() !=_low)
)
{ // the link is not towards the low node
record->GetLine()->AddCrossing(_low);
merges++;
}
IL++;
}
}
return merges;
}
int ScanBeam::Process_LinkToLink_Flat(KBoolLine* flatline)
{
int crossfound = 0;
Record* record;
DL_Iter<Record*> _BBI = DL_Iter<Record*>();
_BBI.Attach(this);
_BBI.toiter(&_BI);
for(_BI.tohead(); !_BI.hitroot(); _BI++)
{
record=_BI.item();
if (record->Ysp() < (flatline->GetLink()->GetLowNode()->GetY() - _GC->GetInternalMarge()))
break;//they are sorted so no other can be there
if ((record->Ysp() > (flatline->GetLink()->GetLowNode()->GetY() - _GC->GetInternalMarge()))
&&
(record->Ysp() < (flatline->GetLink()->GetHighNode()->GetY() + _GC->GetInternalMarge()))
)
{ //it is in between the flat link region
//create a new node at ysp and insert it in both the flatlink and the crossing link
if (
(record->GetLink()->GetEndNode() != flatline->GetLink()->GetHighNode()) &&
(record->GetLink()->GetEndNode() != flatline->GetLink()->GetLowNode() ) &&
(record->GetLink()->GetBeginNode()!= flatline->GetLink()->GetHighNode()) &&
(record->GetLink()->GetBeginNode()!= flatline->GetLink()->GetLowNode() )
)
{
Node *newnode = new Node(_low->GetX(),_BI.item()->Ysp(), _GC);
flatline->AddCrossing(newnode);
record->GetLine()->AddCrossing(newnode);
crossfound++;
}
}
}
_BI.toiter(&_BBI);
_BBI.Detach();
return crossfound;
}
bool ScanBeam::checksort()
{
// if empty then just insert
if (empty())
return true;
// put new item left of the one that is bigger
_BI.tohead();
Record* prev=_BI.item();
_BI++;
while(!_BI.hitroot())
{
Record* curr=_BI.item();
if (recordsorter_ysp_angle(prev,curr)==-1)
{
recordsorter_ysp_angle(prev,curr);
return false;
}
prev=_BI.item();
_BI++;
}
return true;
}
bool ScanBeam::writebeam()
{
#if KBOOL_DEBUG == 1
FILE* file = _GC->GetLogFile();
if (file == NULL)
return true;
fprintf( file, "# beam %d \n", count() );
fprintf( file, " low %I64d %I64d \n", _low->GetX() , _low->GetY() );
fprintf( file, " type %d \n", _type );
if (empty())
{
fprintf( file, " empty \n" );
return true;
}
DL_Iter<Record*> _BI( this );
// put new item left of the one that is bigger
_BI.tohead();
while(!_BI.hitroot())
{
Record* cur=_BI.item();
fprintf( file, " ysp %I64d \n", cur->Ysp() );
KBoolLink* curl=cur->GetLink();
fprintf( file, " linkbegin %I64d %I64d \n", curl->GetBeginNode()->GetX(), curl->GetBeginNode()->GetY() );
fprintf( file, " linkend %I64d %I64d \n", curl->GetEndNode()->GetX(), curl->GetEndNode()->GetY() );
_BI++;
}
#endif
return true;
}
links to software relative to polygons (clipping and and other operations)
used in freePCB (Written by Alan Wright)
gpc (here: GenericPolygonClipperLibrary.cpp)
http://www.cs.man.ac.uk/~toby/alan/software/gpc.html
polygon.php (ported in "C++" by Alan Wright)
the c++ corresponding file is php_polygon.cpp
http://www.phpclasses.org/browse/file/10683.html
used in gpcb:
polygon1.c:
http://www.koders.com/c/
and for this file:
http://www.koders.com/c/fidE26CF2236C2DF7E435D597390A05B982EDFB4C38.aspx
gpcb uses a modified file (integer coordinates)
......@@ -5,16 +5,9 @@ COMMON =
OBJECTS= \
GenericPolygonClipperLibrary.o \
php_polygon.o\
php_polygon_vertex.o\
PolyLine.o\
math_for_graphics.o
GenericPolygonClipperLibrary.o: GenericPolygonClipperLibrary.cpp GenericPolygonClipperLibrary.h
php_polygon.o: php_polygon.cpp php_polygon.h php_polygon_vertex.h defs-macros.h
#polygon1.o: polygon1.cpp polyarea.h vectmatr.h
PolyLine.o: PolyLine.cpp PolyLine.h
math_for_graphics.o: math_for_graphics.cpp math_for_graphics.h
......@@ -10,9 +10,6 @@ using namespace std;
#include "fctsys.h"
#include "defs-macros.h"
#include "PolyLine2Kicad.h"
#include "PolyLine.h"
......@@ -49,7 +46,7 @@ CPoint GetInflectionPoint( CPoint pi, CPoint pf, int mode )
{
int vert; // length of vertical line needed
if( dy > 0 )
vert = dy - abs(dx); // positive
vert = dy - abs(dx); // positive
else
vert = dy + abs(dx); // negative
if( mode == IM_90_45 )
......@@ -75,7 +72,7 @@ CPoint GetInflectionPoint( CPoint pi, CPoint pf, int mode )
{
int hor; // length of horizontal line needed
if( dx > 0 )
hor = dx - abs(dy); // positive
hor = dx - abs(dy); // positive
else
hor = dx + abs(dy); // negative
if( mode == IM_90_45 )
......@@ -93,11 +90,11 @@ CPoint GetInflectionPoint( CPoint pi, CPoint pf, int mode )
return p;
}
//
//
// function to rotate a point clockwise about another point
// currently, angle must be 0, 90, 180 or 270
//
void RotatePoint( CPoint *p, int angle, CPoint org )
void RotatePoint( CPoint *p, int angle, CPoint org )
{
if( angle == 90 )
{
......@@ -204,7 +201,7 @@ int TestLineHit( int xi, int yi, int xf, int yf, int x, int y, double dist )
if( dd<dist && ( (xf>xi && xp<xf && xp>xi) || (xf<xi && xp>xf && xp<xi) ) )
return 1;
}
}
}
return 0; // no hit
}
......@@ -293,16 +290,16 @@ int MakeEllipseFromArc( int xi, int yi, int xf, int yf, int style, EllipseKH * e
// returns number of intersections found (max of 2)
// returns coords of intersections in arrays x[2], y[2]
//
int FindSegmentIntersections( int xi, int yi, int xf, int yf, int style,
int FindSegmentIntersections( int xi, int yi, int xf, int yf, int style,
int xi2, int yi2, int xf2, int yf2, int style2,
double x[], double y[] )
{
double xr[12], yr[12];
int iret = 0;
if( max(xi,xf) < min(xi2,xf2)
|| min(xi,xf) > max(xi2,xf2)
|| max(yi,yf) < min(yi2,yf2)
if( max(xi,xf) < min(xi2,xf2)
|| min(xi,xf) > max(xi2,xf2)
|| max(yi,yf) < min(yi2,yf2)
|| min(yi,yf) > max(yi2,yf2) )
return 0;
......@@ -449,7 +446,7 @@ int FindSegmentIntersections( int xi, int yi, int xf, int yf, int style,
// sets coords of intersections in *x1, *y1, *x2, *y2
// if no intersection, returns min distance in dist
//
int FindLineSegmentIntersection( double a, double b, int xi, int yi, int xf, int yf, int style,
int FindLineSegmentIntersection( double a, double b, int xi, int yi, int xf, int yf, int style,
double * x1, double * y1, double * x2, double * y2,
double * dist )
{
......@@ -505,7 +502,7 @@ int FindLineSegmentIntersection( double a, double b, int xi, int yi, int xf, int
else
{
// oblique line
if( (xx>=xi && xx>xf) || (xx<=xi && xx<xf)
if( (xx>=xi && xx>xf) || (xx<=xi && xx<xf)
|| (yy>yi && yy>yf) || (yy<yi && yy<yf) )
return 0;
}
......@@ -637,7 +634,7 @@ int FindLineSegmentIntersection( double a, double b, int xi, int yi, int xf, int
// if false, returns min. distance in dist (may be 0.0 if parallel)
// and coords on nearest point in one of the segments in (x,y)
//
bool TestForIntersectionOfStraightLineSegments( int x1i, int y1i, int x1f, int y1f,
bool TestForIntersectionOfStraightLineSegments( int x1i, int y1i, int x1f, int y1f,
int x2i, int y2i, int x2f, int y2f,
int * x, int * y, double * d )
{
......@@ -994,14 +991,14 @@ void DrawArc( CDC * pDC, int shape, int xxi, int yyi, int xxf, int yyf, bool bMe
pDC->MoveTo( xxi, yyi );
pDC->LineTo( xxf, yyf );
}
else if( shape == DL_ARC_CCW || shape == DL_ARC_CW )
else if( shape == DL_ARC_CCW || shape == DL_ARC_CW )
{
// set endpoints so we can always draw counter-clockwise arc
if( shape == DL_ARC_CW )
{
xi = xxf;
yi = yyf;
xf = xxi;
xf = xxi;
yf = yyi;
}
else
......@@ -1043,7 +1040,7 @@ void DrawArc( CDC * pDC, int shape, int xxi, int yyi, int xxf, int yyf, bool bMe
int h = -(yf-yi)*2;
if( !bMeta )
pDC->Arc( xf, yi, xf+w, yi-h,
xi, yi, xf, yf );
xi, yi, xf, yf );
else
pDC->Arc( xf, yi-h, xf+w, yi,
xf, yf, xi, yi );
......@@ -1117,7 +1114,7 @@ void GetPadElements( int type, int x, int y, int wid, int len, int radius, int a
}
return;
}
//
//
int h;
int v;
if( angle == 90 || angle == 270 )
......@@ -1251,7 +1248,7 @@ int GetClearanceBetweenSegments( int x1i, int y1i, int x1f, int y1f, int style1,
// both segments are straight lines
int xx, yy;
double dd;
TestForIntersectionOfStraightLineSegments( x1i, y1i, x1f, y1f,
TestForIntersectionOfStraightLineSegments( x1i, y1i, x1f, y1f,
x2i, y2i, x2f, y2f, &xx, &yy, &dd );
int d = max( 0, (int)dd - w1/2 - w2/2 );
if( x )
......@@ -1266,7 +1263,7 @@ int GetClearanceBetweenSegments( int x1i, int y1i, int x1f, int y1f, int style1,
double xr[2];
double yr[2];
test = FindSegmentIntersections( x1i, y1i, x1f, y1f, style1, x2i, y2i, x2f, y2f, style2, xr, yr );
if( test )
if( test )
{
if( x )
*x = (int) xr[0];
......@@ -1341,7 +1338,7 @@ int GetClearanceBetweenSegments( int x1i, int y1i, int x1f, int y1f, int style1,
int nsteps2 = NSTEPS;
double step = (s_start-s_end)/(nsteps-1);
double step2 = (s_start2-s_end2)/(nsteps2-1);
while( (step * max(el1.xrad, el1.yrad)) > 0.1*NM_PER_MIL
while( (step * max(el1.xrad, el1.yrad)) > 0.1*NM_PER_MIL
&& (step2 * len2) > 0.1*NM_PER_MIL )
{
step = (s_start-s_end)/(nsteps-1);
......@@ -1444,7 +1441,7 @@ int GetClearanceBetweenPads( int type1, int x1, int y1, int w1, int l1, int r1,
}
for( int iss=0; iss<nss; iss++ )
{
int d = (int) GetPointToLineSegmentDistance( c[ic].x, c[ic].y,
int d = (int) GetPointToLineSegmentDistance( c[ic].x, c[ic].y,
ss[iss].xi, ss[iss].yi, ss[iss].xf, ss[iss].yf ) - c[ic].r;
dist = min(dist,d);
}
......@@ -1453,7 +1450,7 @@ int GetClearanceBetweenPads( int type1, int x1, int y1, int w1, int l1, int r1,
{
for( int icc=0; icc<ncc; icc++ )
{
int d = (int) GetPointToLineSegmentDistance( cc[icc].x, cc[icc].y,
int d = (int) GetPointToLineSegmentDistance( cc[icc].x, cc[icc].y,
s[is].xi, s[is].yi, s[is].xf, s[is].yf ) - cc[icc].r;
dist = min(dist,d);
}
......@@ -1577,8 +1574,8 @@ double Distance( int x1, int y1, int x2, int y2 )
// this finds approximate solutions
// note: this works best if el2 is smaller than el1
//
int GetArcIntersections( EllipseKH * el1, EllipseKH * el2,
double * x1, double * y1, double * x2, double * y2 )
int GetArcIntersections( EllipseKH * el1, EllipseKH * el2,
double * x1, double * y1, double * x2, double * y2 )
{
if( el1->theta2 > el1->theta1 )
wxASSERT(0);
......@@ -1591,7 +1588,7 @@ int GetArcIntersections( EllipseKH * el1, EllipseKH * el2,
double xscale = 1.0/el1->xrad;
double yscale = 1.0/el1->yrad;
// now transform params of second ellipse into reference frame
// with origin at center if first ellipse,
// with origin at center if first ellipse,
// scaled so the first ellipse is a circle of radius = 1.0
double xo = (el2->Center.X - el1->Center.X)*xscale;
double yo = (el2->Center.Y - el1->Center.Y)*yscale;
......@@ -1657,9 +1654,9 @@ int GetArcIntersections( EllipseKH * el1, EllipseKH * el2,
// this finds approximate solution
//
//double GetSegmentClearance( EllipseKH * el1, EllipseKH * el2,
double GetArcClearance( EllipseKH * el1, EllipseKH * el2,
double * x1, double * y1 )
//double GetSegmentClearance( EllipseKH * el1, EllipseKH * el2,
double GetArcClearance( EllipseKH * el1, EllipseKH * el2,
double * x1, double * y1 )
{
const int NSTEPS = 32;
......@@ -1680,7 +1677,7 @@ double GetArcClearance( EllipseKH * el1, EllipseKH * el2,
int nsteps2 = NSTEPS;
double step = (th_start-th_end)/(nsteps-1);
double step2 = (th_start2-th_end2)/(nsteps2-1);
while( (step * max(el1->xrad, el1->yrad)) > 1.0*NM_PER_MIL
while( (step * max(el1->xrad, el1->yrad)) > 1.0*NM_PER_MIL
&& (step2 * max(el2->xrad, el2->yrad)) > 1.0*NM_PER_MIL )
{
step = (th_start-th_end)/(nsteps-1);
......
// math stuff for graphics, from FreePCB
#ifndef abs
#define abs(x) (((x) >=0) ? (x) : (-(x)))
#endif
typedef struct PointTag
{
double X,Y;
......@@ -11,7 +16,7 @@ typedef struct EllipseTag
// double MaxRad,MinRad; /* major and minor axis */
// double Phi; /* major axis rotation */
double xrad, yrad; // radii on x and y
double theta1, theta2; // start and end angle for arc
double theta1, theta2; // start and end angle for arc
} EllipseKH;
const CPoint zero(0,0);
......@@ -25,7 +30,7 @@ public:
y = yy;
r = rr;
};
int x, y, r;
int x, y, r;
};
class my_rect {
......@@ -38,10 +43,10 @@ public:
ylo = min(yi,yf);
yhi = max(yi,yf);
};
int xlo, ylo, xhi, yhi;
int xlo, ylo, xhi, yhi;
};
class my_seg {
class my_seg {
public:
my_seg(){};
my_seg( int xxi, int yyi, int xxf, int yyf )
......@@ -51,27 +56,27 @@ public:
xf = xxf;
yf = yyf;
};
int xi, yi, xf, yf;
int xi, yi, xf, yf;
};
// math stuff for graphics
#if 0
void DrawArc( CDC * pDC, int shape, int xxi, int yyi, int xxf, int yyf, BOOL bMeta=FALSE );
void DrawArc( CDC * pDC, int shape, int xxi, int yyi, int xxf, int yyf, bool bMeta=FALSE );
#endif
BOOL Quadratic( double a, double b, double c, double *x1, double *x2 );
bool Quadratic( double a, double b, double c, double *x1, double *x2 );
void RotatePoint( CPoint *p, int angle, CPoint org );
void RotateRect( CRect *r, int angle, CPoint org );
int TestLineHit( int xi, int yi, int xf, int yf, int x, int y, double dist );
int FindLineIntersection( double a, double b, double c, double d, double * x, double * y );
int FindLineSegmentIntersection( double a, double b, int xi, int yi, int xf, int yf, int style,
int FindLineSegmentIntersection( double a, double b, int xi, int yi, int xf, int yf, int style,
double * x1, double * y1, double * x2, double * y2, double * dist=NULL );
int FindSegmentIntersections( int xi, int yi, int xf, int yf, int style,
int FindSegmentIntersections( int xi, int yi, int xf, int yf, int style,
int xi2, int yi2, int xf2, int yf2, int style2,
double x[]=NULL, double y[]=NULL );
BOOL FindLineEllipseIntersections( double a, double b, double c, double d, double *x1, double *x2 );
BOOL FindVerticalLineEllipseIntersections( double a, double b, double x, double *y1, double *y2 );
BOOL TestForIntersectionOfStraightLineSegments( int x1i, int y1i, int x1f, int y1f,
bool FindLineEllipseIntersections( double a, double b, double c, double d, double *x1, double *x2 );
bool FindVerticalLineEllipseIntersections( double a, double b, double x, double *y1, double *y2 );
bool TestForIntersectionOfStraightLineSegments( int x1i, int y1i, int x1f, int y1f,
int x2i, int y2i, int x2f, int y2f,
int * x=NULL, int * y=NULL, double * dist=NULL );
void GetPadElements( int type, int x, int y, int wid, int len, int radius, int angle,
......@@ -79,7 +84,7 @@ void GetPadElements( int type, int x, int y, int wid, int len, int radius, int a
int GetClearanceBetweenPads( int type1, int x1, int y1, int w1, int l1, int r1, int angle1,
int type2, int x2, int y2, int w2, int l2, int r2, int angle2 );
int GetClearanceBetweenSegmentAndPad( int x1, int y1, int x2, int y2, int w,
int type, int x, int y, int wid, int len,
int type, int x, int y, int wid, int len,
int radius, int angle );
int GetClearanceBetweenSegments( int x1i, int y1i, int x1f, int y1f, int style1, int w1,
int x2i, int y2i, int x2f, int y2f, int style2, int w2,
......@@ -94,11 +99,11 @@ int GetClearanceBetweenSegments( int x1i, int y1i, int x1f, int y1f, int style1,
double GetPointToLineSegmentDistance( int x, int y, int xi, int yi, int xf, int yf );
double GetPointToLineDistance( double a, double b, int x, int y, double * xp=NULL, double * yp=NULL );
BOOL InRange( double x, double xi, double xf );
bool InRange( double x, double xi, double xf );
double Distance( int x1, int y1, int x2, int y2 );
int GetArcIntersections( EllipseKH * el1, EllipseKH * el2,
double * x1=NULL, double * y1=NULL,
double * x2=NULL, double * y2=NULL );
int GetArcIntersections( EllipseKH * el1, EllipseKH * el2,
double * x1=NULL, double * y1=NULL,
double * x2=NULL, double * y2=NULL );
CPoint GetInflectionPoint( CPoint pi, CPoint pf, int mode );
// quicksort (2-way or 3-way)
......
// file php_polygon.cpp
// This is a port of a php class written by Brenor Brophy (see below)
/*------------------------------------------------------------------------------
** File: polygon.php
** Description: PHP class for a polygon.
** Version: 1.1
** Author: Brenor Brophy
** Email: brenor at sbcglobal dot net
** Homepage: www.brenorbrophy.com
**------------------------------------------------------------------------------
** COPYRIGHT (c) 2005 BRENOR BROPHY
**
** The source code included in this package is free software; you can
** redistribute it and/or modify it under the terms of the GNU General Public
** License as published by the Free Software Foundation. This license can be
** read at:
**
** http://www.opensource.org/licenses/gpl-license.php
**
** This program is distributed in the hope that it will be useful, but WITHOUT
** ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
** FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
**------------------------------------------------------------------------------
**
** Based on the paper "Efficient Clipping of Arbitary Polygons" by Gunther
** Greiner (greiner at informatik dot uni-erlangen dot de) and Kai Hormann
** (hormann at informatik dot tu-clausthal dot de), ACM Transactions on Graphics
** 1998;17(2):71-83.
**
** Available at: www.in.tu-clausthal.de/~hormann/papers/clipping.pdf
**
** Another useful site describing the algorithm and with some example
** C code by Ionel Daniel Stroe is at:
**
** http://davis.wpi.edu/~matt/courses/clipping/
**
** The algorithm is extended by Brenor Brophy to allow polygons with
** arcs between vertices.
**
** Rev History
** -----------------------------------------------------------------------------
** 1.0 08/25/2005 Initial Release
** 1.1 09/04/2005 Added Move(), Rotate(), isPolyInside() and bRect() methods.
** Added software license language to header comments
*/
//#include "stdafx.h"
#include <stdio.h>
#include <math.h>
#include "fctsys.h"
#include "php_polygon_vertex.h"
#include "php_polygon.h"
const double PT = 0.99999;
//const double eps = (1.0 - PT)/10.0;
const double eps = 0.0;
polygon::polygon( vertex* first )
{
m_first = first;
m_cnt = 0;
}
polygon::~polygon()
{
while( m_cnt > 1 )
{
vertex* v = getFirst();
del( v->m_nextV );
}
if( m_first )
{
delete m_first;
}
}
vertex* polygon::getFirst()
{
return m_first;
}
polygon* polygon::NextPoly()
{
return m_first->NextPoly();
}
/*
** Add a vertex object to the polygon (vertex is added at the "end" of the list)
** Which because polygons are closed lists means it is added just before the first
** vertex.
*/
void polygon::add( vertex* nv )
{
if( m_cnt == 0 ) // If this is the first vertex in the polygon
{
m_first = nv; // Save a reference to it in the polygon
m_first->setNext( nv ); // Set its pointer to point to itself
m_first->setPrev( nv ); // because it is the only vertex in the list
segment* ps = m_first->Nseg(); // Get ref to the Next segment object
m_first->setPseg( ps ); // and save it as Prev segment as well
}
else // At least one other vertex already exists
{
// p <-> nv <-> n
// ps ns
vertex* n = m_first; // Get a ref to the first vertex in the list
vertex* p = n->Prev(); // Get ref to previous vertex
n->setPrev( nv ); // Add at end of list (just before first)
nv->setNext( n ); // link the new vertex to it
nv->setPrev( p ); // link to the pervious EOL vertex
p->setNext( nv ); // And finally link the previous EOL vertex
// Segments
segment* ns = nv->Nseg(); // Get ref to the new next segment
segment* ps = p->Nseg(); // Get ref to the previous segment
n->setPseg( ns ); // Set new previous seg for m_first
nv->setPseg( ps ); // Set previous seg of the new vertex
}
m_cnt++; // Increment the count of vertices
}
/*
** Create a vertex and then add it to the polygon
*/
void polygon::addv( double x, double y,
double xc, double yc, int d )
{
vertex* nv = new vertex( x, y, xc, yc, d );
add( nv );
}
/*
** Delete a vertex object from the polygon. This is not used by the main algorithm
** but instead is used to clean-up a polygon so that a second boolean operation can
** be performed.
*/
vertex* polygon::del( vertex* v )
{
// p <-> v <-> n Will delete v and ns
// ps ns
vertex* p = v->Prev(); // Get ref to previous vertex
vertex* n = v->Next(); // Get ref to next vertex
p->setNext( n ); // Link previous forward to next
n->setPrev( p ); // Link next back to previous
// Segments
segment* ps = p->Nseg(); // Get ref to previous segment
segment* ns = v->Nseg(); // Get ref to next segment
n->setPseg( ps ); // Link next back to previous segment
delete ns; //AMW
v->m_nSeg = NULL; // AMW
delete v; //AMW
// ns = NULL;
// v = NULL; // Free the memory
m_cnt--; // One less vertex
return n; // Return a ref to the next valid vertex
}
/*
** Reset Polygon - Deletes all intersection vertices. This is used to
** restore a polygon that has been processed by the boolean method
** so that it can be processed again.
*/
void polygon::res()
{
vertex* v = getFirst(); // Get the first vertex
do
{
v = v->Next(); // Get the next vertex in the polygon
while( v->isIntersect() ) // Delete all intersection vertices
v = del( v );
} while( v->id() != m_first->id() );
}
/*
** Copy Polygon - Returns a reference to a new copy of the poly object
** including all its vertices & their segments
*/
polygon* polygon::copy_poly()
{
polygon* n = new polygon; // Create a new instance of this class
vertex* v = getFirst();
do
{
n->addv( v->X(), v->Y(), v->Xc(), v->Yc(), (int) v->d() );
v = v->Next();
} while( v->id() != m_first->id() );
return n;
}
/*
** Insert and Sort a vertex between a specified pair of vertices (start and end)
**
** This function inserts a vertex (most likely an intersection point) between two
** other vertices. These other vertices cannot be intersections (that is they must
** be actual vertices of the original polygon). If there are multiple intersection
** points between the two vertices then the new vertex is inserted based on its
** alpha value.
*/
void polygon::insertSort( vertex* nv, vertex* s, vertex* e )
{
vertex* c = s; // Set current to the starting vertex
// Move current past any intersections
// whose alpha is lower but don't go past
// the end vertex
while( c->id() != e->id() && c->Alpha() < nv->Alpha() )
c = c->Next();
// p <-> nv <-> c
nv->setNext( c ); // Link new vertex forward to curent one
vertex* p = c->Prev(); // Get a link to the previous vertex
nv->setPrev( p ); // Link the new vertex back to the previous one
p->setNext( nv ); // Link previous vertex forward to new vertex
c->setPrev( nv ); // Link current vertex back to the new vertex
// Segments
segment* ps = p->Nseg();
nv->setPseg( ps );
segment* ns = nv->Nseg();
c->setPseg( ns );
m_cnt++; // Just added a new vertex
}
/*
** return the next non intersecting vertex after the one specified
*/
vertex* polygon::nxt( vertex* v )
{
vertex* c = v; // Initialize current vertex
while( c && c->isIntersect() ) // Move until a non-intersection
c = c->Next(); // vertex if found
return c; // return that vertex
}
/*
** Check if any unchecked intersections remain in the polygon. The boolean
** method is complete when all intersections have been checked.
*/
BOOL polygon::unckd_remain()
{
BOOL remain = FALSE;
vertex* v = m_first;
do
{
if( v->isIntersect() && !v->isChecked() )
remain = TRUE; // Set if an unchecked intersection is found
v = v->Next();
} while( v->id() != m_first->id() );
return remain;
}
/*
** Return a ref to the first unchecked intersection point in the polygon.
** If none are found then just the first vertex is returned.
*/
vertex* polygon::first_unckd_intersect()
{
vertex* v = m_first;
do // Do-While
{ // Not yet reached end of the polygon
v = v->Next(); // AND the vertex if NOT an intersection
} // OR it IS an intersection, but has been checked already
while( v->id() != m_first->id() && ( !v->isIntersect() || ( v->isIntersect() && v->isChecked() ) ) );
return v;
}
/*
** Return the distance between two points
*/
double polygon::dist( double x1, double y1, double x2, double y2 )
{
return sqrt( (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) );
}
/*
** Calculate the angle between 2 points, where Xc,Yc is the center of a circle
** and x,y is a point on its circumference. All angles are relative to
** the 3 O'Clock position. Result returned in radians
*/
double polygon::angle( double xc, double yc, double x1, double y1 )
{
double d = dist( xc, yc, x1, y1 ); // calc distance between two points
double a1;
if( asin( (y1 - yc) / d ) >= 0 )
a1 = acos( (x1 - xc) / d );
else
a1 = 2 * PI - acos( (x1 - xc) / d );
return a1;
}
/*
** Return Alpha value for an Arc
**
** X1/Y1 & X2/Y2 are the end points of the arc, Xc/Yc is the center & Xi/Yi
** the intersection point on the arc. d is the direction of the arc
*/
double polygon::aAlpha( double x1, double y1, double x2, double y2,
double xc, double yc, double xi, double yi, double d )
{
double sa = angle( xc, yc, x1, y1 ); // Start Angle
double ea = angle( xc, yc, x2, y2 ); // End Angle
double ia = angle( xc, yc, xi, yi ); // Intersection Angle
double arc, aint;
if( d == 1 ) // Anti-Clockwise
{
arc = ea - sa;
aint = ia - sa;
}
else // Clockwise
{
arc = sa - ea;
aint = sa - ia;
}
if( arc < 0 )
arc += 2 * PI;
if( aint < 0 )
aint += 2 * PI;
double a = aint / arc;
return a;
}
/*
** This function handles the degenerate case where a vertex of one
** polygon lies directly on an edge of the other. This case can
** also occur during the isInside() function, where the search
** line exactly intersects with a vertex. The function works
** by shortening the line by a tiny amount.
*/
void polygon::perturb( vertex* p1, vertex* p2, vertex* q1, vertex* q2,
double aP, double aQ )
{
// if (aP == 0) // Move vertex p1 closer to p2
if( abs( aP ) <= eps ) // Move vertex p1 closer to p2
{
p1->setX( p1->X() + (1 - PT) * ( p2->X() - p1->X() ) );
p1->setY( p1->Y() + (1 - PT) * ( p2->Y() - p1->Y() ) );
}
// else if (aP == 1) // Move vertex p2 closer to p1
else if( abs( 1 - aP ) <= eps ) // Move vertex p2 closer to p1
{
p2->setX( p1->X() + PT * ( p2->X() - p1->X() ) );
p2->setY( p1->Y() + PT * ( p2->Y() - p1->Y() ) );
}
//** else if (aQ == 0) // Move vertex q1 closer to q2
if( abs( aQ ) <= eps ) // Move vertex q1 closer to q2
{
q1->setX( q1->X() + (1 - PT) * ( q2->X() - q1->X() ) );
q1->setY( q1->Y() + (1 - PT) * ( q2->Y() - q1->Y() ) );
}
//** else if (aQ == 1) // Move vertex q2 closer to q1
else if( abs( 1 - aQ ) <= eps ) // Move vertex q2 closer to q1
{
q2->setX( q1->X() + PT * ( q2->X() - q1->X() ) );
q2->setY( q1->Y() + PT * ( q2->Y() - q1->Y() ) );
}
}
/*
** Determine the intersection between two pairs of vertices p1/p2, q1/q2
**
** Either or both of the segments passed to this function could be arcs.
** Thus we must first determine if the intersection is line/line, arc/line
** or arc/arc. Then apply the correct math to calculate the intersection(s).
**
** Line/Line can have 0 (no intersection) or 1 intersection
** Line/Arc and Arc/Arc can have 0, 1 or 2 intersections
**
** The function returns TRUE is any intersections are found
** The number found is returned in n
** The arrays ix[], iy[], alphaP[] & alphaQ[] return the intersection points
** and their associated alpha values.
*/
BOOL polygon::ints( vertex* p1, vertex* p2, vertex* q1, vertex* q2,
int* n, double ix[], double iy[], double alphaP[], double alphaQ[] )
{
BOOL found = FALSE;
*n = 0; // No intersections found yet
int pt = (int) p1->d();
int qt = (int) q1->d(); // Do we have Arcs or Lines?
if( pt == 0 && qt == 0 ) // Is it line/Line ?
{
/* LINE/LINE
** Algorithm from: http://astronomy.swin.edu.au/~pbourke/geometry/lineline2d/
*/
double x1 = p1->X();
double y1 = p1->Y();
double x2 = p2->X();
double y2 = p2->Y();
double x3 = q1->X();
double y3 = q1->Y();
double x4 = q2->X();
double y4 = q2->Y();
double d = ( (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1) );
if( d != 0 )
{ // The lines intersect at a point somewhere
double ua = ( (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3) ) / d;
double ub = ( (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3) ) / d;
// TRACE( " ints: ua = %.17f, ub = %.17f\n", ua, ub );
// The values of $ua and $ub tell us where the intersection occurred.
// A value between 0 and 1 means the intersection occurred within the
// line segment.
// A value less than 0 or greater than 1 means the intersection occurred
// outside the line segment
// A value of exactly 0 or 1 means the intersection occurred right at the
// start or end of the line segment. For our purposes we will consider this
// NOT to be an intersection and we will move the vertex a tiny distance
// away from the intersecting line.
// if( ua == 0 || ua == 1 || ub == 0 || ub == 1 )
if( abs( ua )<=eps || abs( 1.0 - ua )<=eps || abs( ub )<=eps || abs( 1.0 - ub )<=eps )
{
// Degenerate case - vertex touches a line
perturb( p1, p2, q1, q2, ua, ub );
//** for testing, see if we have successfully resolved the degeneracy
{
double tx1 = p1->X();
double ty1 = p1->Y();
double tx2 = p2->X();
double ty2 = p2->Y();
double tx3 = q1->X();
double ty3 = q1->Y();
double tx4 = q2->X();
double ty4 = q2->Y();
double td = ( (ty4 - ty3) * (tx2 - tx1) - (tx4 - tx3) * (ty2 - ty1) );
if( td != 0 )
{
// The lines intersect at a point somewhere
double tua =
( (tx4 - tx3) * (ty1 - ty3) - (ty4 - ty3) * (tx1 - tx3) ) / td;
double tub =
( (tx2 - tx1) * (ty1 - ty3) - (ty2 - ty1) * (tx1 - tx3) ) / td;
if( abs( tua )<=eps || abs( 1.0 - tua )<=eps || abs( tub )<=eps ||
abs( 1.0 - tub )<=eps )
wxASSERT( 0 );
else if( (tua > 0 && tua < 1) && (tub > 0 && tub < 1) )
wxASSERT( 0 );
TRACE(
" perturb:\n new s = (%f,%f) to (%f,%f)\n new c = (%f,%f) to (%f,%f)\n new ua = %.17f, ub = %.17f\n",
tx1,
ty1,
tx2,
ty2,
tx3,
ty3,
tx4,
ty4,
tua,
tub );
}
}
//** end test
found = FALSE;
}
else if( (ua > 0 && ua < 1) && (ub > 0 && ub < 1) )
{
// Intersection occurs on both line segments
double x = x1 + ua * (x2 - x1);
double y = y1 + ua * (y2 - y1);
iy[0] = y;
ix[0] = x;
alphaP[0] = ua;
alphaQ[0] = ub;
*n = 1;
found = TRUE;
}
else
{
// The lines do not intersect
found = FALSE;
}
}
else
{
// The lines do not intersect (they are parallel)
found = FALSE;
}
} // End of find Line/Line intersection
else if( pt != 0 && qt != 0 ) // Is it Arc/Arc?
{
/* ARC/ARC
** Algorithm from: http://astronomy.swin.edu.au/~pbourke/geometry/2circle/
*/
double x0 = p1->Xc();
double y0 = p1->Yc(); // Center of first Arc
double r0 = dist( x0, y0, p1->X(), p1->Y() ); // Calc the radius
double x1 = q1->Xc();
double y1 = q1->Yc(); // Center of second Arc
double r1 = dist( x1, y1, q1->X(), q1->Y() ); // Calc the radius
double dx = x1 - x0; // dx and dy are the vertical and horizontal
double dy = y1 - y0; // distances between the circle centers.
double d = sqrt( (dy * dy) + (dx * dx) ); // Distance between the centers.
if( d > (r0 + r1) ) // Check for solvability.
{ // no solution. circles do not intersect.
found = FALSE;
}
else if( d < abs( r0 - r1 ) )
{ // no solution. one circle inside the other
found = FALSE;
}
else
{
/*
** 'xy2' is the point where the line through the circle intersection
** points crosses the line between the circle centers.
*/
double a = ( (r0 * r0) - (r1 * r1) + (d * d) ) / (2.0 * d); // Calc the distance from xy0 to xy2.
double x2 = x0 + (dx * a / d); // Determine the coordinates of xy2.
double y2 = y0 + (dy * a / d);
if( d == (r0 + r1) ) // Arcs touch at xy2 exactly (unlikely)
{
alphaP[0] = aAlpha( p1->X(), p1->Y(), p2->X(), p2->Y(), x0, y0, x2, y2, pt );
alphaQ[0] = aAlpha( q1->X(), q1->Y(), q2->X(), q2->Y(), x1, y1, x2, y2, qt );
if( (alphaP[0] >0 && alphaP[0] < 1) && (alphaQ[0] >0 && alphaQ[0] < 1) )
{
ix[0] = x2;
iy[0] = y2;
*n = 1; found = TRUE;
}
}
else // Arcs intersect at two points
{
double alP[2], alQ[2];
double h = sqrt( (r0 * r0) - (a * a) ); // Calc the distance from xy2 to either
// of the intersection points.
double rx = -dy * (h / d); // Now determine the offsets of the
double ry = dx * (h / d);
// intersection points from xy2
double x[2], y[2];
x[0] = x2 + rx; x[1] = x2 - rx; // Calc the absolute intersection points.
y[0] = y2 + ry; y[1] = y2 - ry;
alP[0] = aAlpha( p1->X(), p1->Y(), p2->X(), p2->Y(), x0, y0, x[0], y[0], pt );
alQ[0] = aAlpha( q1->X(), q1->Y(), q2->X(), q2->Y(), x1, y1, x[0], y[0], qt );
alP[1] = aAlpha( p1->X(), p1->Y(), p2->X(), p2->Y(), x0, y0, x[1], y[1], pt );
alQ[1] = aAlpha( q1->X(), q1->Y(), q2->X(), q2->Y(), x1, y1, x[1], y[1], qt );
for( int i = 0; i<=1; i++ )
if( (alP[i] >0 && alP[i] < 1) && (alQ[i] >0 && alQ[i] < 1) )
{
ix[*n] = x[i];
iy[*n] = y[i];
alphaP[*n] = alP[i];
alphaQ[*n] = alQ[i];
*n++;
found = TRUE;
}
}
}
} // End of find Arc/Arc intersection
else // It must be Arc/Line
{
/* ARC/LINE
** Algorithm from: http://astronomy.swin.edu.au/~pbourke/geometry/sphereline/
*/
double d, x1, x2, xc, xs, xe;
double y1, y2, yc, ys, ye;
if( pt == 0 ) // Segment p1,p2 is the line
{ // Segment q1,q2 is the arc
x1 = p1->X();
y1 = p1->Y();
x2 = p2->X();
y2 = p2->Y();
xc = q1->Xc();
yc = q1->Yc();
xs = q1->X();
ys = q1->Y();
xe = q2->X();
ye = q2->Y();
d = qt;
}
else // Segment q1,q2 is the line
{
// Segment p1,p2 is the arc
x1 = q1->X(); y1 = q1->Y();
x2 = q2->X(); y2 = q2->Y();
xc = p1->Xc(); yc = p1->Yc();
xs = p1->X(); ys = p1->Y();
xe = p2->X(); ye = p2->Y();
d = pt;
}
double r = dist( xc, yc, xs, ys );
double a = pow( (x2 - x1), 2 ) + pow( (y2 - y1), 2 );
double b = 2 * ( (x2 - x1) * (x1 - xc)
+ (y2 - y1) * (y1 - yc) );
double c = pow( xc, 2 ) + pow( yc, 2 ) +
pow( x1, 2 ) + pow( y1, 2 ) -
2 * ( xc * x1 + yc * y1) - pow( r, 2 );
double i = b * b - 4 * a * c;
if( i < 0.0 ) // no intersection
{
found = FALSE;
}
else if( i == 0.0 ) // one intersection
{
double mu = -b / (2 * a);
double x = x1 + mu * (x2 - x1);
double y = y1 + mu * (y2 - y1);
double al = mu; // Line Alpha
double aa = this->aAlpha( xs, ys, xe, ye, xc, yc, x, y, d ); // Arc Alpha
if( (al >0 && al <1)&&(aa >0 && aa <1) )
{
ix[0] = x; iy[0] = y;
*n = 1;
found = TRUE;
if( pt == 0 )
{
alphaP[0] = al; alphaQ[0] = aa;
}
else
{
alphaP[0] = aa; alphaQ[0] = al;
}
}
}
else if( i > 0.0 ) // two intersections
{
double mu[2], x[2], y[2], al[2], aa[2];
mu[0] = ( -b + sqrt( pow( b, 2 ) - 4 * a * c ) ) / (2 * a); // first intersection
x[0] = x1 + mu[0] * (x2 - x1);
y[0] = y1 + mu[0] * (y2 - y1);
mu[1] = ( -b - sqrt( pow( b, 2 ) - 4 * a * c ) ) / (2 * a); // second intersection
x[1] = x1 + mu[1] * (x2 - x1);
y[1] = y1 + mu[1] * (y2 - y1);
al[0] = mu[0];
aa[0] = aAlpha( xs, ys, xe, ye, xc, yc, x[0], y[0], d );
al[1] = mu[1];
aa[1] = aAlpha( xs, ys, xe, ye, xc, yc, x[1], y[1], d );
for( int i = 0; i<=1; i++ )
if( (al[i] >0 && al[i] < 1) && (aa[i] >0 && aa[i] < 1) )
{
ix[*n] = x[i];
iy[*n] = y[i];
if( pt == 0 )
{
alphaP[*n] = al[i];
alphaQ[*n] = aa[i];
}
else
{
alphaP[*n] = aa[i];
alphaQ[*n] = al[i];
}
*n++;
found = TRUE;
}
}
} // End of find Arc/Line intersection
return found;
} // end of intersect function
/*
** Test if a vertex lies inside the polygon
**
** This function calculates the "winding" number for the point. This number
** represents the number of times a ray emitted from the point to infinity
** intersects any edge of the polygon. An even winding number means the point
** lies OUTSIDE the polygon, an odd number means it lies INSIDE it.
**
** Right now infinity is set to -10000000, some people might argue that infinity
** actually is a bit bigger. Those people have no lives.
**
** Allan Wright 4/16/2006: I guess I have no life: I had to increase it to -1000000000
*/
BOOL polygon::isInside( vertex* v )
{
//** modified for testing
if( v->isIntersect() )
wxASSERT( 0 );
int winding_number = 0;
int winding_number2 = 0;
int winding_number3 = 0;
int winding_number4 = 0;
//** vertex * point_at_infinity = new vertex(-10000000,v->Y()); // Create point at infinity
/* vertex * point_at_infinity = new vertex(-1000000000,-50000000); // Create point at infinity
* vertex * point_at_infinity2 = new vertex(1000000000,+50000000); // Create point at infinity
* vertex * point_at_infinity3 = new vertex(500000000,1000000000); // Create point at infinity
* vertex * point_at_infinity4 = new vertex(-500000000,1000000000); // Create point at infinity
*/
vertex point_at_infinity( -1000000000, -50000000 ); // Create point at infinity
vertex point_at_infinity2( 1000000000, +50000000 ); // Create point at infinity
vertex point_at_infinity3( 500000000, 1000000000 ); // Create point at infinity
vertex point_at_infinity4( -500000000, 1000000000 ); // Create point at infinity
vertex* q = m_first; // End vertex of a line segment in polygon
do
{
if( !q->isIntersect() )
{
int n;
double x[2], y[2], aP[2], aQ[2];
if( ints( &point_at_infinity, v, q, nxt( q->Next() ), &n, x, y, aP, aQ ) )
winding_number += n; // Add number of intersections found
if( ints( &point_at_infinity2, v, q, nxt( q->Next() ), &n, x, y, aP, aQ ) )
winding_number2 += n; // Add number of intersections found
if( ints( &point_at_infinity3, v, q, nxt( q->Next() ), &n, x, y, aP, aQ ) )
winding_number3 += n; // Add number of intersections found
if( ints( &point_at_infinity4, v, q, nxt( q->Next() ), &n, x, y, aP, aQ ) )
winding_number4 += n; // Add number of intersections found
}
q = q->Next();
} while( q->id() != m_first->id() );
// delete point_at_infinity;
// delete point_at_infinity2;
if( winding_number % 2 != winding_number2 % 2
|| winding_number3 % 2 != winding_number4 % 2
|| winding_number % 2 != winding_number3 % 2 )
wxASSERT( 0 );
if( winding_number % 2 == 0 ) // Check even or odd
return FALSE; // even == outside
else
return TRUE; // odd == inside
}
/*
** Execute a Boolean operation on a polygon
**
** This is the key method. It allows you to AND/OR this polygon with another one
** (equvalent to a UNION or INTERSECT operation. You may also subtract one from
** the other (same as DIFFERENCE). Given two polygons A, B the following operations
** may be performed:
**
** A|B ... A OR B (Union of A and B)
** A&B ... A AND B (Intersection of A and B)
** A\B ... A - B
** B\A ... B - A
**
** A is the object and B is the polygon passed to the method.
*/
polygon* polygon::boolean( polygon* polyB, int oper )
{
polygon* last = NULL;
vertex* s = m_first; // First vertex of the subject polygon
vertex* c = polyB->getFirst(); // First vertex of the "clip" polygon
/*
** Phase 1 of the algoritm is to find all intersection points between the two
** polygons. A new vertex is created for each intersection and it is added to
** the linked lists for both polygons. The "neighbor" reference in each vertex
** stores the link between the same intersection point in each polygon.
*/
TRACE( "boolean...phase 1\n" );
do
{
TRACE( "s=(%f,%f) to (%f,%f) I=%d\n",
s->m_x, s->m_y, s->m_nextV->m_x, s->m_nextV->m_y, s->m_intersect );
if( !s->isIntersect() )
{
do
{
TRACE( " c=(%f,%f) to (%f,%f) I=%d\n",
c->m_x, c->m_y, c->m_nextV->m_x, c->m_nextV->m_y, c->m_intersect );
if( !c->isIntersect() )
{
int n;
double ix[2], iy[2], alphaS[2], alphaC[2];
BOOL bInt = ints( s, nxt( s->Next() ), c, polyB->nxt(
c->Next() ), &n, ix, iy, alphaS, alphaC );
if( bInt )
{
TRACE( " int at (%f,%f) aS = %.17f, aC = %.17f\n",
ix[0],
iy[0],
alphaS[0],
alphaC[0] );
for( int i = 0; i<n; i++ )
{
vertex* is = new vertex( ix[i], iy[i], s->Xc(), s->Yc(),
s->d(), NULL, NULL, NULL, TRUE, NULL, alphaS[i], FALSE, FALSE );
vertex* ic = new vertex( ix[i], iy[i], c->Xc(), c->Yc(),
c->d(), NULL, NULL, NULL, TRUE, NULL, alphaC[i], FALSE, FALSE );
is->setNeighbor( ic );
ic->setNeighbor( is );
insertSort( is, s, this->nxt( s->Next() ) );
polyB->insertSort( ic, c, polyB->nxt( c->Next() ) );
}
}
} // end if c is not an intersect point
c = c->Next();
} while( c->id() != polyB->m_first->id() );
} // end if s not an intersect point
s = s->Next();
} while( s->id() != m_first->id() );
//** for testing...check number of intersections in each poly
TRACE( "boolean...phase 1 testing\n" );
int n_ints = 0;
s = m_first;
do
{
if( s->isIntersect() )
n_ints++;
s = s->Next();
} while( s->id() != m_first->id() );
int n_polyB_ints = 0;
s = polyB->m_first;
do
{
if( s->isIntersect() )
n_polyB_ints++;
s = s->Next();
} while( s->id() != polyB->m_first->id() );
if( n_ints != n_polyB_ints )
wxASSERT( 0 );
if( n_ints % 2 != 0 )
wxASSERT( 0 );
//** end test
/*
** Phase 2 of the algorithm is to identify every intersection point as an
** entry or exit point to the other polygon. This will set the entry bits
** in each vertex object.
**
** What is really stored in the entry record for each intersection is the
** direction the algorithm should take when it arrives at that entry point.
** Depending in the operation requested (A&B, A|B, A/B, B/A) the direction is
** set as follows for entry points (f=foreward, b=Back), exit points are always set
** to the opposite:
** Enter Exit
** A B A B
** A|B b b f f
** A&B f f b b
** A\B b f f b
** B\A f b b f
**
** f = TRUE, b = FALSE when stored in the entry record
*/
TRACE( "boolean...phase 2\n" );
BOOL A, B;
switch( oper )
{
case A_OR_B:
A = FALSE; B = FALSE; break;
case A_AND_B:
A = TRUE; B = TRUE; break;
case A_MINUS_B:
A = FALSE; B = TRUE; break;
case B_MINUS_A:
A = TRUE; B = FALSE; break;
default:
A = TRUE; B = TRUE; break;
}
s = m_first;
//** testing
if( s->isIntersect() )
wxASSERT( 0 );
//** end test
BOOL entry;
if( polyB->isInside( s ) ) // if we are already inside
entry = !A; // next intersection must be an exit
else // otherwise
entry = A; // next intersection must be an entry
do
{
if( s->isIntersect() )
{
s->setEntry( entry );
entry = !entry;
}
s = s->Next();
} while( s->id() != m_first->id() );
/*
** Repeat for other polygon
*/
c = polyB->m_first;
if( this->isInside( c ) ) // if we are already inside
entry = !B; // next intersection must be an exit
else // otherwise
entry = B; // next intersection must be an entry
do
{
if( c->isIntersect() )
{
c->setEntry( entry );
entry = !entry;
}
c = c->Next();
} while( c->id() != polyB->m_first->id() );
/*
** Phase 3 of the algorithm is to scan the linked lists of the
** two input polygons an construct a linked list of result
** polygons. We start at the first intersection then depending
** on whether it is an entry or exit point we continue building
** our result polygon by following the source or clip polygon
** either forwards or backwards.
*/
TRACE( "boolean...phase 3\n" );
while( this->unckd_remain() ) // Loop while unchecked intersections remain
{
vertex* v = first_unckd_intersect(); // Get the first unchecked intersect point
polygon* r = new polygon; // Create a new instance of that class
do
{
v->setChecked(); // Set checked flag true for this intersection
if( v->isEntry() )
{
do
{
v = v->Next();
vertex* nv = new vertex( v->X(), v->Y(), v->Xc(), v->Yc(), v->d() );
r->add( nv );
} while( !v->isIntersect() );
}
else
{
do
{
v = v->Prev();
vertex* nv =
new vertex( v->X(), v->Y(), v->Xc( FALSE ), v->Yc( FALSE ), v->d( FALSE ) );
r->add( nv );
} while( !v->isIntersect() );
}
v = v->Neighbor();
} while( !v->isChecked() ); // until polygon closed
if( last ) // Check in case first time thru the loop
r->m_first->setNextPoly( last ); // Save ref to the last poly in the first vertex
// of this poly
last = r; // Save this polygon
} // end of while there is another intersection to check
/*
** Clean up the input polygons by deleting the intersection points
*/
res();
polyB->res();
/*
** It is possible that no intersection between the polygons was found and
** there is no result to return. In this case we make function fail
** gracefully as follows (depending on the requested operation):
**
** A|B : Return this with polyB in m_first->nextPoly
** A&B : Return this
** A\B : Return this
** B\A : return polyB
*/
polygon* p;
if( !last )
{
TRACE( "boolean...end with no intersection\n" );
switch( oper )
{
case A_OR_B:
last = copy_poly();
p = polyB->copy_poly();
last->m_first->setNextPoly( p );
break;
case A_AND_B:
last = copy_poly();
break;
case A_MINUS_B:
last = copy_poly();
break;
case B_MINUS_A:
last = polyB->copy_poly();
break;
default:
last = copy_poly();
break;
}
}
else if( m_first->m_nextPoly )
{
TRACE( "boolean...end with nextPoly\n" );
last->m_first->m_nextPoly = m_first->NextPoly();
}
vertex * curr_vertex = last->getFirst();
for( int ii = 0; ii < last->m_cnt; ii++ )
{
int x = (int) curr_vertex->X();
int y = (int) curr_vertex->Y();
TRACE( "point %d @ %.4f %.4f\n", ii, (float)x/10000, (float)y/10000 );
curr_vertex = curr_vertex->Next();
}
return last;
} // end of boolean function
/*
** Test if a polygon lies entirly inside this polygon
**
** First every point in the polygon is tested to determine if it is
** inside this polygon. If all points are inside, then the second
** test is performed that looks for any intersections between the
** two polygons. If no intersections are found then the polygon
** must be completely enclosed by this polygon.
*/
#if 0
function polygon::isPolyInside( p )
{
inside = TRUE;
c = p->getFirst(); // Get the first vertex in polygon p
do
{
if( !this->isInside( c ) ) // If vertex is NOT inside this polygon
inside = FALSE; // then set flag to false
c = c->Next(); // Get the next vertex in polygon p
} while( c->id() != p->first->id() );
if( inside )
{
c = p->getFirst(); // Get the first vertex in polygon p
s = getFirst(); // Get the first vertex in this polygon
do
{
do
{
if( this->ints( s, s->Next(), c, c->Next(), n, x, y, aS, aC ) )
inside = FALSE;
c = c->Next();
} while( c->id() != p->first->id() );
s = s->Next();
} while( s->id() != m_first->id() );
}
return inside;
} // end of isPolyInside
/*
** Move Polygon
**
** Translates polygon by delta X and delta Y
*/
function polygon::move( dx, dy )
{
v = getFirst();
do
{
v->setX( v->X() + dx );
v->setY( v->Y() + dy );
if( v->d() != 0 )
{
v->setXc( v->Xc() + dx );
v->setYc( v->Yc() + dy );
}
v = v->Next();
} while( v->id() != m_first->id() );
} // end of move polygon
/*
** Rotate Polygon
**
** Rotates a polgon about point xr/yr by a radians
*/
function polygon::rotate( xr, yr, a )
{
this->move( -xr, -yr ); // Move the polygon so that the point of
// rotation is at the origin (0,0)
if( a < 0 ) // We might be passed a negitive angle
a += 2 * pi(); // make it positive
v = m_first;
do
{
x = v->X(); y = v->Y();
v->setX( x * cos( a ) - y * sin( a ) ); // x' = xCos(a)-ySin(a)
v->setY( x * sin( a ) + y * cos( a ) ); // y' = xSin(a)+yCos(a)
if( v->d() != 0 )
{
x = v->Xc(); y = v->Yc();
v->setXc( x * cos( a ) - y * sin( a ) );
v->setYc( x * sin( a ) + y * cos( a ) );
}
v = v->Next();
} while( v->id() != m_first->id() );
this->move( xr, yr ); // Move the rotated polygon back
} // end of rotate polygon
/*
** Return Bounding Rectangle for a Polygon
**
** returns a polygon object that represents the bounding rectangle
** for this polygon. Arc segments are correctly handled.
*/
function polygon::& bRect()
{
minX = INF; minY = INF; maxX = -INF; maxY = -INF;
v = m_first;
do
{
if( v->d() != 0 ) // Is it an arc segment
{
vn = v->Next(); // end vertex of the arc segment
v1 = new vertex( v->Xc(), -infinity ); // bottom point of vertical line thru arc center
v2 = new vertex( v->Xc(), +infinity ); // top point of vertical line thru arc center
if( this->ints( v, vn, v1, v2, n, x, y, aS, aC ) ) // Does line intersect the arc ?
{
for( i = 0; i<n; i++ ) // check y portion of all intersections
{
minY = min( minY, y[i], v->Y() );
maxY = max( maxY, y[i], v->Y() );
}
}
else // There was no intersection so bounding rect is determined
{
// by the start point only, not teh edge of the arc
minY = min( minY, v->Y() );
maxY = max( maxY, v->Y() );
}
v1 = NULL; v2 = NULL; // Free the memory used
h1 = new vertex( -infinity, v->Yc() ); // left point of horozontal line thru arc center
h2 = new vertex( +infinity, v->Yc() ); // right point of horozontal line thru arc center
if( this->ints( v, vn, h1, h2, n, x, y, aS, aC ) ) // Does line intersect the arc ?
{
for( i = 0; i<n; i++ ) // check x portion of all intersections
{
minX = min( minX, x[i], v->X() );
maxX = max( maxX, x[i], v->X() );
}
}
else
{
minX = min( minX, v->X() );
maxX = max( maxX, v->X() );
}
h1 = NULL; h2 = NULL;
}
else // Straight segment so just check the vertex
{
minX = min( minX, v->X() );
minY = min( minY, v->Y() );
maxX = max( maxX, v->X() );
maxY = max( maxY, v->Y() );
}
v = v->Next();
} while( v->id() != m_first->id() );
//
// Now create an return a polygon with the bounding rectangle
//
this_class = get_class( this ); // Findout the class I'm in (might be an extension of polygon)
p = new this_class; // Create a new instance of that class
p->addv( minX, minY );
p->addv( minX, maxY );
p->addv( maxX, maxY );
p->addv( maxX, minY );
return p;
} // end of bounding rectangle
#endif
// file php_polygon.h
// See comments in php_polygon.cpp
#ifndef PHP_POLYGON_H
#define PHP_POLYGON_H
class vertex;
class segment;
#define infinity 100000000 // for places that are far far away
#define PI 3.14159265359
enum {
A_OR_B,
A_AND_B,
A_MINUS_B,
B_MINUS_A
};
/*------------------------------------------------------------------------------
** This class manages a doubly linked list of vertex objects that represents
** a polygon. The class consists of basic methods to manage the list
** and methods to implement boolean operations between polygon objects.
*/
class polygon
{
public:
vertex* m_first; // Reference to first vertex in the linked list
int m_cnt; // Tracks number of vertices in the polygon
public:
polygon( vertex* first = NULL );
~polygon();
vertex* getFirst();
polygon* NextPoly();
void add( vertex* nv );
void addv( double x, double y,
double xc = 0, double yc = 0, int d = 0 );
vertex* del( vertex* v );
void res();
polygon* copy_poly();
void insertSort( vertex* nv, vertex* s, vertex* e );
vertex* nxt( vertex* v );
BOOL unckd_remain();
vertex* first_unckd_intersect();
double dist( double x1, double y1, double x2, double y2 );
double angle( double xc, double yc, double x1, double y1 );
double aAlpha( double x1, double y1, double x2, double y2,
double xc, double yc, double xi, double yi, double d );
void perturb( vertex* p1, vertex* p2, vertex* q1, vertex* q2,
double aP, double aQ );
BOOL ints( vertex * p1, vertex * p2, vertex * q1, vertex * q2,
int* n, double ix[], double iy[], double alphaP[], double alphaQ[] );
BOOL isInside( vertex* v );
polygon* boolean( polygon* polyB, int oper );
#if 0
function isPolyInside( p );
function move( dx, dy );
function rotate( xr, yr, a );
function& bRect();
#endif
}; //end of class polygon
#endif // ifndef PHP_POLYGON_H
// file php_polygon_vertex.cpp
// This is a port of a php class written by Brenor Brophy (see below)
/*------------------------------------------------------------------------------
** File: vertex.php
** Description: PHP class for a polygon vertex. Used as the base object to
** build a class of polygons.
** Version: 1.1
** Author: Brenor Brophy
** Email: brenor at sbcglobal dot net
** Homepage: www.brenorbrophy.com
**------------------------------------------------------------------------------
** COPYRIGHT (c) 2005 BRENOR BROPHY
**
** The source code included in this package is free software; you can
** redistribute it and/or modify it under the terms of the GNU General Public
** License as published by the Free Software Foundation. This license can be
** read at:
**
** http://www.opensource.org/licenses/gpl-license.php
**
** This program is distributed in the hope that it will be useful, but WITHOUT
** ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
** FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
**------------------------------------------------------------------------------
**
** Based on the paper "Efficient Clipping of Arbitary Polygons" by Gunther
** Greiner (greiner at informatik dot uni-erlangen dot de) and Kai Hormann
** (hormann at informatik dot tu-clausthal dot de), ACM Transactions on Graphics
** 1998;17(2):71-83.
**
** Available at: www.in.tu-clausthal.de/~hormann/papers/clipping.pdf
**
** Another useful site describing the algorithm and with some example
** C code by Ionel Daniel Stroe is at:
**
** http://davis.wpi.edu/~matt/courses/clipping/
**
** The algorithm is extended by Brenor Brophy to allow polygons with
** arcs between vertices.
**
** Rev History
** -----------------------------------------------------------------------------
** 1.0 08/25/2005 Initial Release
** 1.1 09/04/2005 Added software license language to header comments
*/
//#include "stdafx.h"
#include <math.h>
#include "php_polygon_vertex.h"
segment::segment(double xc, double yc, int d )
{
m_xc = xc;
m_yc = yc;
m_d = d;
}
vertex::vertex( double x, double y,
double xc, double yc, double d,
vertex * nextV, vertex * prevV,
polygon * nextPoly,
BOOL intersect,
vertex * neighbor,
double alpha,
BOOL entry,
BOOL checked )
{
m_x = x;
m_y = y;
m_nextV = nextV;
m_prevV = prevV;
m_nextPoly = nextPoly;
m_intersect = intersect;
m_neighbor = neighbor;
m_alpha = alpha;
m_entry = entry;
m_checked = checked;
m_id = 0;
m_nSeg = new segment( xc, yc, (int) d );
m_pSeg = NULL;
}
vertex::~vertex()
{
if( m_nSeg )
delete m_nSeg;
}
double vertex::Xc ( BOOL g )
{
if ( isIntersect() )
{
if ( m_neighbor->isEntry() )
return m_neighbor->m_nSeg->Xc();
else
return m_neighbor->m_pSeg->Xc();
}
else
if (g)
return m_nSeg->Xc();
else
return m_pSeg->Xc();
}
double vertex::Yc ( BOOL g )
{
if ( isIntersect() )
{
if ( m_neighbor->isEntry() )
return m_neighbor->m_nSeg->Yc();
else
return m_neighbor->m_pSeg->Yc();
}
else
if (g)
return m_nSeg->Yc();
else
return m_pSeg->Yc();
}
double vertex::d ( BOOL g )
{
if ( isIntersect() )
{
if ( m_neighbor->isEntry() )
return m_neighbor->m_nSeg->d();
else
return (-1*m_neighbor->m_pSeg->d());
}
else
if (g)
return m_nSeg->d();
else
return (-1*m_pSeg->d());
}
void vertex::setChecked( BOOL check )
{
m_checked = check;
if( m_neighbor )
if( !m_neighbor->isChecked() )
m_neighbor->setChecked();
}
// file php_polygon_vertex.h
// See comments in file php_polygon_vertex.cpp
#ifndef PHP_POLYGON_VERTEX_H
#define PHP_POLYGON_VERTEX_H
#include "defs-macros.h"
class vertex;
class polygon;
class segment
{
public:
segment(double xc=0.0, double yc=0.0, int d=0 );
double Xc(){ return m_xc; };
double Yc(){ return m_yc; };
int d(){ return m_d; };
void setXc( double xc ){ m_xc = xc; };
void setYc( double yc ){ m_yc = yc; };
double m_xc, m_yc; // center of arc
int m_d; // direction (-1=CW, 0=LINE, 1=CCW)
};
class vertex
{
public:
vertex( double x, double y,
double xc=0.0, double yc=0.0, double d=0.0,
vertex * nextV=NULL, vertex * prevV=NULL,
polygon * nextPoly=NULL,
BOOL intersect=FALSE,
vertex * neighbor=NULL,
double alpha=0.0,
BOOL entry=TRUE,
BOOL checked=FALSE );
~vertex();
int id() { return m_id; };
double X() { return m_x; };
void setX( double x ) { m_x = x; };
double Y() { return m_y; };
void setY( double y ) { m_y = y; };
double Xc ( BOOL g = TRUE );
double Yc ( BOOL g = TRUE );
double d ( BOOL g = TRUE );
void setXc ( double xc ) { m_nSeg->setXc(xc); };
void setYc ( double yc ) { m_nSeg->setYc(yc); };
void setNext ( vertex* nextV ){ m_nextV = nextV; };
vertex * Next (){ return m_nextV; };
void setPrev ( vertex *prevV ){ m_prevV = prevV; };
vertex * Prev (){ return m_prevV; };
void setNseg ( segment * nSeg ){ m_nSeg = nSeg; };
segment * Nseg (){ return m_nSeg; };
void setPseg ( segment * pSeg ){ m_pSeg = pSeg; };
segment * Pseg (){ return m_pSeg; };
void setNextPoly ( polygon * nextPoly ){ m_nextPoly = nextPoly; };
polygon * NextPoly (){ return m_nextPoly; };
void setNeighbor ( vertex * neighbor ){ m_neighbor = neighbor; };
vertex * Neighbor (){ return m_neighbor; };
double Alpha (){ return m_alpha; };
BOOL isIntersect (){ return m_intersect; };
void setChecked( BOOL check = TRUE);
BOOL isChecked () { return m_checked; };
void setEntry ( BOOL entry = TRUE){ m_entry = entry; }
BOOL isEntry (){ return m_entry; };
double m_x, m_y; // coords
vertex * m_nextV; // links to next and prev vertices
vertex * m_prevV; // links to next and prev vertices
segment * m_nSeg, * m_pSeg; // links to next and prev segments
polygon * m_nextPoly;
BOOL m_intersect;
vertex * m_neighbor;
double m_alpha;
BOOL m_entry;
BOOL m_checked;
int m_id;
};
#endif // ifndef PHP_POLYGON_VERTEX_H
......@@ -26,9 +26,6 @@ Need to do this using DialogBlocks.
** Switch to a free polygon library.
2008-Feb-8 Assigned To: Jean-Pierre, per his email
asked by: Dick Hollenbeck
================================================================================
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment