1
/***************************************************************************
2
* Copyright (c) 2013 WandererFan <wandererfan (at) gmail.com> *
4
* This file is part of the FreeCAD CAx development system. *
6
* This library is free software; you can redistribute it and/or *
7
* modify it under the terms of the GNU Library General Public *
8
* License as published by the Free Software Foundation; either *
9
* version 2 of the License, or (at your option) any later version. *
11
* This library is distributed in the hope that it will be useful, *
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14
* GNU Library General Public License for more details. *
16
* You should have received a copy of the GNU Library General Public *
17
* License along with this library; see the file COPYING.LIB. If not, *
18
* write to the Free Software Foundation, Inc., 59 Temple Place, *
19
* Suite 330, Boston, MA 02111-1307, USA *
21
***************************************************************************/
22
/***************************************************************************
23
* FreeType License (FTL) credit: *
24
* Portions of this software are copyright (c) <1996-2011> The FreeType *
25
* Project (www.freetype.org). All rights reserved. *
26
***************************************************************************/
28
#include "PreCompiled.h"
40
# include <BRepBuilderAPI_MakeEdge.hxx>
41
# include <BRepBuilderAPI_MakeWire.hxx>
42
# include <BRepBuilderAPI_Transform.hxx>
43
# include <BRepLib.hxx>
44
# include <GCE2d_MakeSegment.hxx>
45
# include <Geom_Plane.hxx>
46
# include <Geom2d_BezierCurve.hxx>
47
# include <Geom2d_BSplineCurve.hxx>
48
# include <Geom2d_TrimmedCurve.hxx>
50
# include <gp_Trsf.hxx>
52
# include <Precision.hxx>
53
# include <ShapeConstruct_Curve.hxx>
54
# include <TColgp_Array1OfPnt2d.hxx>
56
# include <TopoDS_Edge.hxx>
57
# include <TopoDS_Wire.hxx>
60
#include <Base/Console.h>
61
#include <Base/FileInfo.h>
63
#include "TopoShapeWirePy.h"
74
#define ANTICLOCKWISE 1
79
using UNICHAR = unsigned long; // ul is FT2's codepoint type <=> Py_UNICODE2/4
81
// Private function prototypes
82
PyObject* getGlyphContours(FT_Face FTFace, UNICHAR currchar, double PenPos, double Scale,int charNum, double tracking);
83
FT_Vector getKerning(FT_Face FTFace, UNICHAR lc, UNICHAR rc);
84
TopoDS_Wire edgesToWire(std::vector<TopoDS_Edge> Edges);
85
int calcClockDir(std::vector<Base::Vector3d> points);
87
// for compatibility with old version - separate path & filename
88
PyObject* FT2FC(const Py_UNICODE *PyUString,
92
const double stringheight,
93
const double tracking) {
95
std::string tmpPath = FontPath; // can't concat const char*
96
std::string tmpName = FontName;
97
FontSpec = tmpPath + tmpName;
98
return (FT2FC(PyUString,length,FontSpec.c_str(),stringheight,tracking));
101
// get string's wires (contours) in FC/OCC coords
102
PyObject* FT2FC(const Py_UNICODE *PyUString,
104
const char *FontSpec,
105
const double stringheight, // fc coords
106
const double tracking) // fc coords
111
FT_Long FaceIndex = 0; // some fonts have multiple faces
113
FT_UInt FTLoadFlags = FT_LOAD_DEFAULT | FT_LOAD_NO_BITMAP;
115
std::stringstream ErrorMsg;
116
double PenPos = 0, scalefactor;
117
UNICHAR prevchar = 0, currchar = 0;
122
error = FT_Init_FreeType(&FTLib);
124
ErrorMsg << "FT_Init_FreeType failed: " << error;
125
throw std::runtime_error(ErrorMsg.str());
129
std::ifstream fontfile;
131
Base::FileInfo winFI(FontSpec);
132
fontfile.open(winFI.toStdWString().c_str(), std::ios::binary | std::ios::in);
134
fontfile.open(FontSpec, std::ios::binary | std::ios::in);
136
if (!fontfile.is_open()) {
138
ErrorMsg << "Can not open font file: " << FontSpec;
139
throw std::runtime_error(ErrorMsg.str());
141
fontfile.seekg (0, fontfile.end);
142
int bytesNeeded = fontfile.tellg();
144
fontfile.seekg (0, fontfile.beg);
145
std::unique_ptr <char[]> buffer (new char[bytesNeeded]);
146
fontfile.read(buffer.get(), bytesNeeded);
149
ErrorMsg << "Can not read font file: " << FontSpec;
150
throw std::runtime_error(ErrorMsg.str());
154
const FT_Byte* ftBuffer = reinterpret_cast<FT_Byte*>(buffer.get());
155
error = FT_New_Memory_Face(FTLib, ftBuffer, bytesNeeded, FaceIndex, &FTFace);
157
ErrorMsg << "FT_New_Face failed: " << error;
158
throw std::runtime_error(ErrorMsg.str());
161
//TODO: check that FTFace is scalable? only relevant for hinting etc?
163
// FT2 blows up if char size is not set to some non-zero value.
164
// This sets size to 48 point. Magic.
165
error = FT_Set_Char_Size(FTFace,
166
0, /* char_width in 1/64th of points */
167
48*64*10, /* char_height in 1/64th of points */ // increased 10X to preserve very small details
168
0, /* horizontal device resolution */
169
0 ); /* vertical device resolution */
171
ErrorMsg << "FT_Set_Char_Size failed: " << error;
172
throw std::runtime_error(ErrorMsg.str());
175
scalefactor = (stringheight/float(FTFace->height))/10; // divide scale by 10 to offset the 10X increased scale in FT_Set_Char_Size above
176
for (i=0; i<length; i++) {
177
currchar = PyUString[i];
178
error = FT_Load_Char(FTFace,
182
ErrorMsg << "FT_Load_Char failed: " << error;
183
throw std::runtime_error(ErrorMsg.str());
186
cadv = FTFace->glyph->advance.x;
187
kern = getKerning(FTFace,prevchar,currchar);
190
Py::List WireList(getGlyphContours(FTFace, currchar, PenPos, scalefactor, i, tracking), true);
191
CharList.append(WireList);
193
catch (Py::Exception& e) {
195
Base::Console().Log("FT2FC char '0x%04x'/'%d' has no Wires!\n", currchar, currchar);
202
error = FT_Done_FreeType(FTLib);
204
ErrorMsg << "FT_Done_FreeType failed: " << error;
205
throw std::runtime_error(ErrorMsg.str());
208
return Py::new_reference_to(CharList);
211
//********** FT Decompose callbacks and data defns
212
// FT Decomp Context for 1 char
214
std::vector<TopoDS_Wire> Wires;
215
std::vector<int> wDir;
216
std::vector<TopoDS_Edge> Edges;
217
std::vector<Base::Vector3d> polyPoints;
220
Handle(Geom_Surface) surf;
223
// move_cb called for start of new contour. pt is xy of contour start.
224
// p points to the context where we remember what happened previously (last point, etc)
225
static int move_cb(const FT_Vector* pt, void* p) {
226
FTDC_Ctx* dc = static_cast<FTDC_Ctx*>(p);
227
if (!dc->Edges.empty()){
228
TopoDS_Wire newwire = edgesToWire(dc->Edges);
229
dc->Wires.push_back(newwire);
231
dc->wDir.push_back(calcClockDir(dc->polyPoints));
232
dc->polyPoints.clear();
235
if (dc->polyPoints.empty()) {
236
dc->polyPoints.emplace_back(pt->x, pt->y, 0.0);
242
// line_cb called for line segment in the current contour: line(LastVert -- pt)
243
static int line_cb(const FT_Vector* pt, void* p) {
244
FTDC_Ctx* dc = static_cast<FTDC_Ctx*>(p);
245
gp_Pnt2d v1(dc->LastVert.x, dc->LastVert.y);
246
gp_Pnt2d v2(pt->x, pt->y);
247
if (!v1.IsEqual(v2, Precision::Confusion())) {
248
Handle(Geom2d_TrimmedCurve) lseg = GCE2d_MakeSegment(v1,v2);
249
TopoDS_Edge edge = BRepBuilderAPI_MakeEdge(lseg , dc->surf);
250
dc->Edges.push_back(edge);
252
dc->polyPoints.emplace_back(pt->x, pt->y, 0.0);
257
// quad_cb called for quadratic (conic) BCurve segment in the current contour
258
// (ie V-C-V in TTF fonts). BCurve(LastVert -- pt0 -- pt1)
259
static int quad_cb(const FT_Vector* pt0, const FT_Vector* pt1, void* p) {
260
FTDC_Ctx* dc = static_cast<FTDC_Ctx*>(p);
261
TColgp_Array1OfPnt2d Poles(1,3);
262
gp_Pnt2d v1(dc->LastVert.x, dc->LastVert.y);
263
gp_Pnt2d c1(pt0->x, pt0->y);
264
gp_Pnt2d v2(pt1->x, pt1->y);
265
Poles.SetValue(1, v1);
266
Poles.SetValue(2, c1);
267
Poles.SetValue(3, v2);
268
Handle(Geom2d_BezierCurve) bcseg = new Geom2d_BezierCurve(Poles);
270
u = bcseg->FirstParameter();
271
v = bcseg->LastParameter();
272
ShapeConstruct_Curve scc;
273
Handle(Geom2d_BSplineCurve) spline = scc.ConvertToBSpline(bcseg, u, v, Precision::Confusion());
274
if (spline.IsNull()) {
275
Base::Console().Message("Conversion to B-spline failed");
277
TopoDS_Edge edge = BRepBuilderAPI_MakeEdge(spline , dc->surf);
278
dc->Edges.push_back(edge);
280
dc->polyPoints.emplace_back(pt1->x, pt1->y, 0.0);
284
// cubic_cb called for cubic BCurve segment in the current contour (ie V-C-C-V in
285
// Type 1 fonts). BCurve(LastVert -- pt0 -- pt1 -- pt2)
286
static int cubic_cb(const FT_Vector* pt0, const FT_Vector* pt1, const FT_Vector* pt2, void* p) {
287
FTDC_Ctx* dc = static_cast<FTDC_Ctx*>(p);
288
TColgp_Array1OfPnt2d Poles(1,4);
289
gp_Pnt2d v1(dc->LastVert.x, dc->LastVert.y);
290
gp_Pnt2d c1(pt0->x, pt0->y);
291
gp_Pnt2d c2(pt1->x, pt1->y);
292
gp_Pnt2d v2(pt2->x, pt2->y);
293
Poles.SetValue(1, v1);
294
Poles.SetValue(2, c1);
295
Poles.SetValue(3, c2);
296
Poles.SetValue(4, v2);
297
Handle(Geom2d_BezierCurve) bcseg = new Geom2d_BezierCurve(Poles);
299
u = bcseg->FirstParameter();
300
v = bcseg->LastParameter();
301
ShapeConstruct_Curve scc;
302
Handle(Geom2d_BSplineCurve) spline = scc.ConvertToBSpline(bcseg, u, v, Precision::Confusion());
303
if (spline.IsNull()) {
304
Base::Console().Message("Conversion to B-spline failed");
306
TopoDS_Edge edge = BRepBuilderAPI_MakeEdge(spline , dc->surf);
307
dc->Edges.push_back(edge);
309
dc->polyPoints.emplace_back(pt2->x, pt2->y, 0.0);
313
// FT Callbacks structure
314
static FT_Outline_Funcs FTcbFuncs = {
315
(FT_Outline_MoveToFunc)move_cb,
316
(FT_Outline_LineToFunc)line_cb,
317
(FT_Outline_ConicToFunc)quad_cb,
318
(FT_Outline_CubicToFunc)cubic_cb,
319
0, 0 // not needed for FC
322
//********** FT2FC Helpers
323
// get glyph outline in wires
324
PyObject* getGlyphContours(FT_Face FTFace, UNICHAR currchar, double PenPos, double Scale, int charNum, double tracking) {
326
std::stringstream ErrorMsg;
327
gp_Pnt origin = gp_Pnt(0.0,0.0,0.0);
330
ctx.currchar = currchar;
331
ctx.surf = new Geom_Plane(origin,gp::DZ());
333
error = FT_Outline_Decompose(&FTFace->glyph->outline,
337
ErrorMsg << "FT_Decompose failed: " << error;
338
throw std::runtime_error(ErrorMsg.str());
341
// make the last TopoDS_Wire
342
if (!ctx.Edges.empty()){
343
ctx.Wires.push_back(edgesToWire(ctx.Edges));
344
ctx.wDir.push_back(calcClockDir(ctx.polyPoints));
347
//a ttf outer contour is clockwise with material on the right.
348
//an occ outer contour has material on the left, so it must be reversed?
351
FT_Orientation ftOrient = FT_Outline_Get_Orientation(&FTFace->glyph->outline);
353
if (ftOrient == FT_ORIENTATION_TRUETYPE) {
359
gp_Vec pointer = gp_Vec(PenPos * Scale + charNum*tracking,0.0,0.0);
361
xForm.SetScale(origin,Scale);
362
xForm.SetTranslationPart(pointer);
363
BRepBuilderAPI_Transform BRepScale(xForm);
364
bool bCopy = true; // no effect?
368
for(std::vector<TopoDS_Wire>::iterator iWire=ctx.Wires.begin();iWire != ctx.Wires.end(); ++iWire, wCount++) {
369
if ((ctx.wDir[wCount] == CLOCKWISE) && isTTF) { //ttf outer wire. fill inside / right
370
(*iWire).Orientation(TopAbs_REVERSED);
371
} else if ((ctx.wDir[wCount] == CLOCKWISE) && !isTTF) { //ps inner wire. fill outside / right
372
(*iWire).Orientation(TopAbs_REVERSED);
373
} else if ((ctx.wDir[wCount] == ANTICLOCKWISE) && isTTF) { //ttf inner wire. fill outside / left
374
(*iWire).Orientation(TopAbs_REVERSED);
375
} else if ((ctx.wDir[wCount] == ANTICLOCKWISE) && !isTTF) { //ps outer wire. fill inside / left
376
(*iWire).Orientation(TopAbs_REVERSED);
378
//this is likely a poorly constructed font (ex a ttf with outer wires ACW )
379
Base::Console().Message("FT2FC::getGlyphContours - indeterminate wire direction\n");
382
BRepScale.Perform(*iWire,bCopy);
383
if (!BRepScale.IsDone()) {
384
ErrorMsg << "FT2FC OCC BRepScale failed \n";
385
throw std::runtime_error(ErrorMsg.str());
388
PyObject* wire = new TopoShapeWirePy(new TopoShape(TopoDS::Wire(BRepScale.Shape())));
389
list.append(Py::asObject(wire));
391
return Py::new_reference_to(list);
394
// get kerning values for this char pair
395
//TODO: should check FT_HASKERNING flag? returns (0,0) if no kerning?
396
FT_Vector getKerning(FT_Face FTFace, UNICHAR lc, UNICHAR rc) {
399
std::stringstream ErrorMsg;
401
FT_UInt lcx = FT_Get_Char_Index(FTFace, lc);
402
FT_UInt rcx = FT_Get_Char_Index(FTFace, rc);
403
error = FT_Get_Kerning(FTFace,lcx,rcx,FT_KERNING_DEFAULT,&ftKern);
405
ErrorMsg << "FT_Get_Kerning failed: " << error;
406
throw std::runtime_error(ErrorMsg.str());
413
// Make a TopoDS_Wire from a list of TopoDS_Edges
414
TopoDS_Wire edgesToWire(std::vector<TopoDS_Edge> Edges) {
416
std::vector<TopoDS_Edge>::iterator iEdge;
417
BRepBuilderAPI_MakeWire mkWire;
418
for (iEdge = Edges.begin(); iEdge != Edges.end(); ++iEdge){
420
if (!mkWire.IsDone()) {
421
Base::Console().Message("FT2FC Trace edgesToWire failed to add wire\n");
424
occwire = mkWire.Wire();
425
BRepLib::BuildCurves3d(occwire);
429
//is polygon formed by points clockwise (0) or anticlockwise(1)
430
int calcClockDir(std::vector<Base::Vector3d> points)
432
int result = CLOCKWISE;
433
int stop = points.size() - 1;
436
for ( ; iPoint < stop; iPoint++) {
437
double area = points[iPoint].x * points[iPoint + 1].y -
438
points[iPoint + 1].x * points[iPoint].y;
441
double area = points.back().x * points.front().y -
442
points.front().x * points.back().y;
445
result = ANTICLOCKWISE;
450
#endif //#ifdef FCUseFreeType