Add poly2tri and C++ wrapper for polygon tesselation.

This commit is contained in:
2022-04-19 20:04:08 +02:00
parent 4aa63db8dd
commit a6899a3f7c
9 changed files with 171 additions and 15 deletions

View File

@@ -0,0 +1,11 @@
project(poly2tri-wrapper LANGUAGES CXX)
cmake_minimum_required(VERSION 3.12)
add_subdirectory(../../3rdparty/poly2tri poly2tri)
set(CMAKE_CXX_STANDARD 14)
aux_source_directory("src" WRAPPER_SOURCES)
add_library(${PROJECT_NAME} STATIC ${WRAPPER_SOURCES})
target_link_libraries(${PROJECT_NAME} poly2tri)
target_include_directories(${PROJECT_NAME} PUBLIC "include")

View File

@@ -0,0 +1,16 @@
#ifndef _POLY2TRI_WRAPPER_H_
#define _POLY2TRI_WRAPPER_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <gds-render/gds-utils/gds-types.h>
int tesselator_triangulate_polygon(const struct gds_graphics *gfx, double scale, float **output_vertices, size_t *vertex_count);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* _POLY2TRI_WRAPPER_H_ */

View File

@@ -0,0 +1,58 @@
#include <iostream>
#include <poly2tri/poly2tri.h>
#include <poly2tri-wrapper/poly2tri-wrapper.h>
//#include <gds-render/gds-utils/gds-types.h>
#include <vector>
int tesselator_triangulate_polygon(const struct gds_graphics *gfx, double scale, float** output_vertices, size_t *vertex_count)
{
GList *vertex_iter;
std::vector<p2t::Point*> polyline;
if (gfx->gfx_type != GRAPHIC_POLYGON)
return -1;
for (vertex_iter = gfx->vertices; vertex_iter; vertex_iter = g_list_next(vertex_iter)) {
struct gds_point *gds_pt = (struct gds_point *)vertex_iter->data;
auto pt = new p2t::Point((double)gds_pt->x/scale, (double)gds_pt->y/scale);
polyline.push_back(pt);
}
auto my_cdt = p2t::CDT(polyline);
my_cdt.Triangulate();
auto triangles = my_cdt.GetTriangles();
/* Free the triangles */
for (auto it = triangles.begin(); it != triangles.end(); it++) {
auto triangle = *it;
std::cout << "Triangle: " <<
triangle->GetPoint(0)->x << "|" << triangle->GetPoint(0)->y << ","
<< triangle->GetPoint(1)->x << "|" << triangle->GetPoint(1)->x << ","
<< triangle->GetPoint(2)->x << "|" << triangle->GetPoint(2)->y
<< std::endl;
}
/* Get the amount of triangles */
auto count = triangles.size();
*output_vertices = (float *)malloc(2*sizeof(float)*3*count);
*vertex_count = count * 3;
/* Free the points in the vector */
for (unsigned int i = 0; i < count; i++) {
for (int j = 0; j < 3; j++) {
auto pt = triangles[i]->GetPoint(j);
unsigned int idx = i * 6 + j * 2;
(*output_vertices)[idx] = (float)pt->x;
(*output_vertices)[idx + 1] = (float)pt->y;
}
}
for (auto it = polyline.begin(); it != polyline.end(); it++)
delete *it;
return 0;
}