Compare commits

...

179 Commits
0.1 ... main

Author SHA1 Message Date
f96479c074 [RELEASE] Release v1.0.0 2021-02-16 21:43:00 +01:00
db35b7c75b [DEBUG] update new API of lutin log 2019-05-03 10:18:22 +02:00
38e338d731 [DEV] integrate the new interface of URI and file 2018-09-24 23:26:06 +02:00
e060e381b1 [DEV] update etk null 2018-06-19 22:13:47 +02:00
bf9d5a126a [DEV] update to the new ETK allocator wrapper 2017-10-21 19:05:21 +02:00
eaa443d484 [DEBUG] missing stream include 2017-09-26 15:47:17 +02:00
1e0de1fc98 [DEBUG] continue removing STL 2017-09-17 15:23:44 +02:00
ebdfeb99d8 [DEV] continue removing STL 2017-09-14 00:59:21 +02:00
9ab4c0f7ab [DEBUG] update to the new interface etk 2017-09-12 14:14:06 +02:00
f02b8b47b9 [DEV] remove STL 2017-09-07 23:38:26 +02:00
6d504b31ec [DEV] continue removing STL 2017-08-29 01:24:48 +02:00
8553ffec06 [DEV] continue removing stl 2017-08-28 00:05:16 +02:00
7563abcf5a [DEV] add build extra flags 2017-05-25 12:07:03 +02:00
343f289fe2 [DEV] update new API etk 2017-05-16 21:06:21 +02:00
aca0e071cd Change licence APACHE-2 to MPL-2 ==> force source redistribution and permit static link 2017-01-05 21:28:23 +01:00
edf2c04a07 [DEV] update dev tag version 2016-10-24 22:25:37 +02:00
5706c70a22 [RELEASE] new version 0.7.4 2016-10-24 22:25:37 +02:00
72d38ca064 [CI] update build 2016-10-24 22:25:37 +02:00
80a1cb6351 [DEV] Update new lutin 2.2.0 (no legacy support) 2016-10-04 23:41:29 +02:00
084e538f3c [DEBUG] correct .hpp port + clean libC include 2016-10-02 23:47:52 +02:00
c4d4ae131e [DEV/API] change .h in .hpp 2016-09-30 22:28:36 +02:00
37bf1cc04c [DEV] basic documentation (no sample) 2016-09-13 22:20:58 +02:00
9bd29c9d5d [DEV] update dev tag version 2016-09-12 21:07:12 +02:00
9cb18e6aa9 [RELEASE] create release 0.7.2 2016-09-12 21:06:37 +02:00
ef6306aa97 [DEV] update to future lutin 2.0 2016-09-08 21:35:02 +02:00
bf16c99039 [DEV] update dev tag version 2016-08-30 22:54:08 +02:00
abe3e9b4e8 [RELEASE] create release 0.7.1 2016-08-30 22:54:08 +02:00
007d0d973e [DEBUG] missing moving point in line generation 2016-08-22 22:03:03 +02:00
e97810c216 [DOC] clean file header 2016-08-22 21:58:37 +02:00
ae7ee334d2 [DEBUG] correct line generations 2016-08-22 21:52:37 +02:00
cb9f67b530 [DEV] add todo log 2016-08-21 22:51:00 +02:00
68e67dfde3 [DEV] try to have a line generator 2016-08-21 22:50:29 +02:00
a9297c4cb1 [DEV] update new ememory::SharedPtr 2016-07-15 21:22:11 +02:00
2b3f855485 [DEV] update the change on 'enum' to 'enum class' 2016-04-29 23:16:07 +02:00
864f2939b3 [DEBUG] error when integrate new exml interface 2016-04-19 23:04:11 +02:00
f9c000e603 [DEV] update new exml interface (removing visibility of shared_ptr 2016-04-17 22:42:13 +02:00
67a6da6099 [DEV] use doxygen documentation 2016-03-30 21:40:01 +02:00
13bc8b1b02 [DEV] add todo list 2016-03-14 21:10:55 +01:00
c3044af7ef [DEV] update of external of elog and ethread 2016-03-08 21:29:34 +01:00
74c2fc7364 [DEV] replace 'include guard' with 'pragma once' 2016-02-02 21:18:54 +01:00
4866eddf59 [DEV] Add debug display in converter 2016-01-19 21:47:12 +01:00
045008a3c5 [DEBUG] correct corner case bug 2016-01-19 21:43:43 +01:00
d3a58b2548 [DEBUG] bug when parsing stroke argument and fill argument 2016-01-18 22:13:17 +01:00
bac21ef69a [DEBUG] correct LLVM Cxx dependency 2016-01-08 21:22:33 +01:00
ebf36c924c [CI] Test build on Windows 2016-01-07 21:52:16 +01:00
8a2a23a40e [DEBUG] missing condition build in release 2016-01-07 21:50:54 +01:00
f3e348a52e [DEV] add basic arc 2016-01-06 23:02:48 +01:00
59ad94637d [DEV] add tool to convert svg in bmp 2015-12-30 21:15:06 +01:00
197016453b [DEV] update dev tag version 2015-12-29 22:42:58 +01:00
9b43aff756 [RELEASE] create release 0.7.0 2015-12-29 22:40:22 +01:00
83f0a8128f [DEV] radial gradient correct the non center focal position 2015-12-29 22:37:52 +01:00
dbbd996850 [DEV] add support of radial gradient (partial) 2015-12-21 21:01:20 +01:00
8610d6491b [DEBUG] correct the display error of linear gradient 2015-12-20 21:23:40 +01:00
c613a23825 [DEV] add spread mode and better calculation 2015-12-18 22:31:54 +01:00
063ae69628 [DEV] Change declaration position of the enums 2015-12-18 21:44:34 +01:00
d9f689ebc6 [DEBUG] correct the display of partial axis in lenear gradient 2015-12-18 21:18:22 +01:00
0ecf356a17 [DEBUG] correct the display of visual-test 2015-12-18 21:17:38 +01:00
dcf4b225c5 [DEBUG] change merge color in debug (faster /3 time of generation) 2015-12-18 21:01:24 +01:00
e464194e37 [DEV] add methodologie of gradient 2015-12-18 20:50:24 +01:00
3bba1c8ba4 [DEV] support xlink::href in linear gradient 2015-12-17 21:55:37 +01:00
6b976bb9ea [DEV] first linear gradient OK with the spec 2015-12-17 21:30:55 +01:00
85a35ae71b [DEV] Render gradient really slowly 2015-12-10 21:40:42 +01:00
5f6c4bab85 [DEV] start realviewport for gradient 2015-12-09 22:06:56 +01:00
8415109007 [DEV] change LOG element from SVG to ESVG better adapted with the library 2015-12-09 21:32:44 +01:00
9c5496f857 [DEV] continue integration of gradient 2015-12-09 21:20:31 +01:00
7e67a54e32 [DEV] start think of the gradient rendering ==> very complicated ... 2015-12-08 21:42:30 +01:00
effc33ef14 [DEV] continue dimention integration... 2015-12-07 21:32:20 +01:00
d3162ad4c3 [DEV] add dimention and linear gradient parsing 2015-12-04 23:06:38 +01:00
aa6e69c7e7 [DEV] remove memory leak 2015-12-04 22:03:16 +01:00
c5ae88df8e [DEV] change tag in developement 2015-12-04 21:17:33 +01:00
f4af37493f [RELEASE] create release 0.6.0 2015-12-04 21:15:43 +01:00
93b93ed964 [DEBUG] correct build error 2015-12-03 23:49:55 +01:00
a0266a4ffe [DEV] RM CMakelist 2015-12-03 22:37:42 +01:00
0a5749bd3a [DEV] Add parsing of Id of elements 2015-12-03 22:36:13 +01:00
7bf04979a7 [DEBUG] correct the Border render of the image 2015-12-03 22:25:02 +01:00
cec2736cc9 [DEBUG] correct path end and not ending 2015-12-03 22:10:30 +01:00
462958f749 [DEBUG] correct miter/bevel/rount start cyclic path and some smal bugs 2015-12-03 21:50:44 +01:00
bbe79f971d [CI] reduce log level 2015-12-03 21:21:42 +01:00
b1a2dec4d9 [DEV] update the position of scaling and rotate 2015-12-01 23:26:43 +01:00
c1358b6d1b [DEV] correct scaling 2015-12-01 23:26:43 +01:00
83c8b7ed39 [DEV] start think of the rescaling ... 2015-12-02 22:16:12 +01:00
4496e42c22 [DEV] correct new API 2015-12-02 21:54:55 +01:00
a776582367 [DEV] correct color integration 2015-12-02 21:43:29 +01:00
1b8fb2f3e4 [DEV] correct the color integration 2015-12-01 23:26:43 +01:00
3ebd82c71d [DEBUG] try to corect color merge ... 2015-12-01 23:11:51 +01:00
7037a6980b [DEV] transfert Cross product to etk lib and add missing miterlimit in style 2015-12-01 21:45:55 +01:00
ef8d2a889e [DEV] Create correct join_roind and factorize rounding and add miter-limit 2015-12-01 21:27:52 +01:00
9b7a8a6d5a [DEV] join bevel is now ok (round need to be done) 2015-11-30 21:16:41 +01:00
fe6235a828 [DEV] Start dev of join modifications ... 2015-11-27 23:30:24 +01:00
3105a734ed [DEBUG] correct display bug of ordering segment before weight and reject double point position in a single line 2015-11-27 23:05:30 +01:00
9e5b150ec3 [DEV] add cap of the line with corect display add bug more visible 2015-11-27 22:35:10 +01:00
eca4520384 [DEV] correct the with of the path and the good closing of a path 2015-11-25 21:52:27 +01:00
6925a59c64 [DEBUG] correct curve calculation ... internal error of las curve management 2015-11-25 21:06:18 +01:00
4ccad4aaed [DEV] try to implement curve path models ... (not work at all) and add test assiciated 2015-11-24 22:20:12 +01:00
3ddc118c4c [DEV] set stroke size in the all element 2015-11-24 21:57:03 +01:00
fec137abfb [DEV] add better display of debug in bmp debug file 2015-11-24 21:55:36 +01:00
2b2a567526 [DEV] add polyline test 2015-11-24 21:53:28 +01:00
54d7054358 [DEV] add miter and cap test 2015-11-24 21:52:11 +01:00
aeb8d8e9d9 [DEBUG] Fix segment 'start' and 'stop' positionning 2015-11-24 21:43:26 +01:00
effd46ddd1 [DEBUG] Fix segmentation fault in Weight 2015-11-24 21:41:14 +01:00
332775ae72 [DEV] add line rendering 2015-11-24 21:34:07 +01:00
7a8cd38615 [DEBUG] correct the visual debug of the renderer 2015-11-24 21:16:18 +01:00
2da6e9ee6f [DEBUG] correct the rounded corner of rectangle 2015-11-23 23:03:11 +01:00
ae04bbcdbe [DEV] add generation of polyline 2015-11-23 22:08:22 +01:00
1decd2893c [DEV] add generation of polygon 2015-11-23 22:03:42 +01:00
be10ea356c [DEV] add generation of circle (easy after ellipse) 2015-11-23 21:55:08 +01:00
4b38dfcd5a [DEV] add generation of ellipse 2015-11-23 21:50:18 +01:00
a1f83ee5da [DEV] Add bitmap export with Alpha correct (reverse ingeneer of BMP, do not ask me how it work ...) 2015-11-23 21:26:51 +01:00
85af6d85d0 [DEV] write test svg file to compare 2015-11-21 22:17:38 +01:00
f5d5391884 [DEV] set Opacity working corectly and corect old bug of opacity 2015-11-21 16:34:58 +01:00
1fc98b70c6 [DEV] color integration might be correct ... need test opacity (not coded) and multiple boject addition 2015-11-21 16:09:14 +01:00
5ab659858e [DEV] correct cyclic path and rectangle basic generation... 2015-11-20 22:09:23 +01:00
bbfe108c5b [DEV] multiple add:
- add display debug to faster developpement
    - add multiple line path in the pointing list
    - better integration of conficuration of svg parameter
2015-11-20 21:34:09 +01:00
93d560395f [DEV] add many test and corect some old bugs ... 2015-11-19 22:26:42 +01:00
bed717cae9 [DEV] all basic class and separators are here ... (good job) 2015-11-18 22:23:08 +01:00
9b64e85733 [DEV] change list point generation methode ==> separate files 2015-11-18 22:07:04 +01:00
ea1aa31d49 [DEV] create a real class to store path ... 2015-11-18 21:07:51 +01:00
2f095120dd [DEV] Remove deprecated function 2015-11-17 22:40:03 +01:00
a66e8ff9ff [DEV] REwork methode to be simple 2015-11-17 22:34:12 +01:00
402b29ca36 [DEV] first study of rendering directly 2015-11-17 21:15:40 +01:00
14eea2f916 [DEV] create dev version 2015-11-09 21:55:52 +01:00
31c7df0fb7 [RELEASE] create version 0.5.0 2015-11-09 21:46:02 +01:00
80017782b3 [DEV] update new lutin 0.8.0 2015-10-14 21:21:03 +02:00
49785009fa [DEV] update next lutin version 2015-09-24 21:44:04 +02:00
7d2449b7da [DEV] update Build interface 2015-09-14 21:11:04 +02:00
4f538a72c1 [CI] update travis with new interface (no sudo) 2015-08-24 23:55:27 +02:00
164d8fd171 [DEV] update travis file 2015-06-17 21:25:57 +02:00
6154d1ff94 [CI] No test softaware 2015-05-27 11:08:28 +02:00
654ba5c4b8 [CI] wron binary file 2015-05-21 22:29:03 +02:00
a9de1a1f68 [CI] travis add 2015-05-20 21:29:12 +02:00
9bc5d4dec8 [BUILD] update new lutin 0.5.3 2015-05-08 22:38:09 +02:00
6c65d74094 [DEV] update Log interafce 2015-03-25 21:14:12 +01:00
d61f0b9607 [DEV] update new xml interface 2015-01-14 20:01:05 +01:00
738ee25fb8 [LICENCE] change BSD to Apache 2.0 2014-08-08 23:33:43 +02:00
ac34d1f531 [DEV] remove etk_min and etk_max & color properties 2014-07-03 21:03:26 +02:00
a6c50c8f94 [STYLE] remove (void) in () to be c++ coherent 2014-05-15 21:37:39 +02:00
467a412ccd [DEV] encoding error compilation 2014-05-02 21:29:44 +02:00
95215e438d [DEV] change log system 2014-04-30 22:18:00 +02:00
9229886513 [DEV] cmake file update 2014-03-04 21:18:41 +01:00
eceec1d928 [DEV] add CMake instance 2014-02-24 21:50:50 +01:00
f24b852752 [DOC] add monk website 2013-12-28 16:09:46 +01:00
0579048327 [DEV] update to the etk normalisation 2013-12-28 14:22:08 +01:00
40494649a6 [DEV] update lutin naming 2013-12-23 22:38:46 +01:00
ac50618272 [DEV] add monk documentation 2013-12-22 19:02:20 +01:00
b8b4ea9a46 [DEV] remove doc/doc/ path 2013-12-08 23:16:50 +01:00
6ba58ea5fc [DEV] Add http folder 2013-12-06 21:46:38 +01:00
9fee33207a [DEV] add documentation generation 2013-12-04 23:44:04 +01:00
03efb06322 [DEV] change idea std::u32string to std::string 2013-11-12 21:58:13 +01:00
32b1966f8d [DEV] integarate std x11 2013-11-11 20:19:43 +01:00
7e28d6b250 [DEV] update Debug in debug 2013-10-25 20:48:12 +02:00
ce05b596af [DEV] coding style ended 2013-10-04 21:43:29 +02:00
b80dbfd298 [DEV] start coding style 2013-10-03 23:35:28 +02:00
32c4469c12 [DEV] remove dependency of etk memory system 2013-07-26 09:11:36 +02:00
51c6650a0a [DEV] remove some Logs 2013-07-24 23:10:53 +02:00
1b0c7b4704 [DEV] corection of the DEFINE protection 2013-07-09 15:14:55 +02:00
b8bb3aebf2 [DEV] update to the exml patch 2013-06-28 21:49:14 +02:00
18832b2305 [DEV] correction of the exml requested elements 2013-06-26 22:41:10 +02:00
7081b72812 [DEV] rename big and corect use of exml 2013-06-24 21:46:07 +02:00
521843f38f [DEV] rework lib to update at exml 2013-06-24 07:56:44 +02:00
4c0e4fb836 [DEV] remove old build system (replace by lutin) 2013-04-25 22:53:51 +02:00
2c7acec000 [DEV] update 'lutin' build system 2013-04-21 22:24:50 +02:00
26375523d5 [BUILD] basic makefile for python maker 2013-04-18 01:52:04 +02:00
928deb22ee [DEV] generate the svg image at the native size 2013-04-14 14:02:03 +02:00
b8287243a8 [dev] update to the nec vecter implementation 2013-01-28 08:08:11 +01:00
c305574cfd [DEBUG] verbose log error 2013-01-10 21:34:38 +01:00
8d360abdae [DEBUG] windows compilation warning remove 2012-12-28 23:11:01 +01:00
6ff447eadb [DEV] change the SVG parser dependence debug 2012-11-22 22:09:36 +01:00
2697e6940e [dev] add license file 2012-11-10 16:18:52 +01:00
fcd7a0542e [TAG] change the position of the tag 2012-11-09 00:58:09 +01:00
edfe4d2aa6 [DEV] Add capacity to the etk::FSNode ==> all is not good, but it is a good start 2012-11-02 18:10:14 +01:00
4ee34e6815 [DEV] usdate to the etk::FSNode 2012-11-01 10:49:36 +01:00
34d4ccc15f [DEV] change Vector2D ==> etk::Vector2D 2012-10-26 16:58:00 +02:00
8f07ec9b7c [DEBUG] display the size requested 2012-10-18 18:15:30 +02:00
ec38558a10 generate output in an agg image 2012-08-22 18:21:14 +02:00
2037fb3efc Move to the agg color system 2012-08-21 18:12:13 +02:00
fc100697e3 no specification on the librairy dependence type 2012-08-19 18:00:20 +02:00
70c27fedad simplify makefiles 2012-08-15 20:44:32 +02:00
e2597ef315 change the color_ts in a better class anc rename VectorType in Vector 2012-08-14 16:11:17 +02:00
fa80d21d57 add tag version on this parser 2012-08-13 09:49:07 +02:00
142 changed files with 10340 additions and 3234 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
*.pyc

88
.travis.yml Normal file
View File

@ -0,0 +1,88 @@
language: cpp
sudo: required
dist: trusty
branches:
only:
- master
- dev
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- g++-4.9
- expect
- binutils-mingw-w64-x86-64 # 64bit MinGW
- gcc-mingw-w64-x86-64
- g++-mingw-w64-x86-64
matrix:
include:
- os: linux
env: CONF=release BUILDER=gcc TARGET=Linux TAG=Linux COMPILATOR_OPTION="--compilator-version=4.9" GCOV=--gcov
compiler: gcc
- os: linux
env: CONF=debug BUILDER=clang TARGET=Linux
compiler: clang
- os: linux
env: CONF=release BUILDER=gcc TARGET=Windows TAG=Mingw
compiler: x86_64-w64-mingw32-gcc
- os: linux
env: CONF=release BUILDER=gcc TARGET=Android TAG=Android DISABLE_PACKAGE=-p
compiler: gcc
- os: osx
env: CONF=release BUILDER=clang TARGET=MacOs TAG=MacOs
compiler: clang
- os: osx
env: CONF=release BUILDER=clang TARGET=IOs TAG=IOs
compiler: clang
install:
- cd ..
- pip install --user lutin
- if [ "$TAG" == "Android" ]; then
git clone --depth 1 --branch master https://github.com/HeeroYui/android-download-tool;
./android-download-tool/dl-android.sh;
fi
- git clone --depth 1 --branch master https://github.com/atria-soft/ci.git
- cd -
before_script:
- cd ..
- git clone https://github.com/atria-soft/elog.git -b $TRAVIS_BRANCH
- git clone https://github.com/atria-soft/ememory.git -b $TRAVIS_BRANCH
- git clone https://github.com/atria-soft/echrono.git -b $TRAVIS_BRANCH
- git clone https://github.com/atria-soft/etk.git -b $TRAVIS_BRANCH
- git clone https://github.com/atria-soft/exml.git -b $TRAVIS_BRANCH
- git clone https://github.com/generic-library/gtest-lutin.git --recursive
- git clone https://github.com/generic-library/z-lutin.git --recursive
- pwd
- ls -l
- if [ "$TRAVIS_OS_NAME" == "osx" ]; then
export PATH=$PATH:/Users/travis/Library/Python/2.7/bin/;
fi
- ./ci/build_send.py --tag=$TAG --status=START;
script:
- lutin -w -j4 -C -P -t$TARGET -c $BUILDER $COMPILATOR_OPTION $BUS -m $CONF $GCOV $DISABLE_PACKAGE esvg-test; STATUS=$?
- ./ci/build_send.py --tag=$TAG --status="$STATUS";
after_script:
- if [ "$GCOV" != "" ]; then
./ci/warning_send.py --find-path ./out/Linux_x86_64/$CONF/build/$BUILDER/esvg/;
fi
- lutin -w -j4 -C -P -t$TARGET -c $BUILDER $COMPILATOR_OPTION $BUS -m $CONF $GCOV $DISABLE_PACKAGE esvg-test?run:--elog-level=3 | tee out_test.txt
- if [ "$GCOV" != "" ]; then
./ci/test_send.py --file=out_test.txt;
lutin -C -P -t $TARGET -c $BUILDER $COMPILATOR_OPTION $BUS -m $CONF -p esvg?gcov;
./ci/coverage_send.py --json=out/Linux_x86_64/$CONF/build/$BUILDER/esvg/esvg_coverage.json;
fi
notifications:
email:
- yui.heero@gmail.com

View File

@ -1,25 +0,0 @@
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
# name of the librairy
LOCAL_MODULE := parsersvg
# name of the dependency
LOCAL_STATIC_LIBRARIES := etk agg tinyxml
LOCAL_C_INCLUDES :=
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)
LOCAL_CFLAGS := -DPARSER_SVG_VERSION_TAG_NAME="\"???-$(BUILD_DIRECTORY_MODE)\""
# load the common sources file of the platform
include $(LOCAL_PATH)/file.mk
LOCAL_SRC_FILES := $(FILE_LIST)
include $(BUILD_STATIC_LIBRARY)

373
LICENSE Normal file
View File

@ -0,0 +1,373 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

View File

@ -1,23 +0,0 @@
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
# name of the librairy
LOCAL_MODULE := parsersvg
# name of the dependency
LOCAL_STATIC_LIBRARIES := etk agg tinyxml
LOCAL_C_INCLUDES :=
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)
LOCAL_CFLAGS := -DPARSER_SVG_VERSION_TAG_NAME="\"???-$(BUILD_DIRECTORY_MODE)\""
# load the common sources file of the platform
include $(LOCAL_PATH)/file.mk
LOCAL_SRC_FILES := $(FILE_LIST)
include $(BUILD_STATIC_LIBRARY)

79
README.md Normal file
View File

@ -0,0 +1,79 @@
esvg
=====
`esvg` is c++ svg image parser and renderer.
Release (master)
----------------
[![Build Status](https://travis-ci.org/atria-soft/esvg.svg?branch=master)](https://travis-ci.org/atria-soft/esvg)
[![Coverage Status](http://atria-soft.com/ci/coverage/atria-soft/esvg.svg?branch=master)](http://atria-soft.com/ci/atria-soft/esvg)
[![Test Status](http://atria-soft.com/ci/test/atria-soft/esvg.svg?branch=master)](http://atria-soft.com/ci/atria-soft/esvg)
[![Warning Status](http://atria-soft.com/ci/warning/atria-soft/esvg.svg?branch=master)](http://atria-soft.com/ci/atria-soft/esvg)
[![Build Status](http://atria-soft.com/ci/build/atria-soft/esvg.svg?branch=master&tag=Linux)](http://atria-soft.com/ci/atria-soft/esvg)
[![Build Status](http://atria-soft.com/ci/build/atria-soft/esvg.svg?branch=master&tag=MacOs)](http://atria-soft.com/ci/atria-soft/esvg)
[![Build Status](http://atria-soft.com/ci/build/atria-soft/esvg.svg?branch=master&tag=Mingw)](http://atria-soft.com/ci/atria-soft/esvg)
[![Build Status](http://atria-soft.com/ci/build/atria-soft/esvg.svg?branch=master&tag=Android)](http://atria-soft.com/ci/atria-soft/esvg)
[![Build Status](http://atria-soft.com/ci/build/atria-soft/esvg.svg?branch=master&tag=IOs)](http://atria-soft.com/ci/atria-soft/esvg)
Developement (dev)
------------------
[![Build Status](https://travis-ci.org/atria-soft/esvg.svg?branch=dev)](https://travis-ci.org/atria-soft/esvg)
[![Coverage Status](http://atria-soft.com/ci/coverage/atria-soft/esvg.svg?branch=dev)](http://atria-soft.com/ci/atria-soft/esvg)
[![Test Status](http://atria-soft.com/ci/test/atria-soft/esvg.svg?branch=dev)](http://atria-soft.com/ci/atria-soft/esvg)
[![Warning Status](http://atria-soft.com/ci/warning/atria-soft/esvg.svg?branch=dev)](http://atria-soft.com/ci/atria-soft/esvg)
[![Build Status](http://atria-soft.com/ci/build/atria-soft/esvg.svg?branch=dev&tag=Linux)](http://atria-soft.com/ci/atria-soft/esvg)
[![Build Status](http://atria-soft.com/ci/build/atria-soft/esvg.svg?branch=dev&tag=MacOs)](http://atria-soft.com/ci/atria-soft/esvg)
[![Build Status](http://atria-soft.com/ci/build/atria-soft/esvg.svg?branch=dev&tag=Mingw)](http://atria-soft.com/ci/atria-soft/esvg)
[![Build Status](http://atria-soft.com/ci/build/atria-soft/esvg.svg?branch=dev&tag=Android)](http://atria-soft.com/ci/atria-soft/esvg)
[![Build Status](http://atria-soft.com/ci/build/atria-soft/esvg.svg?branch=dev&tag=IOs)](http://atria-soft.com/ci/atria-soft/esvg)
Instructions
============
download Build system:
----------------------
sudo pip install lutin
sudo pip install pillow
download the software:
----------------------
mkdir WORKING_DIRECTORY
cd WORKING_DIRECTORY
git clone https://github.com/atria-soft/etk.git
git clone https://github.com/atria-soft/exml.git
git clone https://github.com/atria-soft/esvg.git
git clone https://github.com/generic-library/gtest-lutin.git --recursive
git clone https://github.com/generic-library/z-lutin.git --recursive
Compile software:
-----------------
cd WORKING_DIRECTORY
lutin -C -P esvg-test
License (MPL v2.0)
=====================
Copyright esvg Edouard DUPIN
Licensed under the Mozilla Public License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.mozilla.org/MPL/2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

1
authors.txt Normal file
View File

@ -0,0 +1 @@
MR Edouard DUPIN <yui.heero@gmail.com>

67
doc/build.md Normal file
View File

@ -0,0 +1,67 @@
Build lib & build sample {#esvg_build}
========================
@tableofcontents
Download: {#esvg_build_download}
=========
esvg use some tools to manage source and build it:
lutin (build-system): {#esvg_build_download_lutin}
---------------------
```{.sh}
pip install lutin --user
# optionnal dependency of lutin (manage image changing size for application release)
pip install pillow --user
```
dependency: {#esvg_build_download_dependency}
-----------
```{.sh}
mkdir framework
cd framework
git clone https://github.com/atria-soft/etk.git
git clone https://github.com/atria-soft/exml.git
git clone https://github.com/generic-library/gtest-lutin.git --recursive
git clone https://github.com/generic-library/z-lutin.git --recursive
cd ..
```
sources: {#esvg_build_download_sources}
--------
```{.sh}
cd framework
git clone https://github.com/atria-soft/esvg.git
cd ..
```
Build: {#esvg_build_build}
======
library: {#esvg_build_build_library}
--------
```{.sh}
lutin -mdebug esvg
```
Sample: {#esvg_build_build_sample}
-------
```{.sh}
lutin -mdebug esvg-test
```
Run sample: {#esvg_build_run_sample}
===========
```{.sh}
lutin -mdebug esvg-test?run
```

62
doc/mainpage.md Normal file
View File

@ -0,0 +1,62 @@
ESVG library {#mainpage}
=============
@tableofcontents
What is ESVG: {#esvg_mainpage_what}
==============
`esvg` is c++ svg image parser and renderer.
What it does: {#esvg_mainpage_what_it_does}
-------------
It parse a svg file (not compressed) and render it in a simple raw image.
ESVG is dependent of the STL (compatible with MacOs stl (CXX))
What is the TODO list: {#esvg_mainpage_todo}
----------------------
Write an interface to manage internal element of the svg (same methode of exml @ref #exml_mainpage_what or ejson @ref #ejson_mainpage_what)
Write svg file
Access et internal meta-data.
What languages are supported? {#esvg_mainpage_language}
=============================
ESVG is written in C++.
Are there any licensing restrictions? {#esvg_mainpage_license_restriction}
=====================================
ESVG is **FREE software** and _all sub-library are FREE and staticly linkable !!!_
License (MPL v2.0) {#esvg_mainpage_license}
==================
Copyright ESVG Edouard DUPIN
Licensed under the Mozilla Public License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
<https://www.mozilla.org/MPL/2.0>
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Other pages {#esvg_mainpage_sub_page}
===========
- @ref esvg_build
- [**ewol coding style**](http://atria-soft.github.io/ewol/ewol_coding_style.html)

32
doxy_esvg.py Normal file
View File

@ -0,0 +1,32 @@
#!/usr/bin/python
import os
import doxy.module as module
import doxy.debug as debug
import doxy.tools as tools
def create(target, module_name):
my_module = module.Module(__file__, module_name)
my_module.set_version("version.txt")
my_module.set_title("esvg: Ewol SVG parser and renderer")
my_module.set_website("http://atria-soft.github.io/" + module_name)
my_module.set_website_sources("http://github.com/atria-soft/" + module_name)
my_module.add_path([
module_name,
"doc"
])
my_module.add_depend([
'exml',
'etk'
])
my_module.add_exclude_symbols([
'*operator<<*',
])
my_module.add_exclude_file([
'debug.hpp',
])
my_module.add_file_patterns([
'*.hpp',
'*.md',
])
return my_module

439
esvg/Base.cpp Normal file
View File

@ -0,0 +1,439 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/debug.hpp>
#include <esvg/Base.hpp>
#include <cmath>
const float esvg::kappa90(0.5522847493f);
esvg::PaintState::PaintState() :
fill(etk::Pair<etk::Color<float,4>, etk::String>(etk::color::black, "")),
stroke(etk::Pair<etk::Color<float,4>, etk::String>(etk::color::none, "")),
strokeWidth(1.0f),
flagEvenOdd(false),
lineCap(esvg::cap_butt),
lineJoin(esvg::join_miter),
miterLimit(4.0f),
viewPort(vec2(0.0f,0.0f), vec2(0.0f,0.0f)),
opacity(1.0) {
}
void esvg::PaintState::clear() {
fill = etk::Pair<etk::Color<float,4>, etk::String>(etk::color::black, "");
stroke = etk::Pair<etk::Color<float,4>, etk::String>(etk::color::none, "");
strokeWidth = 1.0;
viewPort.first.setValue(0.0f,0.0f);
viewPort.first.setValue(0.0f,0.0f);
flagEvenOdd = false;
lineJoin = esvg::join_miter;
lineCap = esvg::cap_butt;
miterLimit = 4.0f;
opacity = 1.0;
}
esvg::Base::Base(PaintState _parentPaintState) {
// copy the parent painting properties ...
m_paint = _parentPaintState;
}
etk::String extractTransformData(const etk::String& _value, const etk::String& _base) {
size_t posStart = _value.find(_base);
if (posStart == etk::String::npos) {
// Not find element is a normal case ...
return "";
}
posStart += _base.size();
if (_value.size() < posStart+2) {
ESVG_ERROR("Not enought spece in the String to have transform value for ' (' or '()' in '" << _value << "'");
return "";
}
if (_value[posStart] == '(') {
// normal SVG does not support this case ...
posStart++;
} else if ( _value[posStart] == ' '
&& _value[posStart+1] == '(') {
posStart+=2;
} else {
ESVG_ERROR("Can not find ' (' or '(' in '" << &_value[posStart] << "' for '" << _value << "'");
return "";
}
if (_value.size() < posStart+1) {
ESVG_ERROR("Not enought spece in the String to have transform value for ')' in '" << _value << "'");
return "";
}
size_t posEnd = _value.find(')', posStart);
if (posEnd == etk::String::npos) {
ESVG_ERROR("Missing element ')' in '" << _value << "' for " << _base);
return "";
}
ESVG_VERBOSE("Find : '" << etk::String(_value.begin()+posStart, _value.begin()+posEnd) << "' for " << _base);
return etk::String(_value.begin()+posStart, _value.begin()+posEnd);
}
void esvg::Base::parseTransform(const exml::Element& _element) {
if (_element.exist() == false) {
return;
}
etk::String inputString = _element.attributes["transform"];
if (inputString.size() == 0) {
return;
}
ESVG_VERBOSE("find transform : \"" << inputString << "\"");
for (size_t iii=0; iii<inputString.size(); iii++) {
if (inputString[iii] == ',') {
inputString[iii] = ' ';
}
}
ESVG_VERBOSE("find transform : \"" << inputString << "\"");
// need to find elements in order ...
etk::String data = extractTransformData(inputString, "matrix");
if (data.size() != 0) {
double matrix[6];
if (sscanf(data.c_str(), "%lf %lf %lf %lf %lf %lf", &matrix[0], &matrix[1], &matrix[2], &matrix[3], &matrix[4], &matrix[5]) == 6) {
m_transformMatrix = mat2x3(matrix);
// find a matrix : simply exit ...
return;
} else {
ESVG_ERROR("Parsing matrix() with wrong data ... '" << data << "'");
}
}
data = extractTransformData(inputString, "translate");
if (data.size() != 0) {
float xxx, yyy;
if (sscanf(data.c_str(), "%f %f", &xxx, &yyy) == 2) {
m_transformMatrix *= etk::mat2x3Translate(vec2(xxx, yyy));
ESVG_VERBOSE("Translate : " << xxx << ", " << yyy);
} else if (sscanf(data.c_str(), "%f", &xxx) == 1) {
m_transformMatrix *= etk::mat2x3Translate(vec2(xxx, 0));
ESVG_VERBOSE("Translate : " << xxx << ", " << 0);
} else {
ESVG_ERROR("Parsing translate() with wrong data ... '" << data << "'");
}
}
data = extractTransformData(inputString, "scale");
if (data.size() != 0) {
float xxx, yyy;
if (sscanf(data.c_str(), "%f %f", &xxx, &yyy) == 2) {
m_transformMatrix *= etk::mat2x3Scale(vec2(xxx, yyy));
ESVG_VERBOSE("Scale : " << xxx << ", " << yyy);
} else if (sscanf(data.c_str(), "%f", &xxx) == 1) {
m_transformMatrix *= etk::mat2x3Scale(xxx);
ESVG_VERBOSE("Scale : " << xxx << ", " << xxx);
} else {
ESVG_ERROR("Parsing scale() with wrong data ... '" << data << "'");
}
}
data = extractTransformData(inputString, "rotate");
if (data.size() != 0) {
float angle, xxx, yyy;
if (sscanf(data.c_str(), "%f %f %f", &angle, &xxx, &yyy) == 3) {
angle = angle / 180 * M_PI;
m_transformMatrix *= etk::mat2x3Translate(vec2(-xxx, -yyy));
m_transformMatrix *= etk::mat2x3Rotate(angle);
m_transformMatrix *= etk::mat2x3Translate(vec2(xxx, yyy));
} else if (sscanf(data.c_str(), "%f", &angle) == 1) {
angle = angle / 180 * M_PI;
ESVG_VERBOSE("rotate : " << angle << "rad, " << (angle/M_PI*180) << "°");
m_transformMatrix *= etk::mat2x3Rotate(angle);
} else {
ESVG_ERROR("Parsing rotate() with wrong data ... '" << data << "'");
}
}
data = extractTransformData(inputString, "skewX");
if (data.size() != 0) {
float angle;
if (sscanf(data.c_str(), "%f", &angle) == 1) {
angle = angle / 180 * M_PI;
ESVG_VERBOSE("skewX : " << angle << "rad, " << (angle/M_PI*180) << "°");
m_transformMatrix *= etk::mat2x3Skew(vec2(angle, 0.0f));
} else {
ESVG_ERROR("Parsing skewX() with wrong data ... '" << data << "'");
}
}
data = extractTransformData(inputString, "skewY");
if (data.size() != 0) {
float angle;
if (sscanf(data.c_str(), "%f", &angle) == 1) {
angle = angle / 180 * M_PI;
ESVG_VERBOSE("skewY : " << angle << "rad, " << (angle/M_PI*180) << "°");
m_transformMatrix *= etk::mat2x3Skew(vec2(0.0f, angle));
} else {
ESVG_ERROR("Parsing skewY() with wrong data ... '" << data << "'");
}
}
}
void esvg::Base::parsePosition(const exml::Element& _element, vec2 &_pos, vec2 &_size) {
_pos.setValue(0,0);
_size.setValue(0,0);
if (_element.exist() == false) {
return;
}
etk::String content = _element.attributes["x"];
if (content.size()!=0) {
_pos.setX(parseLength(content));
}
content = _element.attributes["y"];
if (content.size()!=0) {
_pos.setY(parseLength(content));
}
content = _element.attributes["width"];
if (content.size()!=0) {
_size.setX(parseLength(content));
}
content = _element.attributes["height"];
if (content.size()!=0) {
_size.setY(parseLength(content));
}
}
etk::Pair<float, enum esvg::distance> esvg::Base::parseLength2(const etk::String& _dataInput) {
ESVG_VERBOSE(" lenght : '" << _dataInput << "'");
float n = _dataInput.to<float>();
etk::String unit;
for (size_t iii=0; iii<_dataInput.size(); ++iii) {
if( (_dataInput[iii]>='0' && _dataInput[iii]<='9')
|| _dataInput[iii]=='+'
|| _dataInput[iii]=='-'
|| _dataInput[iii]=='.') {
continue;
}
unit = etk::String(_dataInput, iii);
break;
}
ESVG_VERBOSE(" lenght : '" << n << "' => unit=" << unit);
// note : ";" is for the parsing of the style elements ...
if(unit.size() == 0) {
return etk::makePair(n, esvg::distance_pixel);
} else if (unit[0] == '%') { // xxx %
return etk::makePair(n, esvg::distance_pourcent);
} else if ( unit[0] == 'e'
&& unit[1] == 'm') { // xxx em
return etk::makePair(n, esvg::distance_element);
} else if ( unit[0] == 'e'
&& unit[1] == 'x') { // xxx ex
return etk::makePair(n, esvg::distance_ex);
} else if ( unit[0] == 'p'
&& unit[1] == 'x') { // xxx px
return etk::makePair(n, esvg::distance_pixel);
} else if ( unit[0] == 'p'
&& unit[1] == 't') { // xxx pt
return etk::makePair(n, esvg::distance_point);
} else if ( unit[0] == 'p'
&& unit[1] == 'c') { // xxx pc
return etk::makePair(n, esvg::distance_pc);
} else if ( unit[0] == 'm'
&& unit[1] == 'm') { // xxx mm
return etk::makePair(n, esvg::distance_millimeter);
} else if ( unit[0] == 'c'
&& unit[1] == 'm') { // xxx cm
return etk::makePair(n, esvg::distance_centimeter);
} else if ( unit[0] == 'i'
&& unit[1] == 'n') { // xxx in
return etk::makePair(n, esvg::distance_inch);
}
return etk::makePair(0.0f, esvg::distance_pixel);
}
float esvg::Base::parseLength(const etk::String& _dataInput) {
etk::Pair<float, enum esvg::distance> value = parseLength2(_dataInput);
ESVG_VERBOSE(" lenght : '" << value.first << "' => unit=" << value.second);
float font_size = 20.0f;
switch (value.second) {
case esvg::distance_pourcent:
return value.first;// / 100.0 * m_paint.viewPort.x();
case esvg::distance_element:
return value.first * font_size;
case esvg::distance_ex:
return value.first / 2.0f * font_size;
case esvg::distance_pixel:
return value.first;
case esvg::distance_point:
return value.first * 1.25f;
case esvg::distance_pc:
return value.first * 15.0f;
case esvg::distance_millimeter:
return value.first * 3.543307f;
case esvg::distance_centimeter:
return value.first * 35.43307f;
case esvg::distance_inch:
return value.first * 90.0f;
}
return 0.0f;
}
void esvg::Base::parsePaintAttr(const exml::Element& _element) {
if (_element.exist() == false) {
return;
}
/*
bool fillNone = false;
bool strokeNone = false;
*/
etk::String content;
// ---------------- get unique ID ----------------
m_id = _element.attributes["id"];
// ---------------- stroke ----------------
content = _element.attributes["stroke"];
if (content == "none") {
m_paint.stroke = etk::Pair<etk::Color<float,4>, etk::String>(etk::color::none, "");
} else {
if (content.size()!=0) {
m_paint.stroke = parseColor(content);
}
content = _element.attributes["stroke-width"];
if (content.size()!=0) {
m_paint.strokeWidth = parseLength(content);
}
content = _element.attributes["stroke-opacity"];
if (content.size()!=0) {
float opacity = parseLength(content);
opacity = etk::avg(0.0f, opacity, 1.0f);
m_paint.stroke.first.setA(opacity);
}
content = _element.attributes["stroke-dasharray"];
if (content.size()!=0) {
if (content == "none" ) {
// OK, Nothing to do ...
} else {
ESVG_TODO(" 'stroke-dasharray' not implemented ...");
}
}
content = _element.attributes["stroke-linecap"];
if (content.size()!=0) {
if (content == "butt" ) {
m_paint.lineCap = esvg::cap_butt;
} else if (content == "round" ) {
m_paint.lineCap = esvg::cap_round;
} else if (content == "square" ) {
m_paint.lineCap = esvg::cap_square;
} else {
m_paint.lineCap = esvg::cap_butt;
ESVG_ERROR("not know stroke-linecap value : \"" << content << "\", not in [butt,round,square]");
}
}
content = _element.attributes["stroke-linejoin"];
if (content.size()!=0) {
if (content == "miter" ) {
m_paint.lineJoin = esvg::join_miter;
} else if (content == "round" ) {
m_paint.lineJoin = esvg::join_round;
} else if (content == "bevel" ) {
m_paint.lineJoin = esvg::join_bevel;
} else {
m_paint.lineJoin = esvg::join_miter;
ESVG_ERROR("not know stroke-linejoin value : \"" << content << "\", not in [miter,round,bevel]");
}
}
content = _element.attributes["stroke-miterlimit"];
if (content.size()!=0) {
float tmp = parseLength(content);
m_paint.miterLimit = etk::max(0.0f, tmp);
}
}
// ---------------- FILL ----------------
content = _element.attributes["fill"];
if (content == "none") {
m_paint.fill = etk::Pair<etk::Color<float,4>, etk::String>(etk::color::none, "");
} else {
if (content.size()!=0) {
m_paint.fill = parseColor(content);
}
content = _element.attributes["fill-opacity"];
if (content.size()!=0) {
float opacity = parseLength(content);
opacity = etk::avg(0.0f, opacity, 1.0f);
m_paint.fill.first.setA(opacity);
}
content = _element.attributes["fill-rule"];
if (content.size()!=0) {
if (content == "nonzero") {
m_paint.flagEvenOdd = false;
} else if (content == "evenodd" ) {
m_paint.flagEvenOdd = true;
} else {
ESVG_ERROR("not know fill-rule value : \"" << content << "\", not in [nonzero,evenodd]");
}
}
// ---------------- opacity ----------------
content = _element.attributes["opacity"];
if (content.size()!=0) {
m_paint.opacity = parseLength(content);
m_paint.opacity = etk::avg(0.0f, m_paint.opacity, 1.0f);
}
}
}
etk::Pair<etk::Color<float,4>, etk::String> esvg::Base::parseColor(const etk::String& _inputData) {
etk::Pair<etk::Color<float,4>, etk::String> localColor(etk::color::white, "");
if( _inputData.size() > 4
&& _inputData[0] == 'u'
&& _inputData[1] == 'r'
&& _inputData[2] == 'l'
&& _inputData[3] == '(') {
if (_inputData[4] == '#') {
etk::String color(_inputData.begin() + 5, _inputData.end()-1);
localColor = etk::Pair<etk::Color<float,4>, etk::String>(etk::color::none, color);
} else {
ESVG_ERROR("Problem in parsing the color : \"" << _inputData << "\" == > url(XXX) is not supported now ...");
}
} else {
localColor = etk::Pair<etk::Color<float,4>, etk::String>(_inputData, "");
}
ESVG_VERBOSE("Parse color : \"" << _inputData << "\" == > " << localColor.first << " " << localColor.second);
return localColor;
}
bool esvg::Base::parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax) {
// TODO : UNDERSTAND why nothing is done here ...
// Parse basic elements (ID...):
m_id = _element.attributes["id"];
_sizeMax = vec2(0.0f, 0.0f);
return false;
}
const char * esvg::Base::spacingDist(int32_t _spacing) {
static const char *tmpValue = " ";
if (_spacing>20) {
_spacing = 20;
}
return tmpValue + 20*4 - _spacing*4;
}
void esvg::Base::draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level) {
ESVG_WARNING(spacingDist(_level) << "DRAW esvg::Base ... ==> No drawing availlable");
}
const etk::String& esvg::Base::getId() const {
return m_id;
}
void esvg::Base::setId(const etk::String& _newId) {
// TODO : Check if it is UNIQUE ...
m_id = _newId;
}
void esvg::Base::drawShapePoints(etk::Vector<etk::Vector<vec2>>& _out,
int32_t _recurtionMax,
float _threshold,
mat2x3& _basicTrans,
int32_t _level) {
}

129
esvg/Base.hpp Normal file
View File

@ -0,0 +1,129 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/join.hpp>
#include <esvg/cap.hpp>
#pragma once
#include <etk/types.hpp>
#include <etk/Vector.hpp>
#include <etk/math/Vector2D.hpp>
#include <etk/math/Matrix2x3.hpp>
#include <etk/Color.hpp>
#include <esvg/render/Path.hpp>
#include <exml/exml.hpp>
#include <esvg/Renderer.hpp>
#include <esvg/Dimension.hpp>
namespace esvg {
extern const float kappa90; //!< proportional lenght to the radius of a bezier handle for 90° arcs.
/**
* @brief Painting mode of the Object:
*/
enum paint {
paint_none, //!< No painting.
paint_color, //!< Painting a color.
paint_gradientLinear, //!< Painting a linear gradient.
paint_gradientRadial //!< Painting a radial gradient.
};
class PaintState {
public:
PaintState();
void clear();
public:
etk::Pair<etk::Color<float,4>, etk::String> fill;
etk::Pair<etk::Color<float,4>, etk::String> stroke;
float strokeWidth;
bool flagEvenOdd; //!< Fill rules
enum esvg::cap lineCap;
enum esvg::join lineJoin;
float miterLimit;
etk::Pair<vec2, vec2> viewPort; //!< min pos, max pos
float opacity;
};
class Base {
protected:
PaintState m_paint;
mat2x3 m_transformMatrix; //!< specific render of the curent element
const char * spacingDist(int32_t _spacing);
public:
Base() {};
Base(PaintState _parentPaintState);
virtual ~Base() { };
/**
* @brief parse all the element needed in the basic node
* @param[in] _element standart XML node
* @return true if no problem arrived
*/
virtual bool parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax);
/**
* @brief Draw the form in the renderer
* @param[in] _myRenderer Renderer engine
* @param[in] _basicTrans Parant transformation of the environement
* @param[in] _level Level of the tree
*/
virtual void draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level=1);
/**
* @brief Draw rhe shape with all points
* @param[in] _out where the lines are added
* @param[in] _recurtionMax interpolation recurtion max
* @param[in] _threshold threshold to stop recurtion
* @param[in] _basicTrans Parant transformation of the environement
* @param[in] _level Level of the tree
*/
virtual void drawShapePoints(etk::Vector<etk::Vector<vec2>>& _out,
int32_t _recurtionMax,
float _threshold,
mat2x3& _basicTrans,
int32_t _level=1);
virtual void display(int32_t _spacing) { };
void parseTransform(const exml::Element& _element);
/**
* @brief parse x, y, width, height attribute of the xml node
* @param[in] _element XML node
* @param[out] _pos parsed position
* @param[out] _size parsed dimention
*/
void parsePosition(const exml::Element& _element, vec2 &_pos, vec2 &_size);
/**
* @brief parse a lenght of the xml element
* @param[in] _dataInput Data C String with the printed lenght
* @return standard number of pixels
*/
float parseLength(const etk::String& _dataInput);
etk::Pair<float, enum esvg::distance> parseLength2(const etk::String& _dataInput);
/**
* @brief parse a Painting attribute of a specific node
* @param[in] _element Basic node of the XML that might be parsed
*/
void parsePaintAttr(const exml::Element& _element);
/**
* @brief parse a color specification from the svg file
* @param[in] _inputData Data C String with the xml definition
* @return The parsed color (color used and the link if needed)
*/
etk::Pair<etk::Color<float,4>, etk::String> parseColor(const etk::String& _inputData);
protected:
etk::String m_id; //!< unique ID of the element.
public:
/**
* @brief Get the ID of the Element
* @return UniqueId in the svg file
*/
const etk::String& getId() const;
/**
* @brief Set the ID of the Element
* @param[in] _newId New Id of the element
*/
void setId(const etk::String& _newId);
};
};

166
esvg/Circle.cpp Normal file
View File

@ -0,0 +1,166 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/debug.hpp>
#include <esvg/Circle.hpp>
#include <esvg/render/Path.hpp>
#include <esvg/render/Weight.hpp>
esvg::Circle::Circle(PaintState _parentPaintState) : esvg::Base(_parentPaintState) {
}
esvg::Circle::~Circle() {
}
bool esvg::Circle::parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax) {
m_radius = 0.0;
m_position.setValue(0,0);
if (_element.exist() == false) {
return false;
}
parseTransform(_element);
parsePaintAttr(_element);
// add the property of the parrent modifications ...
m_transformMatrix *= _parentTrans;
etk::String content = _element.attributes["cx"];
if (content.size()!=0) {
m_position.setX(parseLength(content));
}
content = _element.attributes["cy"];
if (content.size()!=0) {
m_position.setY(parseLength(content));
}
content = _element.attributes["r"];
if (content.size()!=0) {
m_radius = parseLength(content);
} else {
ESVG_ERROR("(l "<<_element.getPos()<<") Circle \"r\" is not present");
return false;
}
if (0 > m_radius) {
m_radius = 0;
ESVG_ERROR("(l "<<_element.getPos()<<") Circle \"r\" is negative");
return false;
}
_sizeMax.setValue(m_position.x() + m_radius, m_position.y() + m_radius);
return true;
}
void esvg::Circle::display(int32_t _spacing) {
ESVG_DEBUG(spacingDist(_spacing) << "Circle " << m_position << " radius=" << m_radius);
}
esvg::render::Path esvg::Circle::createPath() {
esvg::render::Path out;
out.clear();
out.moveTo(false, m_position + vec2(m_radius, 0.0f));
out.curveTo(false,
m_position + vec2(m_radius, m_radius*esvg::kappa90),
m_position + vec2(m_radius*esvg::kappa90, m_radius),
m_position + vec2(0.0f, m_radius));
out.curveTo(false,
m_position + vec2(-m_radius*esvg::kappa90, m_radius),
m_position + vec2(-m_radius, m_radius*esvg::kappa90),
m_position + vec2(-m_radius, 0.0f));
out.curveTo(false,
m_position + vec2(-m_radius, -m_radius*esvg::kappa90),
m_position + vec2(-m_radius*esvg::kappa90, -m_radius),
m_position + vec2(0.0f, -m_radius));
out.curveTo(false,
m_position + vec2(m_radius*esvg::kappa90, -m_radius),
m_position + vec2(m_radius, -m_radius*esvg::kappa90),
m_position + vec2(m_radius, 0.0f));
out.close();
return out;
}
void esvg::Circle::draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level) {
ESVG_VERBOSE(spacingDist(_level) << "DRAW esvg::Circle");
if (m_radius <= 0.0f) {
ESVG_VERBOSE(spacingDist(_level+1) << "Too small radius" << m_radius);
return;
}
esvg::render::Path listElement = createPath();
mat2x3 mtx = m_transformMatrix;
mtx *= _basicTrans;
esvg::render::PointList listPoints;
listPoints = listElement.generateListPoints(_level,
_myRenderer.getInterpolationRecurtionMax(),
_myRenderer.getInterpolationThreshold());
//listPoints.applyMatrix(mtx);
esvg::render::SegmentList listSegmentFill;
esvg::render::SegmentList listSegmentStroke;
esvg::render::Weight tmpFill;
esvg::render::Weight tmpStroke;
ememory::SharedPtr<esvg::render::DynamicColor> colorFill = esvg::render::createColor(m_paint.fill, mtx);
ememory::SharedPtr<esvg::render::DynamicColor> colorStroke;
if (m_paint.strokeWidth > 0.0f) {
colorStroke = esvg::render::createColor(m_paint.stroke, mtx);
}
// Check if we need to display background
if (colorFill != null) {
listSegmentFill.createSegmentList(listPoints);
colorFill->setViewPort(listSegmentFill.getViewPort());
listSegmentFill.applyMatrix(mtx);
// now, traverse the scanlines and find the intersections on each scanline, use non-zero rule
tmpFill.generate(_myRenderer.getSize(),
_myRenderer.getNumberSubScanLine(),
listSegmentFill);
}
// check if we need to display stroke:
if (colorStroke != null) {
listSegmentStroke.createSegmentListStroke(listPoints,
m_paint.strokeWidth,
m_paint.lineCap,
m_paint.lineJoin,
m_paint.miterLimit);
colorStroke->setViewPort(listSegmentStroke.getViewPort());
listSegmentStroke.applyMatrix(mtx);
// now, traverse the scanlines and find the intersections on each scanline, use non-zero rule
tmpStroke.generate(_myRenderer.getSize(),
_myRenderer.getNumberSubScanLine(),
listSegmentStroke);
}
// add on images:
_myRenderer.print(tmpFill,
colorFill,
tmpStroke,
colorStroke,
m_paint.opacity);
#ifdef DEBUG
_myRenderer.addDebugSegment(listSegmentFill);
_myRenderer.addDebugSegment(listSegmentStroke);
#endif
}
void esvg::Circle::drawShapePoints(etk::Vector<etk::Vector<vec2>>& _out,
int32_t _recurtionMax,
float _threshold,
mat2x3& _basicTrans,
int32_t _level) {
ESVG_VERBOSE(spacingDist(_level) << "DRAW Shape esvg::Circle");
esvg::render::Path listElement = createPath();
mat2x3 mtx = m_transformMatrix;
mtx *= _basicTrans;
esvg::render::PointList listPoints;
listPoints = listElement.generateListPoints(_level, _recurtionMax, _threshold);
listPoints.applyMatrix(mtx);
for (auto &it : listPoints.m_data) {
etk::Vector<vec2> listPoint;
for (auto &itDot : it) {
listPoint.pushBack(itDot.m_pos);
}
_out.pushBack(listPoint);
}
}

31
esvg/Circle.hpp Normal file
View File

@ -0,0 +1,31 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <esvg/Base.hpp>
namespace esvg {
class Circle : public esvg::Base {
private:
vec2 m_position; //!< Position of the Circle
float m_radius; //!< Radius of the Circle
public:
Circle(PaintState _parentPaintState);
~Circle();
bool parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax) override;
void display(int32_t _spacing) override;
void draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level) override;
void drawShapePoints(etk::Vector<etk::Vector<vec2>>& _out,
int32_t _recurtionMax,
float _threshold,
mat2x3& _basicTrans,
int32_t _level=1) override;
private:
esvg::render::Path createPath();
};
}

445
esvg/Dimension.cpp Normal file
View File

@ -0,0 +1,445 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/Dimension.hpp>
#include <esvg/debug.hpp>
static const float inchToMillimeter = 1.0f/25.4f;
static const float footToMillimeter = 1.0f/304.8f;
static const float meterToMillimeter = 1.0f/1000.0f;
static const float centimeterToMillimeter = 1.0f/10.0f;
static const float kilometerToMillimeter = 1.0f/1000000.0f;
static const float millimeterToInch = 25.4f;
static const float millimeterToFoot = 304.8f;
static const float millimeterToMeter =1000.0f;
static const float millimeterToCentimeter = 10.0f;
static const float millimeterToKilometer = 1000000.0f;
// 72 px /inch(2.54cm)
static const float basicRatio = 72.0f / 25.4f;
esvg::Dimension::Dimension() :
m_data(0,0),
m_type(esvg::distance_pixel) {
// notinh to do ...
}
esvg::Dimension::Dimension(const vec2& _size, enum esvg::distance _type) :
m_data(0,0),
m_type(esvg::distance_pixel) {
set(_size, _type);
}
void esvg::Dimension::set(etk::String _config) {
m_data.setValue(0,0);
m_type = esvg::distance_pixel;
enum distance type = esvg::distance_pixel;
if (etk::end_with(_config, "%", false) == true) {
type = esvg::distance_pourcent;
_config.erase(_config.size()-1, 1);
} else if (etk::end_with(_config, "px",false) == true) {
type = esvg::distance_pixel;
_config.erase(_config.size()-2, 2);
} else if (etk::end_with(_config, "ft",false) == true) {
type = esvg::distance_foot;
_config.erase(_config.size()-2, 2);
} else if (etk::end_with(_config, "in",false) == true) {
type = esvg::distance_inch;
_config.erase(_config.size()-2, 2);
} else if (etk::end_with(_config, "km",false) == true) {
type = esvg::distance_kilometer;
_config.erase(_config.size()-2, 2);
} else if (etk::end_with(_config, "mm",false) == true) {
type = esvg::distance_millimeter;
_config.erase(_config.size()-2, 2);
} else if (etk::end_with(_config, "cm",false) == true) {
type = esvg::distance_centimeter;
_config.erase(_config.size()-2, 2);
} else if (etk::end_with(_config, "m",false) == true) {
type = esvg::distance_meter;
_config.erase(_config.size()-1, 1);
} else {
type = esvg::distance_pixel;
ESVG_VERBOSE("default dimention type for: '" << _config << "' ==> pixel");
return;
}
vec2 tmp = _config;
set(tmp, type);
ESVG_VERBOSE(" config dimention : \"" << _config << "\" == > " << *this );
}
static enum esvg::distance parseType(etk::String& _config) {
enum esvg::distance type = esvg::distance_pixel;
if (etk::end_with(_config, "%", false) == true) {
type = esvg::distance_pourcent;
_config.erase(_config.size()-1, 1);
} else if (etk::end_with(_config, "px",false) == true) {
type = esvg::distance_pixel;
_config.erase(_config.size()-2, 2);
} else if (etk::end_with(_config, "ft",false) == true) {
type = esvg::distance_foot;
_config.erase(_config.size()-2, 2);
} else if (etk::end_with(_config, "in",false) == true) {
type = esvg::distance_inch;
_config.erase(_config.size()-2, 2);
} else if (etk::end_with(_config, "km",false) == true) {
type = esvg::distance_kilometer;
_config.erase(_config.size()-2, 2);
} else if (etk::end_with(_config, "mm",false) == true) {
type = esvg::distance_millimeter;
_config.erase(_config.size()-2, 2);
} else if (etk::end_with(_config, "cm",false) == true) {
type = esvg::distance_centimeter;
_config.erase(_config.size()-2, 2);
} else if (etk::end_with(_config, "m",false) == true) {
type = esvg::distance_meter;
_config.erase(_config.size()-1, 1);
} else {
type = esvg::distance_pixel;
ESVG_VERBOSE("default dimention type for: '" << _config << "' ==> pixel");
}
return type;
}
void esvg::Dimension::set(etk::String _configX, etk::String _configY) {
m_data.setValue(0,0);
m_type = esvg::distance_pixel;
enum distance type = esvg::distance_pixel;
// First Parse X
enum distance typeX = parseType(_configX);
float valueX = etk::string_to_float(_configX);
// Second Parse Y
enum distance typeY = parseType(_configY);
float valueY = etk::string_to_float(_configY);
// TODO : Check difference ...
set(vec2(valueX, valueY), typeX);
ESVG_VERBOSE(" config dimention : '" << _configX << "' '" << _configY << "' == > " << *this );
}
esvg::Dimension::~Dimension() {
// nothing to do ...
}
esvg::Dimension::operator etk::String() const {
etk::String str;
str = getValue();
switch(getType()) {
case esvg::distance_pourcent:
str += "%";
break;
case esvg::distance_pixel:
str += "px";
break;
case esvg::distance_meter:
str += "m";
break;
case esvg::distance_centimeter:
str += "cm";
break;
case esvg::distance_millimeter:
str += "mm";
break;
case esvg::distance_kilometer:
str += "km";
break;
case esvg::distance_inch:
str += "in";
break;
case esvg::distance_foot:
str += "ft";
break;
case esvg::distance_element:
str += "em";
break;
case esvg::distance_ex:
str += "ex";
break;
case esvg::distance_point:
str += "pt";
break;
case esvg::distance_pc:
str += "pc";
break;
}
return str;
}
void esvg::Dimension::set(const vec2& _size, enum esvg::distance _type) {
m_data = _size;
m_type = _type;
switch(_type) {
case esvg::distance_pourcent:
case esvg::distance_pixel:
// nothing to do: Supported ...
break;
case esvg::distance_meter:
case esvg::distance_centimeter:
case esvg::distance_millimeter:
case esvg::distance_kilometer:
case esvg::distance_inch:
case esvg::distance_foot:
case esvg::distance_element:
case esvg::distance_ex:
case esvg::distance_point:
case esvg::distance_pc:
ESVG_ERROR("Does not support other than Px and % type of dimention : " << _type << " automaticly convert with {72,72} pixel/inch");
break;
}
}
vec2 esvg::Dimension::getPixel(const vec2& _upperSize) const {
switch(m_type) {
case esvg::distance_pourcent:
return vec2(_upperSize.x()*m_data.x()*0.01f, _upperSize.y()*m_data.y()*0.01f);
case esvg::distance_pixel:
return m_data;
case esvg::distance_meter:
return vec2(m_data.x()*meterToMillimeter*basicRatio, m_data.y()*meterToMillimeter*basicRatio);
case esvg::distance_centimeter:
return vec2(m_data.x()*centimeterToMillimeter*basicRatio, m_data.y()*centimeterToMillimeter*basicRatio);
case esvg::distance_millimeter:
return vec2(m_data.x()*basicRatio, m_data.y()*basicRatio);
case esvg::distance_kilometer:
return vec2(m_data.x()*kilometerToMillimeter*basicRatio, m_data.y()*kilometerToMillimeter*basicRatio);
case esvg::distance_inch:
return vec2(m_data.x()*inchToMillimeter*basicRatio, m_data.y()*inchToMillimeter*basicRatio);
case esvg::distance_foot:
return vec2(m_data.x()*footToMillimeter*basicRatio, m_data.y()*footToMillimeter*basicRatio);
}
return vec2(128.0f, 128.0f);
}
etk::Stream& esvg::operator <<(etk::Stream& _os, enum esvg::distance _obj) {
switch(_obj) {
case esvg::distance_pourcent:
_os << "%";
break;
case esvg::distance_pixel:
_os << "px";
break;
case esvg::distance_meter:
_os << "m";
break;
case esvg::distance_centimeter:
_os << "cm";
break;
case esvg::distance_millimeter:
_os << "mm";
break;
case esvg::distance_kilometer:
_os << "km";
break;
case esvg::distance_inch:
_os << "in";
break;
case esvg::distance_foot:
_os << "ft";
break;
case esvg::distance_element:
_os << "em";
break;
case esvg::distance_ex:
_os << "ex";
break;
case esvg::distance_point:
_os << "pt";
break;
case esvg::distance_pc:
_os << "pc";
break;
}
return _os;
}
etk::Stream& esvg::operator <<(etk::Stream& _os, const esvg::Dimension& _obj) {
_os << _obj.getValue() << _obj.getType();
return _os;
}
namespace etk {
template<> etk::String toString<esvg::Dimension>(const esvg::Dimension& _obj) {
return _obj;
}
template<> etk::UString toUString<esvg::Dimension>(const esvg::Dimension& _obj) {
return etk::toUString(etk::toString(_obj));
}
template<> bool from_string<esvg::Dimension>(esvg::Dimension& _variableRet, const etk::String& _value) {
_variableRet = esvg::Dimension(_value);
return true;
}
template<> bool from_string<esvg::Dimension>(esvg::Dimension& _variableRet, const etk::UString& _value) {
return from_string(_variableRet, etk::toString(_value));
}
};
esvg::Dimension1D::Dimension1D() :
m_data(0.0f),
m_type(esvg::distance_pixel) {
// notinh to do ...
}
esvg::Dimension1D::Dimension1D(float _size, enum esvg::distance _type) :
m_data(0.0f),
m_type(esvg::distance_pixel) {
set(_size, _type);
}
void esvg::Dimension1D::set(etk::String _config) {
m_data = 0;
m_type = esvg::distance_pixel;
enum distance type = esvg::distance_pixel;
if (etk::end_with(_config, "%", false) == true) {
type = esvg::distance_pourcent;
_config.erase(_config.size()-1, 1);
} else if (etk::end_with(_config, "px",false) == true) {
type = esvg::distance_pixel;
_config.erase(_config.size()-2, 2);
} else if (etk::end_with(_config, "ft",false) == true) {
type = esvg::distance_foot;
_config.erase(_config.size()-2, 2);
} else if (etk::end_with(_config, "in",false) == true) {
type = esvg::distance_inch;
_config.erase(_config.size()-2, 2);
} else if (etk::end_with(_config, "km",false) == true) {
type = esvg::distance_kilometer;
_config.erase(_config.size()-2, 2);
} else if (etk::end_with(_config, "mm",false) == true) {
type = esvg::distance_millimeter;
_config.erase(_config.size()-2, 2);
} else if (etk::end_with(_config, "cm",false) == true) {
type = esvg::distance_centimeter;
_config.erase(_config.size()-2, 2);
} else if (etk::end_with(_config, "m",false) == true) {
type = esvg::distance_meter;
_config.erase(_config.size()-1, 1);
} else {
type = esvg::distance_pixel;
ESVG_VERBOSE("default dimention type for: '" << _config << "' ==> pixel");
}
float tmp = etk::string_to_float(_config);
set(tmp, type);
ESVG_VERBOSE(" config dimention : \"" << _config << "\" == > " << *this );
}
esvg::Dimension1D::~Dimension1D() {
// nothing to do ...
}
esvg::Dimension1D::operator etk::String() const {
etk::String str;
str = getValue();
switch(getType()) {
case esvg::distance_pourcent:
str += "%";
break;
case esvg::distance_pixel:
str += "px";
break;
case esvg::distance_meter:
str += "m";
break;
case esvg::distance_centimeter:
str += "cm";
break;
case esvg::distance_millimeter:
str += "mm";
break;
case esvg::distance_kilometer:
str += "km";
break;
case esvg::distance_inch:
str += "in";
break;
case esvg::distance_foot:
str += "ft";
break;
case esvg::distance_element:
str += "em";
break;
case esvg::distance_ex:
str += "ex";
break;
case esvg::distance_point:
str += "pt";
break;
case esvg::distance_pc:
str += "pc";
break;
}
return str;
}
void esvg::Dimension1D::set(float _size, enum esvg::distance _type) {
m_data = _size;
m_type = _type;
switch(_type) {
case esvg::distance_pourcent:
case esvg::distance_pixel:
// nothing to do: Supported ...
break;
case esvg::distance_meter:
case esvg::distance_centimeter:
case esvg::distance_millimeter:
case esvg::distance_kilometer:
case esvg::distance_inch:
case esvg::distance_foot:
case esvg::distance_element:
case esvg::distance_ex:
case esvg::distance_point:
case esvg::distance_pc:
ESVG_ERROR("Does not support other than Px and % type of dimention1D : " << _type << " automaticly convert with {72,72} pixel/inch");
break;
}
}
float esvg::Dimension1D::getPixel(float _upperSize) const {
switch(m_type) {
case esvg::distance_pourcent:
return _upperSize*m_data*0.01f;
case esvg::distance_pixel:
return m_data;
case esvg::distance_meter:
return m_data*meterToMillimeter*basicRatio;
case esvg::distance_centimeter:
return m_data*centimeterToMillimeter*basicRatio;
case esvg::distance_millimeter:
return m_data*basicRatio;
case esvg::distance_kilometer:
return m_data*kilometerToMillimeter*basicRatio;
case esvg::distance_inch:
return m_data*inchToMillimeter*basicRatio;
case esvg::distance_foot:
return m_data*footToMillimeter*basicRatio;
}
return 128.0f;
}
etk::Stream& esvg::operator <<(etk::Stream& _os, const esvg::Dimension1D& _obj) {
_os << _obj.getValue() << _obj.getType();
return _os;
}
namespace etk {
template<> etk::String toString<esvg::Dimension1D>(const esvg::Dimension1D& _obj) {
return _obj;
}
template<> etk::UString toUString<esvg::Dimension1D>(const esvg::Dimension1D& _obj) {
return etk::toUString(etk::toString(_obj));
}
template<> bool from_string<esvg::Dimension1D>(esvg::Dimension1D& _variableRet, const etk::String& _value) {
_variableRet = esvg::Dimension1D(_value);
return true;
}
template<> bool from_string<esvg::Dimension1D>(esvg::Dimension1D& _variableRet, const etk::UString& _value) {
return from_string(_variableRet, etk::toString(_value));
}
};

252
esvg/Dimension.hpp Normal file
View File

@ -0,0 +1,252 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
namespace esvg {
enum distance {
distance_pourcent=0, //!< "%"
distance_pixel, //!< "px"
distance_meter, //!< "m"
distance_centimeter, //!< "cm"
distance_millimeter, //!< "mm"
distance_kilometer, //!< "km"
distance_inch, //!< "in"
distance_foot, //!< "ft"
distance_element, //!< "em"
distance_ex, //!< "ex"
distance_point, //!< "pt"
distance_pc //!< "pc"
};
/**
* @brief in the dimention class we store the data as the more usefull unit (pixel)
* but one case need to be dynamic the %, then when requested in % the register the % value
*/
class Dimension {
private:
vec2 m_data;
enum distance m_type;
public:
/**
* @brief Constructor (default :0,0 mode pixel)
*/
Dimension();
/**
* @brief Constructor
* @param[in] _size Requested dimention
* @param[in] _type Unit of the Dimention
*/
Dimension(const vec2& _size, enum esvg::distance _type=esvg::distance_pixel);
/**
* @brief Constructor
* @param[in] _config dimension configuration.
*/
Dimension(const etk::String& _config) :
m_data(0,0),
m_type(esvg::distance_pixel) {
set(_config);
};
/**
* @brief Constructor
* @param[in] _configX dimension X configuration.
* @param[in] _configY dimension Y configuration.
*/
Dimension(const etk::String& _configX, const etk::String& _configY) :
m_data(0,0),
m_type(esvg::distance_pixel) {
set(_configX, _configY);
};
/**
* @brief Destructor
*/
~Dimension();
/**
* @brief string cast :
*/
operator etk::String() const;
/**
* @brief get the current dimention.
* @return dimention requested.
*/
const vec2& getValue() const {
return m_data;
}
/**
* @breif get the dimension type
* @return the type
*/
enum distance getType() const {
return m_type;
};
/**
* @brief set the current dimention in requested type
* @param[in] _size Dimention to set
* @param[in] _type Type of unit requested.
*/
void set(const vec2& _size, enum distance _type);
public:
/**
* @brief set the current dimention in requested type
* @param[in] _config dimension configuration.
*/
void set(etk::String _config);
/**
* @brief set the current dimention in requested type
* @param[in] _configX dimension X configuration.
* @param[in] _configY dimension Y configuration.
*/
void set(etk::String _configX, etk::String _configY);
public:
/**
* @brief get the current dimention in pixel
* @param[in] _upperSize Size in pixel of the upper value
* @return dimention in Pixel
*/
vec2 getPixel(const vec2& _upperSize) const;
/*****************************************************
* = assigment
*****************************************************/
const Dimension& operator= (const Dimension& _obj ) {
if (this!=&_obj) {
m_data = _obj.m_data;
m_type = _obj.m_type;
}
return *this;
}
/*****************************************************
* == operator
*****************************************************/
bool operator == (const Dimension& _obj) const {
if( m_data == _obj.m_data
&& m_type == _obj.m_type) {
return true;
}
return false;
}
/*****************************************************
* != operator
*****************************************************/
bool operator!= (const Dimension& _obj) const {
if( m_data != _obj.m_data
|| m_type != _obj.m_type) {
return true;
}
return false;
}
};
etk::Stream& operator <<(etk::Stream& _os, enum esvg::distance _obj);
etk::Stream& operator <<(etk::Stream& _os, const esvg::Dimension& _obj);
/**
* @brief in the dimention class we store the data as the more usefull unit (pixel)
* but one case need to be dynamic the %, then when requested in % the register the % value
*/
class Dimension1D {
private:
float m_data;
enum distance m_type;
public:
/**
* @brief Constructor (default :0,0 mode pixel)
*/
Dimension1D();
/**
* @brief Constructor
* @param[in] _size Requested dimention
* @param[in] _type Unit of the Dimention
*/
Dimension1D(float _size, enum esvg::distance _type=esvg::distance_pixel);
/**
* @brief Constructor
* @param[in] _config dimension configuration.
*/
Dimension1D(const etk::String& _config) :
m_data(0.0f),
m_type(esvg::distance_pixel) {
set(_config);
};
/**
* @brief Destructor
*/
~Dimension1D();
/**
* @brief string cast :
*/
operator etk::String() const;
/**
* @brief get the current dimention.
* @return dimention requested.
*/
const float& getValue() const {
return m_data;
}
/**
* @breif get the dimension type
* @return the type
*/
enum distance getType() const {
return m_type;
};
/**
* @brief set the current dimention in requested type
* @param[in] _size Dimention to set
* @param[in] _type Type of unit requested.
*/
void set(float _size, enum distance _type);
public:
/**
* @brief set the current dimention in requested type
* @param[in] _config dimension configuration.
*/
void set(etk::String _config);
public:
/**
* @brief get the current dimention in pixel
* @param[in] _upperSize Size in pixel of the upper value
* @return dimention in Pixel
*/
float getPixel(float _upperSize) const;
/*****************************************************
* = assigment
*****************************************************/
const Dimension1D& operator= (const Dimension1D& _obj ) {
if (this!=&_obj) {
m_data = _obj.m_data;
m_type = _obj.m_type;
}
return *this;
}
/*****************************************************
* == operator
*****************************************************/
bool operator == (const Dimension1D& _obj) const {
if( m_data == _obj.m_data
&& m_type == _obj.m_type) {
return true;
}
return false;
}
/*****************************************************
* != operator
*****************************************************/
bool operator!= (const Dimension1D& _obj) const {
if( m_data != _obj.m_data
|| m_type != _obj.m_type) {
return true;
}
return false;
}
};
etk::Stream& operator <<(etk::Stream& _os, const esvg::Dimension1D& _obj);
}

172
esvg/Ellipse.cpp Normal file
View File

@ -0,0 +1,172 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/debug.hpp>
#include <esvg/Ellipse.hpp>
#include <esvg/render/Path.hpp>
#include <esvg/render/Weight.hpp>
esvg::Ellipse::Ellipse(PaintState _parentPaintState) : esvg::Base(_parentPaintState) {
}
esvg::Ellipse::~Ellipse() {
}
bool esvg::Ellipse::parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax) {
if (_element.exist() == false) {
return false;
}
parseTransform(_element);
parsePaintAttr(_element);
// add the property of the parrent modifications ...
m_transformMatrix *= _parentTrans;
m_c.setValue(0,0);
m_r.setValue(0,0);
etk::String content = _element.attributes["cx"];
if (content.size()!=0) {
m_c.setX(parseLength(content));
}
content = _element.attributes["cy"];
if (content.size()!=0) {
m_c.setY(parseLength(content));
}
content = _element.attributes["rx"];
if (content.size()!=0) {
m_r.setX(parseLength(content));
} else {
ESVG_ERROR("(l "<<_element.getPos()<<") Ellipse \"rx\" is not present");
return false;
}
content = _element.attributes["ry"];
if (content.size()!=0) {
m_r.setY(parseLength(content));
} else {
ESVG_ERROR("(l "<<_element.getPos()<<") Ellipse \"ry\" is not present");
return false;
}
_sizeMax.setValue(m_c.x() + m_r.x(), m_c.y() + m_r.y());
return true;
}
void esvg::Ellipse::display(int32_t _spacing) {
ESVG_DEBUG(spacingDist(_spacing) << "Ellipse c=" << m_c << " r=" << m_r);
}
esvg::render::Path esvg::Ellipse::createPath() {
esvg::render::Path out;
out.clear();
out.moveTo(false, m_c + vec2(m_r.x(), 0.0f));
out.curveTo(false,
m_c + vec2(m_r.x(), m_r.y()*esvg::kappa90),
m_c + vec2(m_r.x()*esvg::kappa90, m_r.y()),
m_c + vec2(0.0f, m_r.y()));
out.curveTo(false,
m_c + vec2(-m_r.x()*esvg::kappa90, m_r.y()),
m_c + vec2(-m_r.x(), m_r.y()*esvg::kappa90),
m_c + vec2(-m_r.x(), 0.0f));
out.curveTo(false,
m_c + vec2(-m_r.x(), -m_r.y()*esvg::kappa90),
m_c + vec2(-m_r.x()*esvg::kappa90, -m_r.y()),
m_c + vec2(0.0f, -m_r.y()));
out.curveTo(false,
m_c + vec2(m_r.x()*esvg::kappa90, -m_r.y()),
m_c + vec2(m_r.x(), -m_r.y()*esvg::kappa90),
m_c + vec2(m_r.x(), 0.0f));
out.close();
return out;
}
void esvg::Ellipse::draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level) {
ESVG_VERBOSE(spacingDist(_level) << "DRAW esvg::Ellipse");
if ( m_r.x()<=0.0f
|| m_r.y()<=0.0f) {
ESVG_VERBOSE(spacingDist(_level+1) << "Too small radius" << m_r);
return;
}
esvg::render::Path listElement = createPath();
mat2x3 mtx = m_transformMatrix;
mtx *= _basicTrans;
esvg::render::PointList listPoints;
listPoints = listElement.generateListPoints(_level,
_myRenderer.getInterpolationRecurtionMax(),
_myRenderer.getInterpolationThreshold());
//listPoints.applyMatrix(mtx);
esvg::render::SegmentList listSegmentFill;
esvg::render::SegmentList listSegmentStroke;
esvg::render::Weight tmpFill;
esvg::render::Weight tmpStroke;
ememory::SharedPtr<esvg::render::DynamicColor> colorFill = esvg::render::createColor(m_paint.fill, mtx);
ememory::SharedPtr<esvg::render::DynamicColor> colorStroke;
if (m_paint.strokeWidth > 0.0f) {
colorStroke = esvg::render::createColor(m_paint.stroke, mtx);
}
// Check if we need to display background
if (colorFill != null) {
listSegmentFill.createSegmentList(listPoints);
colorFill->setViewPort(listSegmentFill.getViewPort());
listSegmentFill.applyMatrix(mtx);
// now, traverse the scanlines and find the intersections on each scanline, use non-zero rule
tmpFill.generate(_myRenderer.getSize(),
_myRenderer.getNumberSubScanLine(),
listSegmentFill);
}
// check if we need to display stroke:
if (colorStroke != null) {
listSegmentStroke.createSegmentListStroke(listPoints,
m_paint.strokeWidth,
m_paint.lineCap,
m_paint.lineJoin,
m_paint.miterLimit);
colorStroke->setViewPort(listSegmentStroke.getViewPort());
listSegmentStroke.applyMatrix(mtx);
// now, traverse the scanlines and find the intersections on each scanline, use non-zero rule
tmpStroke.generate(_myRenderer.getSize(),
_myRenderer.getNumberSubScanLine(),
listSegmentStroke);
}
// add on images:
_myRenderer.print(tmpFill,
colorFill,
tmpStroke,
colorStroke,
m_paint.opacity);
#ifdef DEBUG
_myRenderer.addDebugSegment(listSegmentFill);
_myRenderer.addDebugSegment(listSegmentStroke);
#endif
}
void esvg::Ellipse::drawShapePoints(etk::Vector<etk::Vector<vec2>>& _out,
int32_t _recurtionMax,
float _threshold,
mat2x3& _basicTrans,
int32_t _level) {
ESVG_VERBOSE(spacingDist(_level) << "DRAW Shape esvg::Ellipse");
esvg::render::Path listElement = createPath();
mat2x3 mtx = m_transformMatrix;
mtx *= _basicTrans;
esvg::render::PointList listPoints;
listPoints = listElement.generateListPoints(_level, _recurtionMax, _threshold);
listPoints.applyMatrix(mtx);
for (auto &it : listPoints.m_data) {
etk::Vector<vec2> listPoint;
for (auto &itDot : it) {
listPoint.pushBack(itDot.m_pos);
}
_out.pushBack(listPoint);
}
}

30
esvg/Ellipse.hpp Normal file
View File

@ -0,0 +1,30 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <esvg/Base.hpp>
namespace esvg {
class Ellipse : public esvg::Base {
private:
vec2 m_c; //!< Center property of the ellipse
vec2 m_r; //!< Radius property of the ellipse
public:
Ellipse(PaintState _parentPaintState);
~Ellipse();
bool parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax) override;
void display(int32_t _spacing) override;
void draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level) override;
void drawShapePoints(etk::Vector<etk::Vector<vec2>>& _out,
int32_t _recurtionMax,
float _threshold,
mat2x3& _basicTrans,
int32_t _level=1) override;
private:
esvg::render::Path createPath();
};
}

129
esvg/Group.cpp Normal file
View File

@ -0,0 +1,129 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/debug.hpp>
#include <esvg/Group.hpp>
#include <etk/types.hpp>
#include <esvg/Base.hpp>
#include <esvg/Circle.hpp>
#include <esvg/Ellipse.hpp>
#include <esvg/Line.hpp>
#include <esvg/Path.hpp>
#include <esvg/Polygon.hpp>
#include <esvg/Polyline.hpp>
#include <esvg/Rectangle.hpp>
#include <esvg/Text.hpp>
#include <esvg/Group.hpp>
esvg::Group::Group(PaintState _parentPaintState) : esvg::Base(_parentPaintState) {
}
esvg::Group::~Group() {
}
bool esvg::Group::parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax) {
if (_element.exist() == false) {
return false;
}
// parse ...
vec2 pos(0,0);
vec2 size(0,0);
parseTransform(_element);
parsePosition(_element, pos, size);
parsePaintAttr(_element);
ESVG_VERBOSE("parsed G1. trans : " << m_transformMatrix);
// add the property of the parrent modifications ...
m_transformMatrix *= _parentTrans;
ESVG_VERBOSE("parsed G2. trans : " << m_transformMatrix);
_sizeMax.setValue(0,0);
vec2 tmpPos(0,0);
// parse all sub node :
for(const auto it : _element.nodes) {
exml::Element child = it.toElement();
if (child.exist() == false) {
// can be a comment ...
continue;
}
ememory::SharedPtr<esvg::Base> elementParser;
if (child.getValue() == "g") {
elementParser = ememory::makeShared<esvg::Group>(m_paint);
} else if (child.getValue() == "a") {
// TODO ...
} else if (child.getValue() == "path") {
elementParser = ememory::makeShared<esvg::Path>(m_paint);
} else if (child.getValue() == "rect") {
elementParser = ememory::makeShared<esvg::Rectangle>(m_paint);
} else if (child.getValue() == "circle") {
elementParser = ememory::makeShared<esvg::Circle>(m_paint);
} else if (child.getValue() == "ellipse") {
elementParser = ememory::makeShared<esvg::Ellipse>(m_paint);
} else if (child.getValue() == "line") {
elementParser = ememory::makeShared<esvg::Line>(m_paint);
} else if (child.getValue() == "polyline") {
elementParser = ememory::makeShared<esvg::Polyline>(m_paint);
} else if (child.getValue() == "polygon") {
elementParser = ememory::makeShared<esvg::Polygon>(m_paint);
} else if (child.getValue() == "text") {
elementParser = ememory::makeShared<esvg::Text>(m_paint);
} else {
ESVG_ERROR("(l " << child.getPos() << ") node not suported : '" << child.getValue() << "' must be [g,a,path,rect,circle,ellipse,line,polyline,polygon,text]");
}
if (elementParser == null) {
ESVG_ERROR("(l " << child.getPos() << ") error on node: '" << child.getValue() << "' allocation error or not supported ...");
continue;
}
if (elementParser->parseXML(child, m_transformMatrix, tmpPos) == false) {
ESVG_ERROR("(l " << child.getPos() << ") error on node: '" << child.getValue() << "' Sub Parsing ERROR");
elementParser.reset();
continue;
}
_sizeMax.setValue(etk::max(_sizeMax.x(), tmpPos.x()),
etk::max(_sizeMax.y(), tmpPos.y()));
// add element in the system
m_subElementList.pushBack(elementParser);
}
return true;
}
void esvg::Group::display(int32_t _spacing) {
ESVG_DEBUG(spacingDist(_spacing) << "Group (START) fill=" << m_paint.fill.first << "/" << m_paint.fill.second
<< " stroke=" << m_paint.stroke.first << "/" << m_paint.stroke.second
<< " stroke-width=" << m_paint.strokeWidth );
for (auto &it : m_subElementList) {
if (it != null) {
it->display(_spacing+1);
}
}
ESVG_DEBUG(spacingDist(_spacing) << "Group (STOP)");
}
void esvg::Group::draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level) {
ESVG_VERBOSE(spacingDist(_level) << "DRAW esvg::group");
for (auto &it : m_subElementList) {
if (it != null) {
it->draw(_myRenderer, _basicTrans, _level+1);
}
}
}
void esvg::Group::drawShapePoints(etk::Vector<etk::Vector<vec2>>& _out,
int32_t _recurtionMax,
float _threshold,
mat2x3& _basicTrans,
int32_t _level) {
ESVG_VERBOSE(spacingDist(_level) << "DRAW shape esvg::group");
for (auto &it : m_subElementList) {
if (it != null) {
it->drawShapePoints(_out, _recurtionMax, _threshold, _basicTrans, _level+1);
}
}
}

28
esvg/Group.hpp Normal file
View File

@ -0,0 +1,28 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <esvg/Base.hpp>
#include <etk/Vector.hpp>
namespace esvg {
class Group : public esvg::Base {
private:
etk::Vector<ememory::SharedPtr<esvg::Base>> m_subElementList; //!< sub elements ...
public:
Group(PaintState _parentPaintState);
~Group();
bool parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax) override;
void display(int32_t spacing) override;
void draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level) override;
void drawShapePoints(etk::Vector<etk::Vector<vec2>>& _out,
int32_t _recurtionMax,
float _threshold,
mat2x3& _basicTrans,
int32_t _level=1) override;
};
}

139
esvg/Line.cpp Normal file
View File

@ -0,0 +1,139 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/debug.hpp>
#include <esvg/Line.hpp>
#include <esvg/render/Path.hpp>
#include <esvg/render/Weight.hpp>
esvg::Line::Line(PaintState _parentPaintState) : esvg::Base(_parentPaintState) {
m_startPos.setValue(0,0);
m_stopPos.setValue(0,0);
}
esvg::Line::~Line() {
}
bool esvg::Line::parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax) {
// line must have a minimum size...
m_paint.strokeWidth = 1;
if (_element.exist() == false) {
return false;
}
parseTransform(_element);
parsePaintAttr(_element);
// add the property of the parrent modifications ...
m_transformMatrix *= _parentTrans;
etk::String content = _element.attributes["x1"];
if (content.size() != 0) {
m_startPos.setX(parseLength(content));
}
content = _element.attributes["y1"];
if (content.size() != 0) {
m_startPos.setY(parseLength(content));
}
content = _element.attributes["x2"];
if (content.size() != 0) {
m_stopPos.setX(parseLength(content));
}
content = _element.attributes["y2"];
if (content.size() != 0) {
m_stopPos.setY(parseLength(content));
}
_sizeMax.setValue(etk::max(m_startPos.x(), m_stopPos.x()),
etk::max(m_startPos.y(), m_stopPos.y()));
return true;
}
void esvg::Line::display(int32_t _spacing) {
ESVG_DEBUG(spacingDist(_spacing) << "Line " << m_startPos << " to " << m_stopPos);
}
esvg::render::Path esvg::Line::createPath() {
esvg::render::Path out;
out.clear();
out.moveTo(false, m_startPos);
out.lineTo(false, m_stopPos);
out.stop();
return out;
}
void esvg::Line::draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level) {
ESVG_VERBOSE(spacingDist(_level) << "DRAW esvg::Line");
esvg::render::Path listElement = createPath();
mat2x3 mtx = m_transformMatrix;
mtx *= _basicTrans;
esvg::render::PointList listPoints;
listPoints = listElement.generateListPoints(_level,
_myRenderer.getInterpolationRecurtionMax(),
_myRenderer.getInterpolationThreshold());
//listPoints.applyMatrix(mtx);
esvg::render::SegmentList listSegmentFill;
esvg::render::SegmentList listSegmentStroke;
esvg::render::Weight tmpFill;
esvg::render::Weight tmpStroke;
ememory::SharedPtr<esvg::render::DynamicColor> colorFill = esvg::render::createColor(m_paint.fill, mtx);
ememory::SharedPtr<esvg::render::DynamicColor> colorStroke;
if (m_paint.strokeWidth > 0.0f) {
colorStroke = esvg::render::createColor(m_paint.stroke, mtx);
}
// Check if we need to display background
// No background ...
// check if we need to display stroke:
if (colorStroke != null) {
listSegmentStroke.createSegmentListStroke(listPoints,
m_paint.strokeWidth,
m_paint.lineCap,
m_paint.lineJoin,
m_paint.miterLimit);
colorStroke->setViewPort(listSegmentStroke.getViewPort());
listSegmentStroke.applyMatrix(mtx);
// now, traverse the scanlines and find the intersections on each scanline, use non-zero rule
tmpStroke.generate(_myRenderer.getSize(),
_myRenderer.getNumberSubScanLine(),
listSegmentStroke);
}
// add on images:
_myRenderer.print(tmpFill,
colorFill,
tmpStroke,
colorStroke,
m_paint.opacity);
#ifdef DEBUG
_myRenderer.addDebugSegment(listSegmentFill);
_myRenderer.addDebugSegment(listSegmentStroke);
_myRenderer.addDebugSegment(listElement.m_debugInformation);
#endif
}
void esvg::Line::drawShapePoints(etk::Vector<etk::Vector<vec2>>& _out,
int32_t _recurtionMax,
float _threshold,
mat2x3& _basicTrans,
int32_t _level) {
ESVG_VERBOSE(spacingDist(_level) << "DRAW Shape esvg::Line");
esvg::render::Path listElement = createPath();
mat2x3 mtx = m_transformMatrix;
mtx *= _basicTrans;
esvg::render::PointList listPoints;
listPoints = listElement.generateListPoints(_level, _recurtionMax, _threshold);
listPoints.applyMatrix(mtx);
for (auto &it : listPoints.m_data) {
etk::Vector<vec2> listPoint;
for (auto &itDot : it) {
listPoint.pushBack(itDot.m_pos);
}
_out.pushBack(listPoint);
}
}

30
esvg/Line.hpp Normal file
View File

@ -0,0 +1,30 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <esvg/Base.hpp>
namespace esvg {
class Line : public esvg::Base {
private:
vec2 m_startPos; //!< Start line position
vec2 m_stopPos; //!< Stop line position
public:
Line(PaintState _parentPaintState);
~Line();
bool parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax) override;
void display(int32_t _spacing) override;
void draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level) override;
void drawShapePoints(etk::Vector<etk::Vector<vec2>>& _out,
int32_t _recurtionMax,
float _threshold,
mat2x3& _basicTrans,
int32_t _level=1) override;
private:
esvg::render::Path createPath();
};
}

176
esvg/LinearGradient.cpp Normal file
View File

@ -0,0 +1,176 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/debug.hpp>
#include <esvg/LinearGradient.hpp>
#include <esvg/RadialGradient.hpp>
#include <esvg/render/Path.hpp>
#include <esvg/render/Weight.hpp>
#include <esvg/esvg.hpp>
esvg::LinearGradient::LinearGradient(PaintState _parentPaintState) :
esvg::Base(_parentPaintState),
m_pos1(vec2(50,50), esvg::distance_pourcent),
m_pos2(vec2(50,50), esvg::distance_pourcent),
m_unit(gradientUnits_objectBoundingBox),
m_spread(spreadMethod_pad) {
}
esvg::LinearGradient::~LinearGradient() {
}
bool esvg::LinearGradient::parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax) {
// line must have a minimum size...
//m_paint.strokeWidth = 1;
if (_element.exist() == false) {
return false;
}
// ---------------- get unique ID ----------------
m_id = _element.attributes["id"];
//parseTransform(_element);
//parsePaintAttr(_element);
// add the property of the parrent modifications ...
m_transformMatrix *= _parentTrans;
etk::String contentX = _element.attributes["x1"];
etk::String contentY = _element.attributes["y1"];
if ( contentX != ""
&& contentY != "") {
m_pos1.set(contentX, contentY);
}
contentX = _element.attributes["x2"];
contentY = _element.attributes["y2"];
if ( contentX != ""
&& contentY != "") {
m_pos2.set(contentX, contentY);
}
contentX = _element.attributes["gradientUnits"];
if (contentX == "userSpaceOnUse") {
m_unit = gradientUnits_userSpaceOnUse;
} else {
m_unit = gradientUnits_objectBoundingBox;
if ( contentX.size() != 0
&& contentX != "objectBoundingBox") {
ESVG_ERROR("Parsing error of 'gradientUnits' ==> not suported value: '" << contentX << "' not in : {userSpaceOnUse/objectBoundingBox} use objectBoundingBox");
}
}
contentX = _element.attributes["spreadMethod"];
if (contentX == "reflect") {
m_spread = spreadMethod_reflect;
} else if (contentX == "repeat") {
m_spread = spreadMethod_repeat;
} else {
m_spread = spreadMethod_pad;
if ( contentX.size() != 0
&& contentX != "pad") {
ESVG_ERROR("Parsing error of 'spreadMethod' ==> not suported value: '" << contentX << "' not in : {reflect/repeate/pad} use pad");
}
}
// note: xlink:href is incompatible with subNode "stop"
m_href = _element.attributes["xlink:href"];
if (m_href.size() != 0) {
m_href = etk::String(m_href.begin()+1, m_href.end());
}
// parse all sub node :
for(const auto it : _element.nodes) {
exml::Element child = it.toElement();
if (child.exist() == false) {
// can be a comment ...
continue;
}
if (child.getValue() == "stop") {
float offset = 100;
etk::Color<float,4> stopColor = etk::color::none;
etk::String content = child.attributes["offset"];
if (content.size()!=0) {
etk::Pair<float, enum esvg::distance> tmp = parseLength2(content);
if (tmp.second == esvg::distance_pixel) {
// special case ==> all time % then no type define ==> % in [0.0 .. 1.0]
offset = tmp.first*100.0f;
} else if (tmp.second != esvg::distance_pourcent) {
ESVG_ERROR("offset : " << content << " res=" << tmp.first << "," << tmp.second << " Not support other than pourcent %");
} else {
offset = tmp.first;
}
}
content = child.attributes["stop-color"];
if (content.size()!=0) {
stopColor = parseColor(content).first;
ESVG_VERBOSE(" color : '" << content << "' == > " << stopColor);
}
content = child.attributes["stop-opacity"];
if (content.size()!=0) {
float opacity = parseLength(content);
opacity = etk::avg(0.0f, opacity, 1.0f);
stopColor.setA(opacity);
ESVG_VERBOSE(" opacity : '" << content << "' == > " << stopColor);
}
m_data.pushBack(etk::Pair<float, etk::Color<float,4>>(offset, stopColor));
} else {
ESVG_ERROR("(l " << child.getPos() << ") node not suported : '" << child.getValue() << "' must be [stop]");
}
}
if (m_data.size() != 0) {
if (m_href != "") {
ESVG_ERROR("(l " << _element.getPos() << ") node can not have an xlink:href element with sub node named: stop ==> removing href");
m_href = "";
}
}
return true;
}
void esvg::LinearGradient::display(int32_t _spacing) {
ESVG_DEBUG(spacingDist(_spacing) << "LinearGradient " << m_pos1 << " to " << m_pos2);
for (auto &it : m_data) {
ESVG_DEBUG(spacingDist(_spacing+1) << "STOP: offset=" << it.first << " color=" << it.second);
}
}
void esvg::LinearGradient::draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level) {
ESVG_VERBOSE(spacingDist(_level) << "DRAW esvg::LinearGradient");
}
const esvg::Dimension& esvg::LinearGradient::getPosition1() {
return m_pos1;
}
const esvg::Dimension& esvg::LinearGradient::getPosition2() {
return m_pos2;
}
const etk::Vector<etk::Pair<float, etk::Color<float,4>>>& esvg::LinearGradient::getColors(esvg::Document* _document) {
if (m_href == "") {
return m_data;
}
if (_document == null) {
ESVG_ERROR("Get null input for document");
return m_data;
}
ememory::SharedPtr<esvg::Base> base = _document->getReference(m_href);
if (base == null) {
ESVG_ERROR("Can not get base : '" << m_href << "'");
return m_data;
}
ememory::SharedPtr<esvg::RadialGradient> gradientR = ememory::dynamicPointerCast<esvg::RadialGradient>(base);
if (gradientR == null) {
ememory::SharedPtr<esvg::LinearGradient> gradientL = ememory::dynamicPointerCast<esvg::LinearGradient>(base);
if (gradientL == null) {
ESVG_ERROR("Can not cast in a linear/radial gradient: '" << m_href << "' ==> wrong type");
return m_data;
}
return gradientL->getColors(_document);
}
return gradientR->getColors(_document);
}

36
esvg/LinearGradient.hpp Normal file
View File

@ -0,0 +1,36 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <esvg/Base.hpp>
#include <esvg/gradientUnits.hpp>
#include <esvg/spreadMethod.hpp>
namespace esvg {
class Document;
class LinearGradient : public esvg::Base {
private:
esvg::Dimension m_pos1; //!< gradient position x1 y1
esvg::Dimension m_pos2; //!< gradient position x2 y2
public:
enum gradientUnits m_unit;
enum spreadMethod m_spread;
private:
etk::String m_href; //!< in case of using a single gradient in multiple gradient, the gradient is store in an other element...
etk::Vector<etk::Pair<float, etk::Color<float,4>>> m_data; //!< incompatible with href
public:
LinearGradient(PaintState _parentPaintState);
~LinearGradient();
virtual bool parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax);
virtual void display(int32_t _spacing);
virtual void draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level);
public:
const esvg::Dimension& getPosition1();
const esvg::Dimension& getPosition2();
const etk::Vector<etk::Pair<float, etk::Color<float,4>>>& getColors(esvg::Document* _document);
};
}

349
esvg/Path.cpp Normal file
View File

@ -0,0 +1,349 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/debug.hpp>
#include <esvg/Path.hpp>
#include <esvg/render/PointList.hpp>
#include <esvg/render/Weight.hpp>
esvg::Path::Path(PaintState _parentPaintState) : esvg::Base(_parentPaintState) {
}
esvg::Path::~Path() {
}
// return the next char position ... (after 'X' or NULL)
const char * extractCmd(const char* _input, char& _cmd, etk::Vector<float>& _outputList) {
if (*_input == '\0') {
return null;
}
_outputList.clear();
_cmd = '\0';
const char * outputPointer = null;
if (!( ( _input[0] <= 'Z'
&& _input[0] >= 'A')
|| ( _input[0] <= 'z'
&& _input[0] >= 'a') ) ) {
ESVG_ERROR("Error in the SVG Path : \"" << _input << "\"");
return null;
}
_cmd = _input[0];
ESVG_VERBOSE("Find command : " << _cmd);
if (_input[1] == '\0') {
return &_input[1];
}
int32_t iii=1;
// extract every float separated by a ' ' or a ','
float element;
char spacer[10];
int32_t nbElementRead;
while( sscanf(&_input[iii], "%1[, ]%f%n", spacer, &element, &nbElementRead) == 2
|| sscanf(&_input[iii], "%f%n", &element, &nbElementRead) == 1) {
ESVG_VERBOSE("Find element : " << element);
_outputList.pushBack(element);
iii += nbElementRead;
}
outputPointer = &_input[iii];
while(*outputPointer!= '\0' && *outputPointer == ' ') {
outputPointer++;
}
//outputPointer++;
return outputPointer;
}
etk::String cleanBadSpaces(const etk::String& _input) {
etk::String out;
bool haveSpace = false;
for (auto &it : _input) {
if ( it == ' '
|| it == '\t'
|| it == '\t'
|| it == '\r') {
haveSpace = true;
} else {
if (haveSpace == true) {
haveSpace = false;
out += ' ';
}
out += it;
}
}
return out;
}
bool esvg::Path::parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax) {
if (_element.exist() == false) {
return false;
}
parseTransform(_element);
parsePaintAttr(_element);
// add the property of the parrent modifications ...
m_transformMatrix *= _parentTrans;
etk::String elementXML1 = _element.attributes["d"];
if (elementXML1.size() == 0) {
ESVG_WARNING("(l "<<_element.getPos()<<") path: missing 'd' attribute or empty");
return false;
}
ESVG_VERBOSE("Parse Path : \"" << elementXML1 << "\"");
char command;
etk::Vector<float> listDot;
elementXML1 = cleanBadSpaces(elementXML1);
const char* elementXML = elementXML1.c_str();
for( const char *sss=extractCmd(elementXML, command, listDot);
sss != null;
sss=extractCmd(sss, command, listDot) ) {
bool relative = false;
switch(command) {
case 'm': // Move to (relative)
relative = true;
case 'M': // Move to (absolute)
// 2 Elements ...
if(listDot.size()%2 != 0) {
ESVG_WARNING("the PATH command "<< command << " has not the good number of element = " << listDot.size() );
break;
}
if (listDot.size() >= 2) {
m_listElement.moveTo(relative,
vec2(listDot[0], listDot[1]));
}
for (size_t iii=2; iii<listDot.size(); iii+=2) {
m_listElement.lineTo(relative,
vec2(listDot[iii], listDot[iii+1]));
}
break;
case 'l': // Line to (relative)
relative = true;
case 'L': // Line to (absolute)
// 2 Elements ...
if(listDot.size()%2 != 0) {
ESVG_WARNING("the PATH command "<< command << " has not the good number of element = " << listDot.size() );
break;
}
for (size_t iii=0; iii<listDot.size(); iii+=2) {
m_listElement.lineTo(relative,
vec2(listDot[iii], listDot[iii+1]));
}
break;
case 'v': // Vertical Line to (relative)
relative = true;
case 'V': // Vertical Line to (absolute)
// 1 Element ...
if(listDot.size() == 0) {
ESVG_WARNING("the PATH command "<< command << " has not the good number of element = " << listDot.size() );
break;
}
for (size_t iii=0; iii<listDot.size(); iii+=1) {
m_listElement.lineToV(relative,
listDot[iii]);
}
break;
case 'h': // Horizantal Line to (relative)
relative = true;
case 'H': // Horizantal Line to (absolute)
// 1 Element ...
if (listDot.size() == 0) {
ESVG_WARNING("the PATH command "<< command << " has not the good number of element = " << listDot.size() );
break;
}
for (size_t iii=0; iii<listDot.size(); iii+=1) {
m_listElement.lineToH(relative,
listDot[iii]);
}
break;
case 'q': // Quadratic Bezier curve (relative)
relative = true;
case 'Q': // Quadratic Bezier curve (absolute)
// 4 Elements ...
if (listDot.size()%4 != 0) {
ESVG_WARNING("the PATH command "<< command << " has not the good number of element = " << listDot.size() );
break;
}
for (size_t iii=0; iii<listDot.size(); iii+=4) {
m_listElement.bezierCurveTo(relative,
vec2(listDot[iii],listDot[iii+1]),
vec2(listDot[iii+2],listDot[iii+3]));
}
break;
case 't': // smooth quadratic Bezier curve to (relative)
relative = true;
case 'T': // smooth quadratic Bezier curve to (absolute)
// 2 Elements ...
if (listDot.size()%2 != 0) {
ESVG_WARNING("the PATH command "<< command << " has not the good number of element = " << listDot.size() );
break;
}
for (size_t iii=0; iii<listDot.size(); iii+=2) {
m_listElement.bezierSmoothCurveTo(relative,
vec2(listDot[iii],listDot[iii+1]));
}
break;
case 'c': // curve to (relative)
relative = true;
case 'C': // curve to (absolute)
// 6 Elements ...
if (listDot.size()%6 != 0) {
ESVG_WARNING("the PATH command "<< command << " has not the good number of element = " << listDot.size() );
break;
}
for (size_t iii=0; iii<listDot.size(); iii+=6) {
m_listElement.curveTo(relative,
vec2(listDot[iii],listDot[iii+1]),
vec2(listDot[iii+2],listDot[iii+3]),
vec2(listDot[iii+4],listDot[iii+5]));
}
break;
case 's': // smooth curve to (relative)
relative = true;
case 'S': // smooth curve to (absolute)
// 4 Elements ...
if (listDot.size()%4 != 0) {
ESVG_WARNING("the PATH command "<< command << " has not the good number of element = " << listDot.size() );
break;
}
for (size_t iii=0; iii<listDot.size(); iii+=4) {
m_listElement.smoothCurveTo(relative,
vec2(listDot[iii],listDot[iii+1]),
vec2(listDot[iii+2],listDot[iii+3]));
}
break;
case 'a': // elliptical Arc (relative)
relative = true;
case 'A': // elliptical Arc (absolute)
// 7 Elements ...
if (listDot.size()%7 != 0) {
ESVG_WARNING("the PATH command "<< command << " has not the good number of element = " << listDot.size() );
break;
}
for (size_t iii=0; iii<listDot.size(); iii+=7) {
bool largeArcFlag = true;
bool sweepFlag = true;
if (listDot[iii+3] == 0.0f) {
largeArcFlag = false;
}
if (listDot[iii+4] == 0.0f) {
sweepFlag = false;
}
m_listElement.ellipticTo(relative,
vec2(listDot[iii], listDot[iii+1]),
listDot[iii+2],
largeArcFlag,
sweepFlag,
vec2(listDot[iii+5], listDot[iii+6]) );
}
break;
case 'z': // closepath (relative)
relative = true;
case 'Z': // closepath (absolute)
// 0 Element ...
if (listDot.size() != 0) {
ESVG_WARNING("the PATH command "<< command << " has not the good number of element = " << listDot.size() );
break;
}
m_listElement.close(relative);
break;
default:
ESVG_ERROR ("Unknow error : \"" << command << "\"");
}
}
return true;
}
void esvg::Path::display(int32_t _spacing) {
m_listElement.display(_spacing);
}
void esvg::Path::draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level) {
ESVG_VERBOSE(spacingDist(_level) << "DRAW esvg::Path");
mat2x3 mtx = m_transformMatrix;
mtx *= _basicTrans;
esvg::render::PointList listPoints;
listPoints = m_listElement.generateListPoints(_level,
_myRenderer.getInterpolationRecurtionMax(),
_myRenderer.getInterpolationThreshold());
//listPoints.applyMatrix(mtx);
esvg::render::SegmentList listSegmentFill;
esvg::render::SegmentList listSegmentStroke;
esvg::render::Weight tmpFill;
esvg::render::Weight tmpStroke;
ememory::SharedPtr<esvg::render::DynamicColor> colorFill = esvg::render::createColor(m_paint.fill, mtx);
ememory::SharedPtr<esvg::render::DynamicColor> colorStroke;
if (m_paint.strokeWidth > 0.0f) {
colorStroke = esvg::render::createColor(m_paint.stroke, mtx);
}
// Check if we need to display background
if (colorFill != null) {
listSegmentFill.createSegmentList(listPoints);
colorFill->setViewPort(listSegmentFill.getViewPort());
listSegmentFill.applyMatrix(mtx);
// now, traverse the scanlines and find the intersections on each scanline, use non-zero rule
tmpFill.generate(_myRenderer.getSize(), _myRenderer.getNumberSubScanLine(), listSegmentFill);
}
// check if we need to display stroke:
if (colorStroke != null) {
listSegmentStroke.createSegmentListStroke(listPoints,
m_paint.strokeWidth,
m_paint.lineCap,
m_paint.lineJoin,
m_paint.miterLimit);
colorStroke->setViewPort(listSegmentStroke.getViewPort());
listSegmentStroke.applyMatrix(mtx);
// now, traverse the scanlines and find the intersections on each scanline, use non-zero rule
tmpStroke.generate(_myRenderer.getSize(), _myRenderer.getNumberSubScanLine(), listSegmentStroke);
}
// add on images:
_myRenderer.print(tmpFill,
colorFill,
tmpStroke,
colorStroke,
m_paint.opacity);
#ifdef DEBUG
_myRenderer.addDebugSegment(listSegmentFill);
_myRenderer.addDebugSegment(listSegmentStroke);
m_listElement.m_debugInformation.applyMatrix(mtx);
_myRenderer.addDebugSegment(m_listElement.m_debugInformation);
#endif
}
void esvg::Path::drawShapePoints(etk::Vector<etk::Vector<vec2>>& _out,
int32_t _recurtionMax,
float _threshold,
mat2x3& _basicTrans,
int32_t _level) {
ESVG_VERBOSE(spacingDist(_level) << "DRAW Shape esvg::Path");
mat2x3 mtx = m_transformMatrix;
mtx *= _basicTrans;
esvg::render::PointList listPoints;
listPoints = m_listElement.generateListPoints(_level, _recurtionMax, _threshold);
listPoints.applyMatrix(mtx);
for (auto &it : listPoints.m_data) {
etk::Vector<vec2> listPoint;
for (auto &itDot : it) {
listPoint.pushBack(itDot.m_pos);
}
_out.pushBack(listPoint);
}
}

28
esvg/Path.hpp Normal file
View File

@ -0,0 +1,28 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <esvg/Base.hpp>
#include <esvg/render/Path.hpp>
namespace esvg {
class Path : public esvg::Base {
public:
esvg::render::Path m_listElement;
public:
Path(PaintState _parentPaintState);
~Path();
bool parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax) override;
void display(int32_t _spacing) override;
void draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level) override;
void drawShapePoints(etk::Vector<etk::Vector<vec2>>& _out,
int32_t _recurtionMax,
float _threshold,
mat2x3& _basicTrans,
int32_t _level=1) override;
};
}

153
esvg/Polygon.cpp Normal file
View File

@ -0,0 +1,153 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/debug.hpp>
#include <esvg/Polygon.hpp>
#include <esvg/render/Path.hpp>
#include <esvg/render/Weight.hpp>
esvg::Polygon::Polygon(PaintState parentPaintState) : esvg::Base(parentPaintState) {
}
esvg::Polygon::~Polygon() {
}
bool esvg::Polygon::parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax) {
if (_element.exist() == false) {
return false;
}
parseTransform(_element);
parsePaintAttr(_element);
ESVG_VERBOSE("parsed P1. trans: " << m_transformMatrix);
// add the property of the parrent modifications ...
m_transformMatrix *= _parentTrans;
ESVG_VERBOSE("parsed P2. trans: " << m_transformMatrix);
const etk::String sss1 = _element.attributes["points"];
if (sss1.size() == 0) {
ESVG_ERROR("(l "/*<<_element->Pos()*/<<") polygon: missing points attribute");
return false;
}
const char * sss = sss1.c_str();
_sizeMax.setValue(0,0);
ESVG_VERBOSE("Parse polygon : \"" << sss << "\"");
while ('\0' != sss[0]) {
vec2 pos(0,0);
int32_t n;
if (sscanf(sss, "%f,%f%n", &pos.m_floats[0], &pos.m_floats[1], &n) == 2) {
m_listPoint.pushBack(pos);
sss += n;
_sizeMax.setValue(etk::max(_sizeMax.x(), pos.x()),
etk::max(_sizeMax.y(), pos.y()));
if(sss[0] == ' ' || sss[0] == ',') {
sss++;
}
} else {
break;
}
}
return true;
}
void esvg::Polygon::display(int32_t _spacing) {
ESVG_DEBUG(spacingDist(_spacing) << "Polygon nbPoint=" << m_listPoint.size());
}
esvg::render::Path esvg::Polygon::createPath() {
esvg::render::Path out;
out.moveTo(false, m_listPoint[0]);
for(size_t iii=1; iii< m_listPoint.size(); iii++) {
out.lineTo(false, m_listPoint[iii]);
}
out.close();
return out;
}
void esvg::Polygon::draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level) {
ESVG_VERBOSE(spacingDist(_level) << "DRAW esvg::Polygon");
esvg::render::Path listElement = createPath();
mat2x3 mtx = m_transformMatrix;
mtx *= _basicTrans;
esvg::render::PointList listPoints;
listPoints = listElement.generateListPoints(_level,
_myRenderer.getInterpolationRecurtionMax(),
_myRenderer.getInterpolationThreshold());
//listPoints.applyMatrix(mtx);
esvg::render::SegmentList listSegmentFill;
esvg::render::SegmentList listSegmentStroke;
esvg::render::Weight tmpFill;
esvg::render::Weight tmpStroke;
ememory::SharedPtr<esvg::render::DynamicColor> colorFill = esvg::render::createColor(m_paint.fill, mtx);
ememory::SharedPtr<esvg::render::DynamicColor> colorStroke;
if (m_paint.strokeWidth > 0.0f) {
colorStroke = esvg::render::createColor(m_paint.stroke, mtx);
}
// Check if we need to display background
if (colorFill != null) {
listSegmentFill.createSegmentList(listPoints);
colorFill->setViewPort(listSegmentFill.getViewPort());
listSegmentFill.applyMatrix(mtx);
// now, traverse the scanlines and find the intersections on each scanline, use non-zero rule
tmpFill.generate(_myRenderer.getSize(),
_myRenderer.getNumberSubScanLine(),
listSegmentFill);
}
// check if we need to display stroke:
if (colorStroke != null) {
listSegmentStroke.createSegmentListStroke(listPoints,
m_paint.strokeWidth,
m_paint.lineCap,
m_paint.lineJoin,
m_paint.miterLimit);
colorStroke->setViewPort(listSegmentStroke.getViewPort());
listSegmentStroke.applyMatrix(mtx);
// now, traverse the scanlines and find the intersections on each scanline, use non-zero rule
tmpStroke.generate(_myRenderer.getSize(),
_myRenderer.getNumberSubScanLine(),
listSegmentStroke);
}
// add on images:
_myRenderer.print(tmpFill,
colorFill,
tmpStroke,
colorStroke,
m_paint.opacity);
#ifdef DEBUG
_myRenderer.addDebugSegment(listSegmentFill);
_myRenderer.addDebugSegment(listSegmentStroke);
#endif
}
void esvg::Polygon::drawShapePoints(etk::Vector<etk::Vector<vec2>>& _out,
int32_t _recurtionMax,
float _threshold,
mat2x3& _basicTrans,
int32_t _level) {
ESVG_VERBOSE(spacingDist(_level) << "DRAW Shape esvg::Polygon");
esvg::render::Path listElement = createPath();
mat2x3 mtx = m_transformMatrix;
mtx *= _basicTrans;
esvg::render::PointList listPoints;
listPoints = listElement.generateListPoints(_level, _recurtionMax, _threshold);
listPoints.applyMatrix(mtx);
for (auto &it : listPoints.m_data) {
etk::Vector<vec2> listPoint;
for (auto &itDot : it) {
listPoint.pushBack(itDot.m_pos);
}
_out.pushBack(listPoint);
}
}

37
esvg/Polygon.hpp Normal file
View File

@ -0,0 +1,37 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <esvg/Base.hpp>
#include <etk/Vector.hpp>
namespace esvg {
/*
enum polygonMode {
polygoneModeNonZero,
polygoneModeEvenOdd
};
*/
class Polygon : public esvg::Base {
private:
etk::Vector<vec2 > m_listPoint; //!< list of all point of the polygone
//enum esvg::polygonMode m_diplayMode; //!< polygone specific display mode
public:
Polygon(PaintState parentPaintState);
~Polygon();
bool parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax) override;
void display(int32_t _spacing) override;
void draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level) override;
void drawShapePoints(etk::Vector<etk::Vector<vec2>>& _out,
int32_t _recurtionMax,
float _threshold,
mat2x3& _basicTrans,
int32_t _level=1) override;
private:
esvg::render::Path createPath();
};
}

149
esvg/Polyline.cpp Normal file
View File

@ -0,0 +1,149 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/debug.hpp>
#include <esvg/Polyline.hpp>
#include <esvg/render/Path.hpp>
#include <esvg/render/Weight.hpp>
esvg::Polyline::Polyline(PaintState _parentPaintState) : esvg::Base(_parentPaintState) {
}
esvg::Polyline::~Polyline() {
}
bool esvg::Polyline::parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax) {
// line must have a minimum size...
m_paint.strokeWidth = 1;
if (_element.exist() == false) {
return false;
}
parseTransform(_element);
parsePaintAttr(_element);
// add the property of the parrent modifications ...
m_transformMatrix *= _parentTrans;
etk::String sss1 = _element.attributes["points"];
if (sss1.size() == 0) {
ESVG_ERROR("(l "<<_element.getPos()<<") polyline: missing points attribute");
return false;
}
_sizeMax.setValue(0,0);
ESVG_VERBOSE("Parse polyline : \"" << sss1 << "\"");
const char* sss = sss1.c_str();
while ('\0' != sss[0]) {
vec2 pos;
int32_t n;
if (sscanf(sss, "%f,%f %n", &pos.m_floats[0], &pos.m_floats[1], &n) == 2) {
m_listPoint.pushBack(pos);
_sizeMax.setValue(etk::max(_sizeMax.x(), pos.x()),
etk::max(_sizeMax.y(), pos.y()));
sss += n;
} else {
break;
}
}
return true;
}
void esvg::Polyline::display(int32_t _spacing) {
ESVG_DEBUG(spacingDist(_spacing) << "Polyline nbPoint=" << m_listPoint.size());
}
esvg::render::Path esvg::Polyline::createPath() {
esvg::render::Path out;
out.clear();
out.moveTo(false, m_listPoint[0]);
for(size_t iii=1; iii< m_listPoint.size(); iii++) {
out.lineTo(false, m_listPoint[iii]);
}
out.stop();
return out;
}
void esvg::Polyline::draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level) {
ESVG_VERBOSE(spacingDist(_level) << "DRAW esvg::Polyline");
esvg::render::Path listElement = createPath();
mat2x3 mtx = m_transformMatrix;
mtx *= _basicTrans;
esvg::render::PointList listPoints;
listPoints = listElement.generateListPoints(_level,
_myRenderer.getInterpolationRecurtionMax(),
_myRenderer.getInterpolationThreshold());
//listPoints.applyMatrix(mtx);
esvg::render::SegmentList listSegmentFill;
esvg::render::SegmentList listSegmentStroke;
esvg::render::Weight tmpFill;
esvg::render::Weight tmpStroke;
ememory::SharedPtr<esvg::render::DynamicColor> colorFill = esvg::render::createColor(m_paint.fill, mtx);
ememory::SharedPtr<esvg::render::DynamicColor> colorStroke;
if (m_paint.strokeWidth > 0.0f) {
colorStroke = esvg::render::createColor(m_paint.stroke, mtx);
}
// Check if we need to display background
if (colorFill != null) {
listSegmentFill.createSegmentList(listPoints);
colorFill->setViewPort(listSegmentFill.getViewPort());
listSegmentFill.applyMatrix(mtx);
// now, traverse the scanlines and find the intersections on each scanline, use non-zero rule
tmpFill.generate(_myRenderer.getSize(),
_myRenderer.getNumberSubScanLine(),
listSegmentFill);
}
// check if we need to display stroke:
if (colorStroke != null) {
listSegmentStroke.createSegmentListStroke(listPoints,
m_paint.strokeWidth,
m_paint.lineCap,
m_paint.lineJoin,
m_paint.miterLimit);
colorStroke->setViewPort(listSegmentStroke.getViewPort());
listSegmentStroke.applyMatrix(mtx);
// now, traverse the scanlines and find the intersections on each scanline, use non-zero rule
tmpStroke.generate(_myRenderer.getSize(),
_myRenderer.getNumberSubScanLine(),
listSegmentStroke);
}
// add on images:
_myRenderer.print(tmpFill,
colorFill,
tmpStroke,
colorStroke,
m_paint.opacity);
#ifdef DEBUG
_myRenderer.addDebugSegment(listSegmentFill);
_myRenderer.addDebugSegment(listSegmentStroke);
#endif
}
void esvg::Polyline::drawShapePoints(etk::Vector<etk::Vector<vec2>>& _out,
int32_t _recurtionMax,
float _threshold,
mat2x3& _basicTrans,
int32_t _level) {
ESVG_VERBOSE(spacingDist(_level) << "DRAW Shape esvg::Polyline");
esvg::render::Path listElement = createPath();
mat2x3 mtx = m_transformMatrix;
mtx *= _basicTrans;
esvg::render::PointList listPoints;
listPoints = listElement.generateListPoints(_level, _recurtionMax, _threshold);
listPoints.applyMatrix(mtx);
for (auto &it : listPoints.m_data) {
etk::Vector<vec2> listPoint;
for (auto &itDot : it) {
listPoint.pushBack(itDot.m_pos);
}
_out.pushBack(listPoint);
}
}

30
esvg/Polyline.hpp Normal file
View File

@ -0,0 +1,30 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <esvg/Base.hpp>
#include <etk/Vector.hpp>
namespace esvg {
class Polyline : public esvg::Base {
private:
etk::Vector<vec2 > m_listPoint; //!< list of all point of the polyline
public:
Polyline(PaintState _parentPaintState);
~Polyline();
bool parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax) override;
void display(int32_t _spacing) override;
void draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level) override;
void drawShapePoints(etk::Vector<etk::Vector<vec2>>& _out,
int32_t _recurtionMax,
float _threshold,
mat2x3& _basicTrans,
int32_t _level=1) override;
private:
esvg::render::Path createPath();
};
}

185
esvg/RadialGradient.cpp Normal file
View File

@ -0,0 +1,185 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/debug.hpp>
#include <esvg/LinearGradient.hpp>
#include <esvg/RadialGradient.hpp>
#include <esvg/render/Path.hpp>
#include <esvg/render/Weight.hpp>
#include <esvg/esvg.hpp>
esvg::RadialGradient::RadialGradient(PaintState _parentPaintState) :
esvg::Base(_parentPaintState),
m_center(vec2(50,50), esvg::distance_pourcent),
m_radius(50, esvg::distance_pourcent),
m_focal(vec2(50,50), esvg::distance_pourcent),
m_unit(gradientUnits_objectBoundingBox),
m_spread(spreadMethod_pad) {
}
esvg::RadialGradient::~RadialGradient() {
}
bool esvg::RadialGradient::parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax) {
// line must have a minimum size...
//m_paint.strokeWidth = 1;
if (_element.exist() == false) {
return false;
}
// ---------------- get unique ID ----------------
m_id = _element.attributes["id"];
//parseTransform(_element);
//parsePaintAttr(_element);
// add the property of the parrent modifications ...
m_transformMatrix *= _parentTrans;
etk::String contentX = _element.attributes["cx"];
etk::String contentY = _element.attributes["cy"];
if ( contentX != ""
&& contentY != "") {
m_center.set(contentX, contentY);
}
contentX = _element.attributes["r"];
if (contentX != "") {
m_radius.set(contentX);
}
contentX = _element.attributes["fx"];
contentY = _element.attributes["fy"];
if ( contentX != ""
&& contentY != "") {
m_focal.set(contentX, contentY);
}
contentX = _element.attributes["gradientUnits"];
if (contentX == "userSpaceOnUse") {
m_unit = gradientUnits_userSpaceOnUse;
} else {
m_unit = gradientUnits_objectBoundingBox;
if ( contentX.size() != 0
&& contentX != "objectBoundingBox") {
ESVG_ERROR("Parsing error of 'gradientUnits' ==> not suported value: '" << contentX << "' not in : {userSpaceOnUse/objectBoundingBox} use objectBoundingBox");
}
}
contentX = _element.attributes["spreadMethod"];
if (contentX == "reflect") {
m_spread = spreadMethod_reflect;
} else if (contentX == "repeat") {
m_spread = spreadMethod_repeat;
} else {
m_spread = spreadMethod_pad;
if ( contentX.size() != 0
&& contentX != "pad") {
ESVG_ERROR("Parsing error of 'spreadMethod' ==> not suported value: '" << contentX << "' not in : {reflect/repeate/pad} use pad");
}
}
// note: xlink:href is incompatible with subNode "stop"
m_href = _element.attributes["xlink:href"];
if (m_href.size() != 0) {
m_href = etk::String(m_href.begin()+1, m_href.end());
}
// parse all sub node :
for(auto it : _element.nodes) {
exml::Element child = it.toElement();
if (child.exist() == false) {
// can be a comment ...
continue;
}
if (child.getValue() == "stop") {
float offset = 100;
etk::Color<float,4> stopColor = etk::color::none;
etk::String content = child.attributes["offset"];
if (content.size()!=0) {
etk::Pair<float, enum esvg::distance> tmp = parseLength2(content);
if (tmp.second == esvg::distance_pixel) {
// special case ==> all time % then no type define ==> % in [0.0 .. 1.0]
offset = tmp.first*100.0f;
} else if (tmp.second != esvg::distance_pourcent) {
ESVG_ERROR("offset : " << content << " res=" << tmp.first << "," << tmp.second << " Not support other than pourcent %");
} else {
offset = tmp.first;
}
}
content = child.attributes["stop-color"];
if (content.size()!=0) {
stopColor = parseColor(content).first;
ESVG_VERBOSE(" color : \"" << content << "\" == > " << stopColor);
}
content = child.attributes["stop-opacity"];
if (content.size()!=0) {
float opacity = parseLength(content);
opacity = etk::avg(0.0f, opacity, 1.0f);
stopColor.setA(opacity);
ESVG_VERBOSE(" opacity : '" << content << "' == > " << stopColor);
}
m_data.pushBack(etk::Pair<float, etk::Color<float,4>>(offset, stopColor));
} else {
ESVG_ERROR("(l " << child.getPos() << ") node not suported : '" << child.getValue() << "' must be [stop]");
}
}
if (m_data.size() != 0) {
if (m_href != "") {
ESVG_ERROR("(l " << _element.getPos() << ") node can not have an xlink:href element with sub node named: stop ==> removing href");
m_href = "";
}
}
return true;
}
void esvg::RadialGradient::display(int32_t _spacing) {
ESVG_DEBUG(spacingDist(_spacing) << "RadialGradient center=" << m_center << " focal=" << m_focal << " radius=" << m_radius);
for (auto &it : m_data) {
ESVG_DEBUG(spacingDist(_spacing+1) << "STOP: offset=" << it.first << " color=" << it.second);
}
}
void esvg::RadialGradient::draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level) {
ESVG_VERBOSE(spacingDist(_level) << "DRAW esvg::RadialGradient");
}
const esvg::Dimension& esvg::RadialGradient::getCenter() {
return m_center;
}
const esvg::Dimension& esvg::RadialGradient::getFocal() {
return m_focal;
}
const esvg::Dimension1D& esvg::RadialGradient::getRadius() {
return m_radius;
}
const etk::Vector<etk::Pair<float, etk::Color<float,4>>>& esvg::RadialGradient::getColors(esvg::Document* _document) {
if (m_href == "") {
return m_data;
}
if (_document == null) {
ESVG_ERROR("Get null input for document");
return m_data;
}
ememory::SharedPtr<esvg::Base> base = _document->getReference(m_href);
if (base == null) {
ESVG_ERROR("Can not get base : '" << m_href << "'");
return m_data;
}
ememory::SharedPtr<esvg::RadialGradient> gradientR = ememory::dynamicPointerCast<esvg::RadialGradient>(base);
if (gradientR == null) {
ememory::SharedPtr<esvg::LinearGradient> gradientL = ememory::dynamicPointerCast<esvg::LinearGradient>(base);
if (gradientL == null) {
ESVG_ERROR("Can not cast in a linear/radial gradient: '" << m_href << "' ==> wrong type");
return m_data;
}
return gradientL->getColors(_document);
}
return gradientR->getColors(_document);
}

38
esvg/RadialGradient.hpp Normal file
View File

@ -0,0 +1,38 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <esvg/Base.hpp>
#include <esvg/gradientUnits.hpp>
#include <esvg/spreadMethod.hpp>
namespace esvg {
class Document;
class RadialGradient : public esvg::Base {
private:
esvg::Dimension m_center; //!< gradient position cx cy
esvg::Dimension1D m_radius; //!< Radius of the gradient
esvg::Dimension m_focal; //!< gradient Focal fx fy
public:
enum gradientUnits m_unit;
enum spreadMethod m_spread;
private:
etk::String m_href; //!< in case of using a single gradient in multiple gradient, the gradient is store in an other element...
etk::Vector<etk::Pair<float, etk::Color<float,4>>> m_data; //!< incompatible with href
public:
RadialGradient(PaintState _parentPaintState);
~RadialGradient();
virtual bool parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax);
virtual void display(int32_t _spacing);
virtual void draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level);
public:
const esvg::Dimension& getCenter();
const esvg::Dimension& getFocal();
const esvg::Dimension1D& getRadius();
const etk::Vector<etk::Pair<float, etk::Color<float,4>>>& getColors(esvg::Document* _document);
};
}

166
esvg/Rectangle.cpp Normal file
View File

@ -0,0 +1,166 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/debug.hpp>
#include <esvg/Rectangle.hpp>
#include <esvg/render/Path.hpp>
#include <esvg/render/Weight.hpp>
esvg::Rectangle::Rectangle(PaintState _parentPaintState) : esvg::Base(_parentPaintState) {
m_position.setValue(0,0);
m_size.setValue(0,0);
m_roundedCorner.setValue(0,0);
}
esvg::Rectangle::~Rectangle() {
}
bool esvg::Rectangle::parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax) {
if (_element.exist() == false) {
return false;
}
m_position.setValue(0.0f, 0.0f);
m_size.setValue(0.0f, 0.0f);
m_roundedCorner.setValue(0.0f, 0.0f);
parseTransform(_element);
parsePaintAttr(_element);
// add the property of the parrent modifications ...
m_transformMatrix *= _parentTrans;
parsePosition(_element, m_position, m_size);
etk::String content = _element.attributes["rx"];
if (content.size()!=0) {
m_roundedCorner.setX(parseLength(content));
}
content = _element.attributes["ry"];
if (content.size()!=0) {
m_roundedCorner.setY(parseLength(content));
}
_sizeMax.setValue(m_position.x() + m_size.x() + m_paint.strokeWidth,
m_position.y() + m_size.y() + m_paint.strokeWidth);
return true;
}
void esvg::Rectangle::display(int32_t _spacing) {
ESVG_DEBUG(spacingDist(_spacing) << "Rectangle : pos=" << m_position << " size=" << m_size << " corner=" << m_roundedCorner);
}
esvg::render::Path esvg::Rectangle::createPath() {
esvg::render::Path out;
out.clear();
if ( m_roundedCorner.x() == 0.0f
|| m_roundedCorner.y() == 0.0f) {
out.moveTo(false, m_position);
out.lineToH(true, m_size.x());
out.lineToV(true, m_size.y());
out.lineToH(true, -m_size.x());
} else {
// Rounded rectangle
out.moveTo(false, m_position + vec2(m_roundedCorner.x(), 0.0f));
out.lineToH(true, m_size.x()-m_roundedCorner.x()*2.0f);
out.curveTo(true, vec2(m_roundedCorner.x()*esvg::kappa90, 0.0f),
vec2(m_roundedCorner.x(), m_roundedCorner.y() * (1.0f - esvg::kappa90)),
vec2(m_roundedCorner.x(), m_roundedCorner.y()) );
out.lineToV(true, m_size.y()-m_roundedCorner.y()*2.0f);
out.curveTo(true, vec2(0.0f, m_roundedCorner.y() * esvg::kappa90),
vec2(-m_roundedCorner.x()* (1.0f - esvg::kappa90), m_roundedCorner.y()),
vec2(-m_roundedCorner.x(), m_roundedCorner.y()) );
out.lineToH(true, -(m_size.x()-m_roundedCorner.x()*2.0f));
out.curveTo(true, vec2(-m_roundedCorner.x()*esvg::kappa90, 0.0f),
vec2(-m_roundedCorner.x(), -m_roundedCorner.y() * (1.0f - esvg::kappa90)),
vec2(-m_roundedCorner.x(), -m_roundedCorner.y()) );
out.lineToV(true, -(m_size.y()-m_roundedCorner.y()*2.0f));
out.curveTo(true, vec2(0.0f, -m_roundedCorner.y() * esvg::kappa90),
vec2(m_roundedCorner.x()* (1.0f - esvg::kappa90), -m_roundedCorner.y()),
vec2(m_roundedCorner.x(), -m_roundedCorner.y()) );
}
out.close();
return out;
}
void esvg::Rectangle::draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level) {
ESVG_VERBOSE(spacingDist(_level) << "DRAW esvg::Rectangle: fill=" << m_paint.fill.first << "/" << m_paint.fill.second
<< " stroke=" << m_paint.stroke.first << "/" << m_paint.stroke.second);
esvg::render::Path listElement = createPath();
mat2x3 mtx = m_transformMatrix;
mtx *= _basicTrans;
esvg::render::PointList listPoints;
listPoints = listElement.generateListPoints(_level,
_myRenderer.getInterpolationRecurtionMax(),
_myRenderer.getInterpolationThreshold());
//listPoints.applyMatrix(mtx);
esvg::render::SegmentList listSegmentFill;
esvg::render::SegmentList listSegmentStroke;
esvg::render::Weight tmpFill;
esvg::render::Weight tmpStroke;
ememory::SharedPtr<esvg::render::DynamicColor> colorFill = esvg::render::createColor(m_paint.fill, mtx);
ememory::SharedPtr<esvg::render::DynamicColor> colorStroke;
if (m_paint.strokeWidth > 0.0f) {
colorStroke = esvg::render::createColor(m_paint.stroke, mtx);
}
// Check if we need to display background
if (colorFill != null) {
listSegmentFill.createSegmentList(listPoints);
colorFill->setViewPort(listSegmentFill.getViewPort());
listSegmentFill.applyMatrix(mtx);
// now, traverse the scanlines and find the intersections on each scanline, use non-zero rule
tmpFill.generate(_myRenderer.getSize(),
_myRenderer.getNumberSubScanLine(),
listSegmentFill);
}
// check if we need to display stroke:
if (colorStroke != null) {
listSegmentStroke.createSegmentListStroke(listPoints,
m_paint.strokeWidth,
m_paint.lineCap,
m_paint.lineJoin,
m_paint.miterLimit);
colorStroke->setViewPort(listSegmentStroke.getViewPort());
listSegmentStroke.applyMatrix(mtx);
// now, traverse the scanlines and find the intersections on each scanline, use non-zero rule
tmpStroke.generate(_myRenderer.getSize(),
_myRenderer.getNumberSubScanLine(),
listSegmentStroke);
}
// add on images:
_myRenderer.print(tmpFill,
colorFill,
tmpStroke,
colorStroke,
m_paint.opacity);
#ifdef DEBUG
_myRenderer.addDebugSegment(listSegmentFill);
_myRenderer.addDebugSegment(listSegmentStroke);
#endif
}
void esvg::Rectangle::drawShapePoints(etk::Vector<etk::Vector<vec2>>& _out,
int32_t _recurtionMax,
float _threshold,
mat2x3& _basicTrans,
int32_t _level) {
ESVG_VERBOSE(spacingDist(_level) << "DRAW Shape esvg::Rectangle");
esvg::render::Path listElement = createPath();
mat2x3 mtx = m_transformMatrix;
mtx *= _basicTrans;
esvg::render::PointList listPoints;
listPoints = listElement.generateListPoints(_level, _recurtionMax, _threshold);
listPoints.applyMatrix(mtx);
for (auto &it : listPoints.m_data) {
etk::Vector<vec2> listPoint;
for (auto &itDot : it) {
listPoint.pushBack(itDot.m_pos);
}
_out.pushBack(listPoint);
}
}

31
esvg/Rectangle.hpp Normal file
View File

@ -0,0 +1,31 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <esvg/Base.hpp>
namespace esvg {
class Rectangle : public esvg::Base {
private:
vec2 m_position; //!< position of the rectangle
vec2 m_size; //!< size of the rectangle
vec2 m_roundedCorner; //!< property of the rounded corner
public:
Rectangle(PaintState _parentPaintState);
~Rectangle();
bool parseXML(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax) override;
void display(int32_t _spacing) override;
void draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level) override;
void drawShapePoints(etk::Vector<etk::Vector<vec2>>& _out,
int32_t _recurtionMax,
float _threshold,
mat2x3& _basicTrans,
int32_t _level=1) override;
private:
esvg::render::Path createPath();
};
}

427
esvg/Renderer.cpp Normal file
View File

@ -0,0 +1,427 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/debug.hpp>
#include <esvg/Renderer.hpp>
#include <etk/uri/Uri.hpp>
#include <etk/uri/provider/provider.hpp>
esvg::Renderer::Renderer(const ivec2& _size, esvg::Document* _document, bool _visualDebug) :
#ifdef DEBUG
m_visualDebug(_visualDebug),
m_factor(1),
#endif
m_interpolationRecurtionMax(10),
m_interpolationThreshold(0.25f),
m_nbSubScanLine(8),
m_document(_document) {
#ifdef DEBUG
if (m_visualDebug == true) {
m_factor = 20;
}
#endif
setSize(_size);
}
esvg::Renderer::~Renderer() {
m_buffer.clear();
m_size = ivec2(0,0);
}
etk::Color<float,4> esvg::Renderer::mergeColor(etk::Color<float,4> _base, etk::Color<float,4> _integration) {
etk::Color<float,4> result;
/*
if (_integration.a() < _base.a()) {
result = _integration;
_integration = _base;
_base = result;
}
*/
result.setR(_integration.a() * _integration.r() + _base.a() * (1.0f - _integration.a()) * _base.r());
result.setG(_integration.a() * _integration.g() + _base.a() * (1.0f - _integration.a()) * _base.g());
result.setB(_integration.a() * _integration.b() + _base.a() * (1.0f - _integration.a()) * _base.b());
result.setA(_integration.a() + _base.a() * (1.0f - _integration.a()));
if (result.a() != 0.0f) {
float reverse = 1.0f/result.a();
result.setR(result.r()*reverse);
result.setG(result.g()*reverse);
result.setB(result.b()*reverse);
}
return result;
}
void esvg::Renderer::print(const esvg::render::Weight& _weightFill,
ememory::SharedPtr<esvg::render::DynamicColor>& _colorFill,
const esvg::render::Weight& _weightStroke,
ememory::SharedPtr<esvg::render::DynamicColor>& _colorStroke,
float _opacity) {
if (_colorFill != null) {
//_colorFill->setViewPort(etk::Pair<vec2, vec2>(vec2(0,0), vec2(sizeX, sizeY)));
_colorFill->generate(m_document);
}
if (_colorStroke != null) {
//_colorStroke->setViewPort(etk::Pair<vec2, vec2>(vec2(0,0), vec2(sizeX, sizeY)));
_colorStroke->generate(m_document);
}
// all together
for (int32_t yyy=0; yyy<m_size.y(); ++yyy) {
for (int32_t xxx=0; xxx<m_size.x(); ++xxx) {
ivec2 pos(xxx, yyy);
float valueFill = _weightFill.get(pos);
float valueStroke = _weightStroke.get(pos);
// calculate merge of stroke and fill value:
etk::Color<float,4> intermediateColorFill(etk::color::none);
etk::Color<float,4> intermediateColorStroke(etk::color::none);
if ( _colorFill != null
&& valueFill != 0.0f) {
intermediateColorFill = _colorFill->getColor(pos);
intermediateColorFill.setA(intermediateColorFill.a()*valueFill);
}
if ( _colorStroke != null
&& valueStroke != 0.0f) {
intermediateColorStroke = _colorStroke->getColor(pos);
intermediateColorStroke.setA(intermediateColorStroke.a()*valueStroke);
}
etk::Color<float,4> intermediateColor = mergeColor(intermediateColorFill, intermediateColorStroke);
intermediateColor.setA(intermediateColor.a() * _opacity);
#if DEBUG
for (int32_t deltaY=0; deltaY<m_factor; ++deltaY) {
for (int32_t deltaX=0; deltaX<m_factor; ++deltaX) {
int32_t id = m_size.x()*m_factor*(yyy*m_factor+deltaY) + (xxx*m_factor+deltaX);
m_buffer[id] = mergeColor(m_buffer[id], intermediateColor);
}
}
#else
m_buffer[m_size.x()*yyy + xxx] = mergeColor(m_buffer[m_size.x()*yyy + xxx], intermediateColor);
#endif
}
}
#ifdef DEBUG
// display the gradient position:
ememory::SharedPtr<esvg::render::DynamicColorSpecial> tmpColor = ememory::dynamicPointerCast<esvg::render::DynamicColorSpecial>(_colorFill);
if (tmpColor != null) {
esvg::render::SegmentList listSegment;
// Display bounding box
listSegment.addSegment(esvg::render::Point(tmpColor->m_viewPort.first),
esvg::render::Point(vec2(tmpColor->m_viewPort.first.x(), tmpColor->m_viewPort.second.y()) ),
false);
listSegment.addSegment(esvg::render::Point(vec2(tmpColor->m_viewPort.first.x(), tmpColor->m_viewPort.second.y()) ),
esvg::render::Point(tmpColor->m_viewPort.second),
false);
listSegment.addSegment(esvg::render::Point(tmpColor->m_viewPort.second),
esvg::render::Point(vec2(tmpColor->m_viewPort.second.x(), tmpColor->m_viewPort.first.y()) ),
false);
listSegment.addSegment(esvg::render::Point(vec2(tmpColor->m_viewPort.second.x(), tmpColor->m_viewPort.first.y()) ),
esvg::render::Point(tmpColor->m_viewPort.first),
false);
listSegment.applyMatrix(tmpColor->m_matrix);
// display the gradient axis
listSegment.addSegment(esvg::render::Point(tmpColor->m_pos1),
esvg::render::Point(tmpColor->m_pos2),
false);
/*
mat2x3 m_matrix;
etk::Pair<vec2, vec2> m_viewPort;
vec2 m_pos1;
vec2 m_pos2;
*/
addDebugSegment(listSegment);
}
#endif
}
#ifdef DEBUG
void esvg::Renderer::addDebugSegment(const esvg::render::SegmentList& _listSegment) {
if (m_visualDebug == false) {
return;
}
ivec2 dynamicSize = m_size * m_factor;
// for each lines:
for (int32_t yyy=0; yyy<dynamicSize.y(); ++yyy) {
// Reduce the number of lines in the subsampling parsing:
etk::Vector<esvg::render::Segment> availlableSegmentPixel;
for (auto &it : _listSegment.m_data) {
if ( it.p0.y() * m_factor <= float(yyy+1)
&& it.p1.y() * m_factor >= float(yyy)) {
availlableSegmentPixel.pushBack(it);
}
}
//find all the segment that cross the middle of the line of the center of the pixel line:
float subSamplingCenterPos = yyy + 0.5f;
etk::Vector<esvg::render::Segment> availlableSegment;
// find in the subList ...
for (auto &it : availlableSegmentPixel) {
if ( it.p0.y() * m_factor <= subSamplingCenterPos
&& it.p1.y() * m_factor >= subSamplingCenterPos ) {
availlableSegment.pushBack(it);
}
}
// x position, angle
etk::Vector<etk::Pair<float, float>> listPosition;
for (auto &it : availlableSegment) {
vec2 delta = it.p0 * m_factor - it.p1 * m_factor;
// x = coefficent*y+bbb;
float coefficient = delta.x()/delta.y();
float bbb = it.p0.x() * m_factor - coefficient*it.p0.y() * m_factor;
float xpos = coefficient * subSamplingCenterPos + bbb;
if ( xpos >= 0
&& xpos < dynamicSize.x()
&& yyy >= 0
&& yyy < dynamicSize.y() ) {
if (it.direction == 1.0f) {
m_buffer[(dynamicSize.x()*yyy + int32_t(xpos))] = etk::color::blue;
} else {
m_buffer[(dynamicSize.x()*yyy + int32_t(xpos))] = etk::color::darkRed;
}
}
}
}
// for each colomn:
for (int32_t xxx=0; xxx<dynamicSize.x(); ++xxx) {
// Reduce the number of lines in the subsampling parsing:
etk::Vector<esvg::render::Segment> availlableSegmentPixel;
for (auto &it : _listSegment.m_data) {
if ( ( it.p0.x() * m_factor <= float(xxx+1)
&& it.p1.x() * m_factor >= float(xxx) )
|| ( it.p0.x() * m_factor >= float(xxx+1)
&& it.p1.x() * m_factor <= float(xxx) ) ) {
availlableSegmentPixel.pushBack(it);
}
}
//find all the segment that cross the middle of the line of the center of the pixel line:
float subSamplingCenterPos = xxx + 0.5f;
etk::Vector<esvg::render::Segment> availlableSegment;
// find in the subList ...
for (auto &it : availlableSegmentPixel) {
if ( ( it.p0.x() * m_factor <= subSamplingCenterPos
&& it.p1.x() * m_factor >= subSamplingCenterPos)
|| ( it.p0.x() * m_factor >= subSamplingCenterPos
&& it.p1.x() * m_factor <= subSamplingCenterPos) ) {
availlableSegment.pushBack(it);
}
}
// x position, angle
etk::Vector<etk::Pair<float, float>> listPosition;
for (auto &it : availlableSegment) {
vec2 delta = it.p0 * m_factor - it.p1 * m_factor;
// x = coefficent*y+bbb;
if (delta.x() == 0) {
continue;
}
float coefficient = delta.y()/delta.x();
float bbb = it.p0.y() * m_factor - coefficient*it.p0.x() * m_factor;
float ypos = coefficient * subSamplingCenterPos + bbb;
if ( ypos >= 0
&& ypos < dynamicSize.y()
&& xxx >= 0
&& xxx < dynamicSize.y() ) {
if (it.direction == 1.0f) {
m_buffer[(dynamicSize.x()*int32_t(ypos) + xxx)] = etk::color::blue;
} else {
m_buffer[(dynamicSize.x()*int32_t(ypos) + xxx)] = etk::color::darkRed;
}
}
}
}
}
#endif
void esvg::Renderer::writePPM(const etk::Uri& _uri) {
if (m_buffer.size() == 0) {
return;
}
auto fileIo = etk::uri::get(_uri);
if (fileIo == null) {
ESVG_ERROR("Can not create the uri: " << _uri);
return;
}
if (fileIo->open(etk::io::OpenMode::Write) == false) {
ESVG_ERROR("Can not open (r) the file : " << _uri);
return;
}
int32_t sizeX = m_size.x();
int32_t sizeY = m_size.y();
#if DEBUG
sizeX *= m_factor;
sizeY *= m_factor;
#endif
ESVG_DEBUG("Generate ppm : " << m_size << " debug size=" << ivec2(sizeX,sizeY));
char tmpValue[1024];
sprintf(tmpValue, "P6 %d %d 255 ", sizeX, sizeY);
fileIo->write(tmpValue,1,sizeof(tmpValue));
for (int32_t iii=0 ; iii<sizeX*sizeY; iii++) {
etk::Color<uint8_t,3> tmp = m_buffer[iii];
fileIo->write(&tmp, 1, 3);
}
fileIo->close();
}
#define PLOPPP
extern "C" {
#pragma pack(push,1)
struct bitmapFileHeader {
int16_t bfType;
int32_t bfSize;
int32_t bfReserved;
int32_t bfOffBits;
};
struct bitmapInfoHeader {
int32_t biSize;
int32_t biWidth;
int32_t biHeight;
int16_t biPlanes;
int16_t biBitCount;
int32_t biCompression;
int32_t biSizeImage;
int32_t biXPelsPerMeter;
int32_t biYPelsPerMeter;
#ifndef PLOPPP
int32_t biClrUsed;
int32_t biClrImportant;
#else
// https://en.wikipedia.org/wiki/BMP_file_format / example 2
int32_t biPaletteNumber;
int32_t biImportantColor;
int32_t biBitMaskRed;
int32_t biBitMaskGreen;
int32_t biBitMaskBlue;
int32_t biBitMaskAlpha;
int32_t biLCSColorSpace;
int32_t biUnused[16];
#endif
};
#pragma pack(pop)
}
void esvg::Renderer::writeBMP(const etk::Uri& _uri) {
if (m_buffer.size() == 0) {
return;
}
auto fileIo = etk::uri::get(_uri);
if (fileIo == null) {
ESVG_ERROR("Can not create the uri: " << _uri);
return;
}
if (fileIo->open(etk::io::OpenMode::Write) == false) {
ESVG_ERROR("Can not open (r) the file : " << _uri);
return;
}
struct bitmapFileHeader fileHeader;
struct bitmapInfoHeader infoHeader;
int32_t sizeX = m_size.x();
int32_t sizeY = m_size.y();
#if DEBUG
sizeX *= m_factor;
sizeY *= m_factor;
#endif
fileHeader.bfType = 0x4D42;
fileHeader.bfSize = sizeof(struct bitmapFileHeader) + sizeof(struct bitmapInfoHeader) + sizeX*sizeY*4;
fileHeader.bfReserved = 0;
fileHeader.bfOffBits = sizeof(struct bitmapFileHeader) + sizeof(struct bitmapInfoHeader);
infoHeader.biSize = sizeof(struct bitmapInfoHeader);
infoHeader.biWidth = sizeX;
infoHeader.biHeight = sizeY;
infoHeader.biPlanes = 1;
infoHeader.biBitCount = 32;
#ifndef PLOPPP
infoHeader.biCompression = 0;
#else
infoHeader.biCompression = 3;
#endif
infoHeader.biSizeImage = sizeX*sizeY*4;
infoHeader.biXPelsPerMeter = 75;
infoHeader.biYPelsPerMeter = 75;
#ifndef PLOPPP
infoHeader.biClrUsed = 0;
infoHeader.biClrImportant = 0;
#else
infoHeader.biPaletteNumber = 0;
infoHeader.biImportantColor = 0;
infoHeader.biBitMaskRed = 0xFF000000;
infoHeader.biBitMaskGreen = 0x00FF0000;
infoHeader.biBitMaskBlue =0x0000FF00;
infoHeader.biBitMaskAlpha = 0x000000FF;
infoHeader.biLCSColorSpace = 0x73524742; // "Win "
for (int32_t jjj=0; jjj<16; ++jjj) {
infoHeader.biUnused[jjj] = 0;
}
infoHeader.biUnused[12] = 0x00000002;
#endif
// get the data :
fileIo->write(&fileHeader, sizeof(struct bitmapFileHeader), 1);
fileIo->write(&infoHeader, sizeof(struct bitmapInfoHeader), 1);
uint8_t data[16];
for(int32_t yyy=sizeY-1; yyy>=0; --yyy) {
for(int32_t xxx=0; xxx<sizeX; ++xxx) {
const etk::Color<uint8_t,4>& tmpColor = m_buffer[sizeX*yyy + xxx];
uint8_t* pointer = data;
#ifndef PLOPPP
*pointer++ = tmpColor.a();
*pointer++ = tmpColor.r();
*pointer++ = tmpColor.g();
*pointer++ = tmpColor.b();
#else
*pointer++ = tmpColor.a();
*pointer++ = tmpColor.b();
*pointer++ = tmpColor.g();
*pointer++ = tmpColor.r();
#endif
fileIo->write(data,1,4);
}
}
fileIo->close();
}
void esvg::Renderer::setSize(const ivec2& _size) {
m_size = _size;
m_buffer.resize(m_size.x() * m_size.y()
#if DEBUG
* m_factor * m_factor
#endif
, etk::color::none);
}
const ivec2& esvg::Renderer::getSize() const {
return m_size;
}
etk::Vector<etk::Color<float,4>> esvg::Renderer::getData() {
return m_buffer;
}
void esvg::Renderer::setInterpolationRecurtionMax(int32_t _value) {
m_interpolationRecurtionMax = etk::avg(1, _value, 200);
}
int32_t esvg::Renderer::getInterpolationRecurtionMax() const {
return m_interpolationRecurtionMax;
}
void esvg::Renderer::setInterpolationThreshold(float _value) {
m_interpolationThreshold = etk::avg(0.0f, _value, 20000.0f);
}
float esvg::Renderer::getInterpolationThreshold() const {
return m_interpolationThreshold;
}
void esvg::Renderer::setNumberSubScanLine(int32_t _value) {
m_nbSubScanLine = etk::avg(1, _value, 200);
}
int32_t esvg::Renderer::getNumberSubScanLine() const {
return m_nbSubScanLine;
}

73
esvg/Renderer.hpp Normal file
View File

@ -0,0 +1,73 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
#include <etk/Color.hpp>
#include <esvg/render/Weight.hpp>
#include <esvg/render/DynamicColor.hpp>
#include <etk/uri/uri.hpp>
namespace esvg {
class Document;
class Renderer {
#ifdef DEBUG
private:
bool m_visualDebug;
int32_t m_factor;
#endif
public:
Renderer(const ivec2& _size, esvg::Document* _document, bool _visualDebug=false);
~Renderer();
protected:
ivec2 m_size;
public:
void setSize(const ivec2& _size);
const ivec2& getSize() const;
protected:
etk::Vector<etk::Color<float,4>> m_buffer;
public:
etk::Vector<etk::Color<float,4>> getData();
protected:
int32_t m_interpolationRecurtionMax;
public:
void setInterpolationRecurtionMax(int32_t _value);
int32_t getInterpolationRecurtionMax() const;
protected:
float m_interpolationThreshold;
public:
void setInterpolationThreshold(float _value);
float getInterpolationThreshold() const;
protected:
int32_t m_nbSubScanLine;
public:
void setNumberSubScanLine(int32_t _value);
int32_t getNumberSubScanLine() const;
public:
void writePPM(const etk::Uri& _uri);
void writeBMP(const etk::Uri& _uri);
protected:
etk::Color<float,4> mergeColor(etk::Color<float,4> _base, etk::Color<float,4> _integration);
public:
void print(const esvg::render::Weight& _weightFill,
ememory::SharedPtr<esvg::render::DynamicColor>& _colorFill,
const esvg::render::Weight& _weightStroke,
ememory::SharedPtr<esvg::render::DynamicColor>& _colorStroke,
float _opacity);
#ifdef DEBUG
void addDebugSegment(const esvg::render::SegmentList& _listSegment);
void addDebug(const etk::Vector<etk::Pair<vec2,vec2>>& _info);
#endif
protected:
esvg::Document* m_document;
public:
esvg::Document* getMainDocument() {
return m_document;
}
};
}

28
esvg/Text.cpp Normal file
View File

@ -0,0 +1,28 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/debug.hpp>
#include <esvg/Text.hpp>
esvg::Text::Text(PaintState _parentPaintState) : esvg::Base(_parentPaintState) {
}
esvg::Text::~Text() {
}
bool esvg::Text::parse(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax) {
_sizeMax.setValue(0,0);
ESVG_ERROR("NOT IMPLEMENTED");
return false;
}
void esvg::Text::display(int32_t _spacing) {
ESVG_DEBUG(spacingDist(_spacing) << "Text");
}

19
esvg/Text.hpp Normal file
View File

@ -0,0 +1,19 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <esvg/Base.hpp>
namespace esvg {
class Text : public esvg::Base {
public:
Text(PaintState _parentPaintState);
~Text();
bool parse(const exml::Element& _element, mat2x3& _parentTrans, vec2& _sizeMax);
void display(int32_t _spacing) override;
};
}

20
esvg/cap.cpp Normal file
View File

@ -0,0 +1,20 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/cap.hpp>
#include <esvg/debug.hpp>
static const char* values[] = {
"butt",
"round",
"square"
};
etk::Stream& esvg::operator <<(etk::Stream& _os, enum esvg::cap _obj) {
_os << values[_obj];
return _os;
}

22
esvg/cap.hpp Normal file
View File

@ -0,0 +1,22 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/Stream.hpp>
namespace esvg {
enum cap {
cap_butt,
cap_round,
cap_square
};
/**
* @brief Debug operator To display the curent element in a Human redeable information
*/
etk::Stream& operator <<(etk::Stream& _os, enum esvg::cap _obj);
}

13
esvg/debug.cpp Normal file
View File

@ -0,0 +1,13 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/debug.hpp>
int32_t esvg::getLogId() {
static int32_t g_val = elog::registerInstance("esvg");
return g_val;
}

39
esvg/debug.hpp Normal file
View File

@ -0,0 +1,39 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <elog/log.hpp>
namespace esvg {
int32_t getLogId();
};
#define ESVG_BASE(info,data) ELOG_BASE(esvg::getLogId(),info,data)
#define ESVG_PRINT(data) ESVG_BASE(-1, data)
#define ESVG_CRITICAL(data) ESVG_BASE(1, data)
#define ESVG_ERROR(data) ESVG_BASE(2, data)
#define ESVG_WARNING(data) ESVG_BASE(3, data)
#ifdef DEBUG
#define ESVG_INFO(data) ESVG_BASE(4, data)
#define ESVG_DEBUG(data) ESVG_BASE(5, data)
#define ESVG_VERBOSE(data) ESVG_BASE(6, data)
#define ESVG_TODO(data) ESVG_BASE(4, "TODO : " << data)
#else
#define ESVG_INFO(data) do { } while(false)
#define ESVG_DEBUG(data) do { } while(false)
#define ESVG_VERBOSE(data) do { } while(false)
#define ESVG_TODO(data) do { } while(false)
#endif
#define ESVG_ASSERT(cond,data) \
do { \
if (!(cond)) { \
SVG_CRITICAL(data); \
assert(!#cond); \
} \
} while (0)

400
esvg/esvg.cpp Normal file
View File

@ -0,0 +1,400 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/debug.hpp>
#include <esvg/esvg.hpp>
#include <esvg/Base.hpp>
#include <esvg/Circle.hpp>
#include <esvg/Ellipse.hpp>
#include <esvg/Line.hpp>
#include <esvg/Path.hpp>
#include <esvg/Polygon.hpp>
#include <esvg/Polyline.hpp>
#include <esvg/Rectangle.hpp>
#include <esvg/Text.hpp>
#include <esvg/Group.hpp>
#include <esvg/LinearGradient.hpp>
#include <esvg/RadialGradient.hpp>
esvg::Document::Document() {
m_uri = "";
m_version = "0.0";
m_loadOK = false;
m_size.setValue(0,0);
}
esvg::Document::~Document() {
}
void esvg::Document::displayDebug() {
ESVG_DEBUG("Main SVG: size=" << m_size);
ESVG_DEBUG(" refs:");
for (size_t iii=0; iii<m_refList.size(); iii++) {
if (m_refList[iii] != null) {
m_refList[iii]->display(2);
}
}
ESVG_DEBUG(" Nodes:");
for (size_t iii=0; iii<m_subElementList.size(); iii++) {
if (m_subElementList[iii] != null) {
m_subElementList[iii]->display(2);
}
}
}
void esvg::Document::draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level) {
for (size_t iii=0; iii<m_subElementList.size(); iii++) {
if (m_subElementList[iii] != null) {
m_subElementList[iii]->draw(_myRenderer, _basicTrans);
}
}
}
// FOR TEST only ...
void esvg::Document::generateAnImage(const etk::Uri& _uri, bool _visualDebug) {
generateAnImage(m_size, _uri, _visualDebug);
}
void esvg::Document::generateAnImage(const ivec2& _size, const etk::Uri& _uri, bool _visualDebug) {
ivec2 sizeRender = _size;
if (sizeRender.x() <= 0) {
sizeRender.setX(m_size.x());
}
if (sizeRender.y() <= 0) {
sizeRender.setY(m_size.y());
}
ESVG_DEBUG("Generate size " << sizeRender);
ememory::SharedPtr<esvg::Renderer> renderedElement = ememory::makeShared<esvg::Renderer>(sizeRender, this, _visualDebug);
// create the first element matrix modification ...
mat2x3 basicTrans;
basicTrans *= etk::mat2x3Scale(vec2(sizeRender.x()/m_size.x(), sizeRender.y()/m_size.y()));
draw(*renderedElement, basicTrans);
if (_uri.getPath().getExtention() == "ppm") {
renderedElement->writePPM(_uri);
} else if (_uri.getPath().getExtention() == "bmp") {
renderedElement->writeBMP(_uri);
} else {
ESVG_ERROR("Can not store with this extention : " << _uri << " not in .bmp/.ppm");
}
}
etk::Vector<etk::Color<float,4>> esvg::Document::renderImageFloatRGBA(ivec2& _size) {
if (_size.x() <= 0) {
_size.setX(m_size.x());
}
if (_size.y() <= 0) {
_size.setY(m_size.y());
}
ESVG_DEBUG("Generate size " << _size);
ememory::SharedPtr<esvg::Renderer> renderedElement = ememory::makeShared<esvg::Renderer>(_size, this);
// create the first element matrix modification ...
mat2x3 basicTrans;
basicTrans *= etk::mat2x3Scale(vec2(_size.x()/m_size.x(), _size.y()/m_size.y()));
draw(*renderedElement, basicTrans);
// direct return the generated data ...
return renderedElement->getData();
}
etk::Vector<etk::Color<float,3>> esvg::Document::renderImageFloatRGB(ivec2& _size) {
etk::Vector<etk::Color<float,4>> data = renderImageFloatRGBA(_size);
// Reduce scope:
etk::Vector<etk::Color<float,3>> out;
out.resize(data.size());
for (size_t iii=0; iii<data.size(); ++iii) {
out[iii] = data[iii];
}
return out;
}
etk::Vector<etk::Color<uint8_t,4>> esvg::Document::renderImageU8RGBA(ivec2& _size) {
etk::Vector<etk::Color<float,4>> data = renderImageFloatRGBA(_size);
// Reduce scope:
etk::Vector<etk::Color<uint8_t,4>> out;
out.resize(data.size());
for (size_t iii=0; iii<data.size(); ++iii) {
out[iii] = data[iii];
}
return out;
}
etk::Vector<etk::Color<uint8_t,3>> esvg::Document::renderImageU8RGB(ivec2& _size) {
etk::Vector<etk::Color<float,4>> data = renderImageFloatRGBA(_size);
// Reduce scope:
etk::Vector<etk::Color<uint8_t,3>> out;
out.resize(data.size());
for (size_t iii=0; iii<data.size(); ++iii) {
out[iii] = data[iii];
}
return out;
}
void esvg::Document::clear() {
m_uri = "";
m_version = "0.0";
m_loadOK = true;
m_paint.clear();
m_size.setValue(0,0);
}
bool esvg::Document::parse(const etk::String& _data) {
clear();
exml::Document doc;
if (doc.parse(_data) == false) {
ESVG_ERROR("Error occured when loading SVG: " << m_uri);
m_loadOK = false;
return m_loadOK;
}
if (doc.nodes.size() == 0) {
ESVG_ERROR("(l ?) No nodes in the SVG file ... '" << m_uri << "'");
m_loadOK = false;
return m_loadOK;
}
exml::Element root = doc.nodes["svg"];
if (root.exist() == false) {
ESVG_ERROR("(l ?) main node not find: 'svg' in '" << m_uri << "'");
m_loadOK = false;
return m_loadOK;
}
cleanStyleProperty(root);
m_loadOK = parseXMLData(root);
return m_loadOK;
}
bool esvg::Document::generate(etk::String& _data) {
return false;
}
bool esvg::Document::load(const etk::Uri& _uri) {
clear();
m_uri = _uri;
exml::Document doc;
if (doc.load(m_uri) == false) {
ESVG_ERROR("Error occured when loading SVG : " << m_uri);
m_loadOK = false;
return m_loadOK;
}
if (doc.nodes.size() == 0) {
ESVG_ERROR("(l ?) No nodes in the SVG file ... '" << m_uri << "'");
m_loadOK = false;
return m_loadOK;
}
exml::Element root = doc.nodes["svg"];
if (root.exist() == false) {
ESVG_ERROR("(l ?) main node not find: 'svg' in '" << m_uri << "'");
m_loadOK = false;
return m_loadOK;
}
cleanStyleProperty(root);
m_loadOK = parseXMLData(root);
return m_loadOK;
}
bool esvg::Document::store(const etk::Uri& _uri) {
ESVG_TODO("not implemented store in SVG...");
return false;
}
bool esvg::Document::cleanStyleProperty(const exml::Element& _root) {
// for each nodes:
for(auto it: _root.nodes) {
exml::Element child = it.toElement();
if (child.exist() == false) {
continue;
}
// get attribute style:
if (child.attributes.exist("style") == true) {
etk::String content = child.attributes["style"];
if (content.size() != 0) {
etk::Vector<etk::String> listStyle = etk::split(content, ';');
for (auto &it : listStyle) {
etk::Vector<etk::String> value = etk::split(it, ':');
if (value.size() != 2) {
ESVG_ERROR("parsing style with a wrong patern : " << it << " missing ':'");
continue;
}
// TODO : Check if the attibute already exist ...
child.attributes.set(value[0], value[1]);
}
}
// remove attribute style:
child.attributes.remove("style");
}
// sub-parsing ...
cleanStyleProperty(child);
}
return true;
}
bool esvg::Document::parseXMLData(const exml::Element& _root, bool _isReference) {
// get the svg version :
m_version = _root.attributes["version"];
// parse ...
vec2 pos(0,0);
if (_isReference == false) {
parseTransform(_root);
parsePosition(_root, pos, m_size);
parsePaintAttr(_root);
ESVG_VERBOSE("parsed .ROOT trans: " << m_transformMatrix);
} else {
ESVG_VERBOSE("Parse Reference section ... (no attibute)");
}
vec2 maxSize(0,0);
vec2 size(0,0);
// parse all sub node:
for(auto it : _root.nodes) {
exml::Element child = it.toElement();
if (child.exist() == false) {
// comment can be here...
continue;
}
ememory::SharedPtr<esvg::Base> elementParser;
if (child.getValue() == "g") {
elementParser = ememory::makeShared<esvg::Group>(m_paint);
} else if (child.getValue() == "a") {
ESVG_INFO("Note : 'a' balise is parsed like a g balise ...");
elementParser = ememory::makeShared<esvg::Group>(m_paint);
} else if (child.getValue() == "title") {
m_title = "TODO : set the title here ...";
continue;
} else if (child.getValue() == "path") {
elementParser = ememory::makeShared<esvg::Path>(m_paint);
} else if (child.getValue() == "rect") {
elementParser = ememory::makeShared<esvg::Rectangle>(m_paint);
} else if (child.getValue() == "circle") {
elementParser = ememory::makeShared<esvg::Circle>(m_paint);
} else if (child.getValue() == "ellipse") {
elementParser = ememory::makeShared<esvg::Ellipse>(m_paint);
} else if (child.getValue() == "line") {
elementParser = ememory::makeShared<esvg::Line>(m_paint);
} else if (child.getValue() == "polyline") {
elementParser = ememory::makeShared<esvg::Polyline>(m_paint);
} else if (child.getValue() == "polygon") {
elementParser = ememory::makeShared<esvg::Polygon>(m_paint);
} else if (child.getValue() == "text") {
elementParser = ememory::makeShared<esvg::Text>(m_paint);
} else if (child.getValue() == "radialGradient") {
if (_isReference == false) {
ESVG_ERROR("'" << child.getValue() << "' node must not be defined outside a defs Section");
continue;
} else {
elementParser = ememory::makeShared<esvg::RadialGradient>(m_paint);
}
} else if (child.getValue() == "linearGradient") {
if (_isReference == false) {
ESVG_ERROR("'" << child.getValue() << "' node must not be defined outside a defs Section");
continue;
} else {
elementParser = ememory::makeShared<esvg::LinearGradient>(m_paint);
}
} else if (child.getValue() == "defs") {
if (_isReference == true) {
ESVG_ERROR("'" << child.getValue() << "' node must not be defined in a defs Section");
continue;
} else {
bool retRefs = parseXMLData(child, true);
// TODO : Use retRefs ...
continue;
}
} else if (child.getValue() == "sodipodi:namedview") {
// Node ignore : generaly inkscape data
continue;
} else if (child.getValue() == "metadata") {
// Node ignore : generaly inkscape data
continue;
} else {
ESVG_ERROR("(l " << child.getPos() << ") node not suported : '" << child.getValue() << "' must be [title,g,a,path,rect,circle,ellipse,line,polyline,polygon,text,metadata]");
}
if (elementParser == null) {
ESVG_ERROR("(l " << child.getPos() << ") error on node: '" << child.getValue() << "' allocation error or not supported ...");
continue;
}
if (elementParser->parseXML(child, m_transformMatrix, size) == false) {
ESVG_ERROR("(l " << child.getPos() << ") error on node: '" << child.getValue() << "' Sub Parsing ERROR");
elementParser.reset();
continue;
}
if (maxSize.x()<size.x()) {
maxSize.setX(size.x());
}
if (maxSize.y()<size.y()) {
maxSize.setY(size.y());
}
// add element in the system
if (_isReference == false) {
m_subElementList.pushBack(elementParser);
} else {
m_refList.pushBack(elementParser);
}
}
if ( m_size.x() == 0
|| m_size.y()==0) {
m_size.setValue((int32_t)maxSize.x(), (int32_t)maxSize.y());
} else {
m_size.setValue((int32_t)m_size.x(), (int32_t)m_size.y());
}
if (_isReference == false) {
displayDebug();
}
return true;
}
ememory::SharedPtr<esvg::Base> esvg::Document::getReference(const etk::String& _name) {
if (_name == "") {
ESVG_ERROR("request a reference with no name ... ");
return null;
}
for (auto &it : m_refList) {
if (it == null) {
continue;
}
if (it->getId() == _name) {
return it;
}
}
ESVG_ERROR("Can not find reference name : '" << _name << "'");
return null;
}
etk::Vector<etk::Vector<vec2>> esvg::Document::getLines(vec2 _size) {
etk::Vector<etk::Vector<vec2>> out;
if (_size.x() <= 0) {
_size.setX(m_size.x());
}
if (_size.y() <= 0) {
_size.setY(m_size.y());
}
ESVG_DEBUG("lineification size " << _size);
// create the first element matrix modification ...
mat2x3 basicTrans;
basicTrans *= etk::mat2x3Scale(vec2(_size.x()/m_size.x(), _size.y()/m_size.y()));
drawShapePoints(out, 10, 0.25f, basicTrans);
return out;
}
void esvg::Document::drawShapePoints(etk::Vector<etk::Vector<vec2>>& _out,
int32_t _recurtionMax,
float _threshold,
mat2x3& _basicTrans,
int32_t _level) {
ESVG_VERBOSE(spacingDist(_level) << "DRAW shape esvg::Document");
for (auto &it : m_subElementList) {
if (it != null) {
it->drawShapePoints(_out, _recurtionMax, _threshold, _basicTrans, _level+1);
}
}
}

105
esvg/esvg.hpp Normal file
View File

@ -0,0 +1,105 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/Vector.hpp>
#include <etk/math/Vector2D.hpp>
#include <etk/uri/uri.hpp>
#include <esvg/Base.hpp>
/**
* @brief Main esvg namespace
*/
namespace esvg {
class Document : public esvg::Base {
private:
etk::Uri m_uri;
bool m_loadOK;
etk::String m_version;
etk::String m_title;
etk::Vector<ememory::SharedPtr<esvg::Base>> m_subElementList; //!< sub-element list
etk::Vector<ememory::SharedPtr<esvg::Base>> m_refList; //!< reference elements ...
vec2 m_size;
public:
Document();
~Document();
void clear();
/**
* @brief parse a string that contain an svg stream
* @param[in] _data Data to parse
* @return false : An error occured
* @return true : Parsing is OK
*/
bool parse(const etk::String& _data);
/**
* @brief generate a string that contain the created SVG
* @param[out] _data Data where the svg is stored
* @return false : An error occured
* @return true : Parsing is OK
*/
bool generate(etk::String& _data);
/**
* @brief Load the file that might contain the svg
* @param[in] _uri File of the svg
* @return false : An error occured
* @return true : Parsing is OK
*/
bool load(const etk::Uri& _uri);
/**
* @brief Store the SVG in the file
* @param[in] _uri File of the svg
* @return false : An error occured
* @return true : Parsing is OK
*/
bool store(const etk::Uri& _uri);
protected:
/**
* @brief change all style in a xml atribute
*/
virtual bool cleanStyleProperty(const exml::Element& _root);
virtual bool parseXMLData(const exml::Element& _root, bool _isReference = false);
public:
bool isLoadOk() {
return m_loadOK;
};
/**
* @brief Display all the node in the svg file.
*/
void displayDebug();
// TODO: remove this fucntion : use generic function ...
void generateAnImage(const etk::Uri& _uri, bool _visualDebug=false);
void generateAnImage(const ivec2& _size, const etk::Uri& _uri, bool _visualDebug=false);
/**
* @brief Generate Image in a specific format.
* @param[in,out] _size Size expected of the rendered image (value <=0 if it need to be automatic.) return the size generate
* @return Vector of the data used to display (simple vector: generic to transmit)
*/
etk::Vector<etk::Color<float,4>> renderImageFloatRGBA(ivec2& _size);
//! @previous
etk::Vector<etk::Color<float,3>> renderImageFloatRGB(ivec2& _size);
//! @previous
etk::Vector<etk::Color<uint8_t,4>> renderImageU8RGBA(ivec2& _size);
//! @previous
etk::Vector<etk::Color<uint8_t,3>> renderImageU8RGB(ivec2& _size);
etk::Vector<etk::Vector<vec2>> getLines(vec2 _size=vec2(256,256));
protected:
void draw(esvg::Renderer& _myRenderer, mat2x3& _basicTrans, int32_t _level=0) override;
public:
vec2 getDefinedSize() {
return m_size;
};
ememory::SharedPtr<esvg::Base> getReference(const etk::String& _name);
protected:
void drawShapePoints(etk::Vector<etk::Vector<vec2>>& _out,
int32_t _recurtionMax,
float _threshold,
mat2x3& _basicTrans,
int32_t _level=1) override;
};
}

19
esvg/gradientUnits.cpp Normal file
View File

@ -0,0 +1,19 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/gradientUnits.hpp>
#include <esvg/debug.hpp>
static const char* values[] = {
"userSpaceOnUse",
"objectBoundingBox"
};
etk::Stream& esvg::operator <<(etk::Stream& _os, enum esvg::gradientUnits _obj) {
_os << values[_obj];
return _os;
}

20
esvg/gradientUnits.hpp Normal file
View File

@ -0,0 +1,20 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/Stream.hpp>
namespace esvg {
enum gradientUnits {
gradientUnits_userSpaceOnUse,
gradientUnits_objectBoundingBox
};
/**
* @brief Debug operator To display the curent element in a Human redeable information
*/
etk::Stream& operator <<(etk::Stream& _os, enum esvg::gradientUnits _obj);
}

20
esvg/join.cpp Normal file
View File

@ -0,0 +1,20 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/join.hpp>
#include <esvg/debug.hpp>
static const char* values[] = {
"miter",
"round",
"bevel"
};
etk::Stream& esvg::operator <<(etk::Stream& _os, enum esvg::join _obj) {
_os << values[_obj];
return _os;
}

23
esvg/join.hpp Normal file
View File

@ -0,0 +1,23 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/Stream.hpp>
namespace esvg {
enum join {
join_miter,
join_round,
join_bevel
};
/**
* @brief Debug operator To display the curent element in a Human redeable information
*/
etk::Stream& operator <<(etk::Stream& _os, enum esvg::join _obj);
}

View File

@ -0,0 +1,452 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/debug.hpp>
#include <esvg/render/DynamicColor.hpp>
#include <esvg/LinearGradient.hpp>
#include <esvg/RadialGradient.hpp>
#include <esvg/esvg.hpp>
esvg::render::DynamicColorSpecial::DynamicColorSpecial(const etk::String& _link, const mat2x3& _mtx) :
m_linear(true),
m_colorName(_link),
m_matrix(_mtx),
m_viewPort(vec2(9999999999.0,9999999999.0),vec2(-9999999999.0,-9999999999.0)) {
}
void esvg::render::DynamicColorSpecial::setViewPort(const etk::Pair<vec2, vec2>& _viewPort) {
m_viewPort = _viewPort;
}
static vec2 getIntersect(const vec2& _point1,
const vec2& _vect1,
const vec2& _point2,
const vec2& _vect2) {
float diviseur = _vect1.x() * _vect2.y() - _vect1.y() * _vect2.x();
if(diviseur != 0.0f) {
float mmm = ( _vect1.x() * _point1.y()
- _vect1.x() * _point2.y()
- _vect1.y() * _point1.x()
+ _vect1.y() * _point2.x()
) / diviseur;
return vec2(_point2 + _vect2 * mmm);
}
ESVG_ERROR("Get divider / 0.0f");
return _point2;
}
etk::Color<float,4> esvg::render::DynamicColorSpecial::getColor(const ivec2& _pos) const {
if (m_data.size() < 2) {
return etk::color::purple;
}
if (m_linear == true) {
return getColorLinear(_pos);
} else {
return getColorRadial(_pos);
}
return etk::color::purple;
}
etk::Color<float,4> esvg::render::DynamicColorSpecial::getColorLinear(const ivec2& _pos) const {
float ratio = 0.0f;
if (m_unit == gradientUnits_userSpaceOnUse) {
vec2 vectorBase = m_pos2 - m_pos1;
vec2 vectorOrtho(vectorBase.y(), -vectorBase.x());
vec2 intersec = getIntersect(m_pos1, vectorBase,
vec2(_pos.x(), _pos.y()), vectorOrtho);
float baseSize = vectorBase.length();
vec2 vectorBaseDraw = intersec - m_pos1;
float baseDraw = vectorBaseDraw.length();
ratio = baseDraw / baseSize;
switch(m_spread) {
case spreadMethod_pad:
if (vectorBase.dot(vectorBaseDraw) < 0) {
ratio *= -1.0;
}
break;
case spreadMethod_reflect:
ratio -= float((int32_t(ratio)>>1)<<1);
if (ratio > 1.0f) {
ratio = 2.0f-ratio;
}
break;
case spreadMethod_repeat:
if (vectorBase.dot(vectorBaseDraw) < 0) {
ratio *= -1.0;
}
ratio -= float(int32_t(ratio));
if (ratio <0.0f) {
#ifndef __STDCPP_LLVM__
ratio = 1.0f-etk::abs(ratio);
#else
ratio = 1.0f-abs(ratio);
#endif
}
break;
}
} else {
// in the basic vertion of the gradient the color is calculated with the ration in X and Y in the bonding box associated (it is rotate with the object..
vec2 intersecX = getIntersect(m_pos1, m_axeX,
vec2(_pos.x(), _pos.y()), m_axeY);
vec2 intersecY = getIntersect(m_pos1, m_axeY,
vec2(_pos.x(), _pos.y()), m_axeX);
vec2 vectorBaseDrawX = intersecX - m_pos1;
vec2 vectorBaseDrawY = intersecY - m_pos1;
float baseDrawX = vectorBaseDrawX.length();
float baseDrawY = vectorBaseDrawY.length();
if (m_axeX.dot(vectorBaseDrawX) < 0) {
baseDrawX *= -1.0f;
}
if (m_axeY.dot(vectorBaseDrawY) < 0) {
baseDrawY *= -1.0f;
}
if (m_baseSize.x()+m_baseSize.y() != 0.0f) {
if ( m_baseSize.x() != 0.0f
&& m_baseSize.y() != 0.0f) {
ratio = (baseDrawX*m_baseSize.y() + baseDrawY*m_baseSize.x())/(m_baseSize.x()*m_baseSize.y()*2.0f);
} else if (m_baseSize.x() != 0.0f) {
ratio = baseDrawX/m_baseSize.x();
} else {
ratio = baseDrawY/m_baseSize.y();
}
} else {
ratio = 1.0f;
}
switch(m_spread) {
case spreadMethod_pad:
// nothing to do ...
break;
case spreadMethod_reflect:
#ifndef __STDCPP_LLVM__
ratio = etk::abs(ratio);
#else
ratio = abs(ratio);
#endif
ratio -= float((int32_t(ratio)>>1)<<1);
if (ratio > 1.0f) {
ratio = 2.0f-ratio;
}
break;
case spreadMethod_repeat:
ratio -= float(int32_t(ratio));
if (ratio <0.0f) {
#ifndef __STDCPP_LLVM__
ratio = 1.0f-etk::abs(ratio);
#else
ratio = 1.0f-abs(ratio);
#endif
}
break;
}
}
if (ratio <= m_data[0].first*0.01f) {
return m_data[0].second;
}
if (ratio >= m_data.back().first*0.01f) {
return m_data.back().second;
}
for (size_t iii=1; iii<m_data.size(); ++iii) {
if (ratio <= m_data[iii].first*0.01f) {
float localRatio = ratio - m_data[iii-1].first*0.01f;
localRatio = localRatio / ((m_data[iii].first - m_data[iii-1].first) * 0.01f);
return etk::Color<float,4>(m_data[iii-1].second.r() * (1.0-localRatio) + m_data[iii].second.r() * localRatio,
m_data[iii-1].second.g() * (1.0-localRatio) + m_data[iii].second.g() * localRatio,
m_data[iii-1].second.b() * (1.0-localRatio) + m_data[iii].second.b() * localRatio,
m_data[iii-1].second.a() * (1.0-localRatio) + m_data[iii].second.a() * localRatio);
}
}
return etk::color::green;
}
static etk::Pair<vec2,vec2> intersectLineToCircle(const vec2& _pos1,
const vec2& _pos2,
const vec2& _center = vec2(0.0f, 0.0f),
float _radius = 1.0f) {
vec2 v1;
vec2 v2;
//vector2D from point 1 to point 2
v1 = _pos2 - _pos1;
//vector2D from point 1 to the circle's center
v2 = _center - _pos1;
float dot = v1.dot(v2);
vec2 proj1 = vec2(((dot / (v1.length2())) * v1.x()),
((dot / (v1.length2())) * v1.y()));
vec2 midpt = _pos1 + proj1;
float distToCenter = (midpt - _center).length2();
if (distToCenter > _radius * _radius) {
return etk::Pair<vec2,vec2>(vec2(0.0,0.0), vec2(0.0,0.0));
}
if (distToCenter == _radius * _radius) {
return etk::Pair<vec2,vec2>(midpt, midpt);
}
float distToIntersection;
if (distToCenter == 0.0f) {
distToIntersection = _radius;
} else {
#ifndef __STDCPP_LLVM__
distToCenter = etk::sqrt(distToCenter);
distToIntersection = etk::sqrt(_radius * _radius - distToCenter * distToCenter);
#else
distToCenter = sqrtf(distToCenter);
distToIntersection = sqrtf(_radius * _radius - distToCenter * distToCenter);
#endif
}
// normalize...
v1.safeNormalize();
v1 *= distToIntersection;
return etk::Pair<vec2,vec2>(midpt + v1, midpt - v1);
}
etk::Color<float,4> esvg::render::DynamicColorSpecial::getColorRadial(const ivec2& _pos) const {
float ratio = 0.0f;
// in the basic vertion of the gradient the color is calculated with the ration in X and Y in the bonding box associated (it is rotate with the object)..
vec2 intersecX = getIntersect(m_pos1, m_axeX,
vec2(_pos.x(), _pos.y()), m_axeY);
vec2 intersecY = getIntersect(m_pos1, m_axeY,
vec2(_pos.x(), _pos.y()), m_axeX);
vec2 vectorBaseDrawX = intersecX - m_pos1;
vec2 vectorBaseDrawY = intersecY - m_pos1;
float baseDrawX = vectorBaseDrawX.length();
float baseDrawY = vectorBaseDrawY.length();
// specal case when focal == center (this is faster ...)
if (m_centerIsFocal == true) {
ratio = vec2(baseDrawX, baseDrawY).length();
if (m_baseSize.x()+m_baseSize.y() != 0.0f) {
if ( m_baseSize.x() != 0.0f
&& m_baseSize.y() != 0.0f) {
ratio = vec2(baseDrawX/m_baseSize.x(), baseDrawY/m_baseSize.y()).length();
} else if (m_baseSize.x() != 0.0f) {
ratio = baseDrawX/m_baseSize.x();
} else {
ratio = baseDrawY/m_baseSize.y();
}
} else {
ratio = 1.0f;
}
} else {
// set the sense of the elements:
if (m_axeX.dot(vectorBaseDrawX) < 0) {
baseDrawX *= -1.0f;
}
if (m_axeY.dot(vectorBaseDrawY) < 0) {
baseDrawY *= -1.0f;
}
if (m_baseSize.y() != 0.0f) {
baseDrawY /= m_baseSize.y();
}
// normalize to 1.0f
baseDrawX /= m_baseSize.x();
if ( m_clipOut == true
&& baseDrawX <= -1.0f) {
ratio = 1.0f;
} else {
float tmpLength = -m_focalLength/m_baseSize.x();
vec2 focalCenter = vec2(tmpLength, 0.0f);
vec2 currentPoint = vec2(baseDrawX, baseDrawY);
if (focalCenter == currentPoint) {
ratio = 0.0f;
} else {
etk::Pair<vec2,vec2> positions = intersectLineToCircle(focalCenter, currentPoint);
float lenghtBase = (currentPoint - focalCenter).length();
float lenghtBorder1 = (positions.first - focalCenter).length();
float lenghtBorder2 = (positions.second - focalCenter).length();
ratio = lenghtBase/lenghtBorder1;
}
}
}
switch(m_spread) {
case spreadMethod_pad:
// nothing to do ...
break;
case spreadMethod_reflect:
ratio -= float((int32_t(ratio)>>1)<<1);
if (ratio > 1.0f) {
ratio = 2.0f-ratio;
}
break;
case spreadMethod_repeat:
ratio -= float(int32_t(ratio));
if (ratio <0.0f) {
#ifndef __STDCPP_LLVM__
ratio = 1.0f-etk::abs(ratio);
#else
ratio = 1.0f-abs(ratio);
#endif
}
break;
}
if (ratio <= m_data[0].first*0.01f) {
return m_data[0].second;
}
if (ratio >= m_data.back().first*0.01f) {
return m_data.back().second;
}
for (size_t iii=1; iii<m_data.size(); ++iii) {
if (ratio <= m_data[iii].first*0.01f) {
float localRatio = ratio - m_data[iii-1].first*0.01f;
localRatio = localRatio / ((m_data[iii].first - m_data[iii-1].first) * 0.01f);
return etk::Color<float,4>(m_data[iii-1].second.r() * (1.0-localRatio) + m_data[iii].second.r() * localRatio,
m_data[iii-1].second.g() * (1.0-localRatio) + m_data[iii].second.g() * localRatio,
m_data[iii-1].second.b() * (1.0-localRatio) + m_data[iii].second.b() * localRatio,
m_data[iii-1].second.a() * (1.0-localRatio) + m_data[iii].second.a() * localRatio);
}
}
return etk::color::green;
}
void esvg::render::DynamicColorSpecial::generate(esvg::Document* _document) {
if (_document == null) {
ESVG_ERROR("Get null input for document");
return;
}
ememory::SharedPtr<esvg::Base> base = _document->getReference(m_colorName);
if (base == null) {
ESVG_ERROR("Can not get base : '" << m_colorName << "'");
return;
}
// Now we can know if we use linear or radial gradient ...
ememory::SharedPtr<esvg::LinearGradient> gradient = ememory::dynamicPointerCast<esvg::LinearGradient>(base);
if (gradient != null) {
m_linear = true;
ESVG_VERBOSE("get for color linear:");
gradient->display(2);
m_unit = gradient->m_unit;
m_spread = gradient->m_spread;
ESVG_VERBOSE(" viewport = {" << m_viewPort.first << "," << m_viewPort.second << "}");
vec2 size = m_viewPort.second - m_viewPort.first;
esvg::Dimension dimPos1 = gradient->getPosition1();
m_pos1 = dimPos1.getPixel(size);
if (dimPos1.getType() == esvg::distance_pourcent) {
m_pos1 += m_viewPort.first;
}
esvg::Dimension dimPos2 = gradient->getPosition2();
m_pos2 = dimPos2.getPixel(size);
if (dimPos2.getType() == esvg::distance_pourcent) {
m_pos2 += m_viewPort.first;
}
// in the basic vertion of the gradient the color is calculated with the ration in X and Y in the bonding box associated (it is rotate with the object..
vec2 delta = m_pos2 - m_pos1;
if (delta.x() < 0.0f) {
m_axeX = vec2(-1.0f, 0.0f);
} else {
m_axeX = vec2(1.0f, 0.0f);
}
if (delta.y() < 0.0f) {
m_axeY = vec2(0.0f, -1.0f);
} else {
m_axeY = vec2(0.0f, 1.0f);
}
// Move the positions ...
m_pos1 = m_matrix * m_pos1;
m_pos2 = m_matrix * m_pos2;
m_axeX = m_matrix.applyScaleRotation(m_axeX);
m_axeY = m_matrix.applyScaleRotation(m_axeY);
// in the basic vertion of the gradient the color is calculated with the ration in X and Y in the bonding box associated (it is rotate with the object..
vec2 intersecX = getIntersect(m_pos1, m_axeX,
m_pos2, m_axeY);
vec2 intersecY = getIntersect(m_pos1, m_axeY,
m_pos2, m_axeX);
m_baseSize = vec2((m_pos1 - intersecX).length(),
(m_pos1 - intersecY).length());
// get all the colors
m_data = gradient->getColors(_document);
} else {
m_linear = false;
ememory::SharedPtr<esvg::RadialGradient> gradient = ememory::dynamicPointerCast<esvg::RadialGradient>(base);
if (gradient == null) {
ESVG_ERROR("Can not cast in a linear gradient: '" << m_colorName << "' ==> wrong type");
return;
}
ESVG_VERBOSE("get for color Radial:");
gradient->display(2);
m_unit = gradient->m_unit;
m_spread = gradient->m_spread;
ESVG_VERBOSE(" viewport = {" << m_viewPort.first << "," << m_viewPort.second << "}");
vec2 size = m_viewPort.second - m_viewPort.first;
esvg::Dimension dimCenter = gradient->getCenter();
vec2 center = dimCenter.getPixel(size);
if (dimCenter.getType() == esvg::distance_pourcent) {
center += m_viewPort.first;
}
esvg::Dimension dimFocal = gradient->getFocal();
vec2 focal = dimFocal.getPixel(size);
if (dimFocal.getType() == esvg::distance_pourcent) {
focal += m_viewPort.first;
}
esvg::Dimension1D dimRadius = gradient->getRadius();
// in the basic vertion of the gradient the color is calculated with the ration in X and Y in the bonding box associated (it is rotate with the object)..
if (center == focal) {
m_centerIsFocal = true;
m_pos2.setX(dimRadius.getPixel(size.x()));
m_pos2.setY(dimRadius.getPixel(size.y()));
m_pos2 += center;
vec2 delta = center - m_pos2;
if (delta.x() < 0.0f) {
m_axeX = vec2(-1.0f, 0.0f);
} else {
m_axeX = vec2(1.0f, 0.0f);
}
if (delta.y() < 0.0f) {
m_axeY = vec2(0.0f, -1.0f);
} else {
m_axeY = vec2(0.0f, 1.0f);
}
m_pos1 = center;
} else {
m_centerIsFocal = false;
m_axeX = (center - focal).safeNormalize();
m_axeY = vec2(m_axeX.y(), -m_axeX.x());
m_pos2 = m_axeX * dimRadius.getPixel(size.x()) + m_axeY * dimRadius.getPixel(size.y());
m_pos2 += center;
m_pos1 = center;
}
// Move the positions ...
m_pos1 = m_matrix * m_pos1;
center = m_matrix * center;
m_pos2 = m_matrix * m_pos2;
m_axeX = m_matrix.applyScaleRotation(m_axeX);
m_axeY = m_matrix.applyScaleRotation(m_axeY);
// in the basic vertion of the gradient the color is calculated with the ration in X and Y in the bonding box associated (it is rotate with the object..
vec2 intersecX = getIntersect(m_pos1, m_axeX,
m_pos2, m_axeY);
vec2 intersecY = getIntersect(m_pos1, m_axeY,
m_pos2, m_axeX);
m_baseSize = vec2((intersecX - m_pos1).length(),
(intersecY - m_pos1).length());
if (m_centerIsFocal == false) {
m_focalLength = (center - m_matrix * focal).length();
if (m_focalLength >= m_baseSize.x()) {
ESVG_DEBUG("Change position of the Focal ... ==> set it inside the circle");
m_focalLength = m_baseSize.x()*0.999998f;
m_clipOut = true;
} else {
m_clipOut = false;
}
}
ESVG_VERBOSE("baseSize=" << m_baseSize << " m_pos1=" << m_pos1 << " dim=" << dimCenter << " m_focal=" << m_focal << " m_pos2=" << m_pos2 << " dim=" << dimRadius);
// get all the colors
m_data = gradient->getColors(_document);
}
}
ememory::SharedPtr<esvg::render::DynamicColor> esvg::render::createColor(etk::Pair<etk::Color<float,4>, etk::String> _color, const mat2x3& _mtx) {
// Check if need to create a color:
if ( _color.first.a() == 0x00
&& _color.second == "") {
return null;
}
if (_color.second != "") {
return ememory::makeShared<esvg::render::DynamicColorSpecial>(_color.second, _mtx);
}
return ememory::makeShared<esvg::render::DynamicColorUni>(_color.first);
}

View File

@ -0,0 +1,80 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <ememory/memory.hpp>
#include <etk/types.hpp>
#include <etk/Pair.hpp>
#include <etk/Color.hpp>
#include <etk/math/Vector2D.hpp>
#include <etk/math/Matrix2x3.hpp>
#include <esvg/gradientUnits.hpp>
#include <esvg/spreadMethod.hpp>
namespace esvg {
class Document;
namespace render {
class DynamicColor {
public:
DynamicColor() {
// nothing to do ...
}
virtual ~DynamicColor() {};
virtual etk::Color<float,4> getColor(const ivec2& _pos) const = 0;
virtual void generate(esvg::Document* _document) = 0;
virtual void setViewPort(const etk::Pair<vec2, vec2>& _viewPort) = 0;
};
class DynamicColorUni : public esvg::render::DynamicColor {
public:
etk::Color<float,4> m_color;
public:
DynamicColorUni(const etk::Color<float,4>& _color) :
m_color(_color) {
}
virtual etk::Color<float,4> getColor(const ivec2& _pos) const {
return m_color;
}
virtual void generate(esvg::Document* _document) {
// nothing to do ...
}
virtual void setViewPort(const etk::Pair<vec2, vec2>& _viewPort) {
// nothing to do ...
};
};
class DynamicColorSpecial : public esvg::render::DynamicColor {
public:
bool m_linear;
esvg::spreadMethod m_spread;
esvg::gradientUnits m_unit;
etk::String m_colorName;
mat2x3 m_matrix;
etk::Pair<vec2, vec2> m_viewPort;
vec2 m_pos1; // in radius ==> center
vec2 m_pos2; // in radius ==> radius end position
vec2 m_focal; // Specific radius
vec2 m_axeX;
vec2 m_axeY;
vec2 m_baseSize;
float m_focalLength;
bool m_clipOut;
bool m_centerIsFocal;
etk::Vector<etk::Pair<float, etk::Color<float,4>>> m_data;
public:
DynamicColorSpecial(const etk::String& _link, const mat2x3& _mtx);
virtual etk::Color<float,4> getColor(const ivec2& _pos) const;
private:
etk::Color<float,4> getColorLinear(const ivec2& _pos) const;
etk::Color<float,4> getColorRadial(const ivec2& _pos) const;
public:
virtual void generate(esvg::Document* _document);
virtual void setViewPort(const etk::Pair<vec2, vec2>& _viewPort);
};
ememory::SharedPtr<DynamicColor> createColor(etk::Pair<etk::Color<float,4>, etk::String> _color, const mat2x3& _mtx);
}
}

57
esvg/render/Element.cpp Normal file
View File

@ -0,0 +1,57 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/render/Element.hpp>
#include <esvg/debug.hpp>
etk::Stream& esvg::operator <<(etk::Stream& _os, enum esvg::render::path _obj) {
switch (_obj) {
case esvg::render::path_stop:
_os << "path_stop";
break;
case esvg::render::path_close:
_os << "path_close";
break;
case esvg::render::path_moveTo:
_os << "path_moveTo";
break;
case esvg::render::path_lineTo:
_os << "path_lineTo";
break;
case esvg::render::path_lineToH:
_os << "path_lineToH";
break;
case esvg::render::path_lineToV:
_os << "path_lineToV";
break;
case esvg::render::path_curveTo:
_os << "path_curveTo";
break;
case esvg::render::path_smoothCurveTo:
_os << "path_smoothCurveTo";
break;
case esvg::render::path_bezierCurveTo:
_os << "path_bezierCurveTo";
break;
case esvg::render::path_bezierSmoothCurveTo:
_os << "path_bezierSmoothCurveTo";
break;
case esvg::render::path_elliptic:
_os << "path_elliptic";
break;
default:
_os << "????";
break;
};
return _os;
}
etk::Stream& esvg::operator <<(etk::Stream& _os, const esvg::render::Element& _obj) {
_os << _obj.getType();
_os << ": rel=" << etk::toString(_obj.getRelative()) << " ";
_os << _obj.display();
return _os;
}

101
esvg/render/Element.hpp Normal file
View File

@ -0,0 +1,101 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
namespace esvg {
namespace render {
enum path {
path_stop,
path_close,
path_moveTo,
path_lineTo,
path_lineToH,
path_lineToV,
path_curveTo,
path_smoothCurveTo,
path_bezierCurveTo,
path_bezierSmoothCurveTo,
path_elliptic
};
class Element {
public:
Element(enum path _type, bool _relative=false) :
m_cmd(_type),
m_relative(_relative) {
}
virtual ~Element() { }
private:
enum path m_cmd;
public:
enum path getType() const {
return m_cmd;
}
protected:
bool m_relative;
public:
bool getRelative() const {
return m_relative;
}
void setRelative(bool _relative) {
m_relative = _relative;
}
protected:
vec2 m_pos;
public:
const vec2& getPos() const {
return m_pos;
}
void setPos(const vec2& _val) {
m_pos = _val;
}
protected:
vec2 m_pos1;
public:
const vec2& getPos1() const {
return m_pos1;
}
void setPos1(const vec2& _val) {
m_pos1 = _val;
}
protected:
vec2 m_pos2;
public:
const vec2& getPos2() const {
return m_pos2;
}
void setPos2(const vec2& _val) {
m_pos2 = _val;
}
public:
virtual etk::String display() const = 0;
};
}
/**
* @brief Debug operator To display the curent element in a Human redeable information
*/
etk::Stream& operator <<(etk::Stream& _os, const esvg::render::Element& _obj);
/**
* @brief Debug operator To display the curent element in a Human redeable information
*/
etk::Stream& operator <<(etk::Stream& _os, enum esvg::render::path _obj);
}
#include <esvg/render/ElementStop.hpp>
#include <esvg/render/ElementClose.hpp>
#include <esvg/render/ElementMoveTo.hpp>
#include <esvg/render/ElementLineTo.hpp>
#include <esvg/render/ElementLineToH.hpp>
#include <esvg/render/ElementLineToV.hpp>
#include <esvg/render/ElementCurveTo.hpp>
#include <esvg/render/ElementSmoothCurveTo.hpp>
#include <esvg/render/ElementBezierCurveTo.hpp>
#include <esvg/render/ElementBezierSmoothCurveTo.hpp>
#include <esvg/render/ElementElliptic.hpp>

View File

@ -0,0 +1,18 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/render/Element.hpp>
#include <esvg/debug.hpp>
esvg::render::ElementBezierCurveTo::ElementBezierCurveTo(bool _relative, const vec2& _pos1, const vec2& _pos):
Element(esvg::render::path_bezierCurveTo, _relative) {
m_pos = _pos;
m_pos1 = _pos1;
}
etk::String esvg::render::ElementBezierCurveTo::display() const {
return etk::String("pos=") + etk::toString(m_pos) + " pos1=" + etk::toString(m_pos1);
}

View File

@ -0,0 +1,22 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
#include <esvg/render/Element.hpp>
namespace esvg {
namespace render {
class ElementBezierCurveTo : public esvg::render::Element {
public:
ElementBezierCurveTo(bool _relative, const vec2& _pos1, const vec2& _pos);
public:
virtual etk::String display() const;
};
}
}

View File

@ -0,0 +1,18 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/render/Element.hpp>
#include <esvg/debug.hpp>
esvg::render::ElementBezierSmoothCurveTo::ElementBezierSmoothCurveTo(bool _relative, const vec2& _pos):
Element(esvg::render::path_bezierSmoothCurveTo, _relative) {
m_pos = _pos;
}
etk::String esvg::render::ElementBezierSmoothCurveTo::display() const {
return etk::String("pos=") + etk::toString(m_pos);
}

View File

@ -0,0 +1,23 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
#include <esvg/render/Element.hpp>
namespace esvg {
namespace render {
class ElementBezierSmoothCurveTo : public esvg::render::Element {
public:
ElementBezierSmoothCurveTo(bool _relative, const vec2& _pos);
public:
virtual etk::String display() const;
};
}
}

View File

@ -0,0 +1,19 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/render/Element.hpp>
#include <esvg/debug.hpp>
esvg::render::ElementClose::ElementClose(bool _relative):
Element(esvg::render::path_close, _relative) {
}
etk::String esvg::render::ElementClose::display() const {
return "";
}

View File

@ -0,0 +1,22 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
#include <esvg/render/Element.hpp>
namespace esvg {
namespace render {
class ElementClose : public esvg::render::Element {
public:
ElementClose(bool _relative=false);
public:
virtual etk::String display() const;
};
}
}

View File

@ -0,0 +1,21 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/render/Element.hpp>
#include <esvg/debug.hpp>
esvg::render::ElementCurveTo::ElementCurveTo(bool _relative, const vec2& _pos1, const vec2& _pos2, const vec2& _pos):
Element(esvg::render::path_curveTo, _relative) {
m_pos = _pos;
m_pos1 = _pos1;
m_pos2 = _pos2;
}
etk::String esvg::render::ElementCurveTo::display() const {
return etk::String("pos=") + etk::toString(m_pos) + " pos1=" + etk::toString(m_pos1) + " pos2=" + etk::toString(m_pos2);
}

View File

@ -0,0 +1,21 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
#include <esvg/render/Element.hpp>
namespace esvg {
namespace render {
class ElementCurveTo : public esvg::render::Element {
public:
ElementCurveTo(bool _relative, const vec2& _pos1, const vec2& _pos2, const vec2& _pos);
public:
virtual etk::String display() const;
};
}
}

View File

@ -0,0 +1,31 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/render/Element.hpp>
#include <esvg/debug.hpp>
esvg::render::ElementElliptic::ElementElliptic(bool _relative,
const vec2& _radius, // in m_vec1
float _angle,
bool _largeArcFlag,
bool _sweepFlag,
const vec2& _pos):
Element(esvg::render::path_elliptic, _relative) {
m_pos1 = _radius;
m_pos = _pos;
m_angle = _angle;
m_largeArcFlag = _largeArcFlag;
m_sweepFlag = _sweepFlag;
}
etk::String esvg::render::ElementElliptic::display() const {
return etk::String("pos=") + etk::toString(m_pos)
+ " radius=" + etk::toString(m_pos1)
+ " angle=" + etk::toString(m_angle)
+ " largeArcFlag=" + etk::toString(m_largeArcFlag)
+ " sweepFlag=" + etk::toString(m_sweepFlag);
}

View File

@ -0,0 +1,31 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
#include <esvg/render/Element.hpp>
namespace esvg {
namespace render {
class ElementElliptic : public esvg::render::Element {
public:
float m_angle;
bool m_largeArcFlag;
bool m_sweepFlag;
public:
ElementElliptic(bool _relative,
const vec2& _radius, // in m_pos1
float _angle,
bool _largeArcFlag,
bool _sweepFlag,
const vec2& _pos);
public:
virtual etk::String display() const;
};
}
}

View File

@ -0,0 +1,18 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/render/Element.hpp>
#include <esvg/debug.hpp>
esvg::render::ElementLineTo::ElementLineTo(bool _relative, const vec2& _pos):
Element(esvg::render::path_lineTo, _relative) {
m_pos = _pos;
}
etk::String esvg::render::ElementLineTo::display() const {
return etk::String("pos=") + etk::toString(m_pos);
}

View File

@ -0,0 +1,22 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
#include <esvg/render/Element.hpp>
namespace esvg {
namespace render {
class ElementLineTo : public esvg::render::Element {
public:
ElementLineTo(bool _relative, const vec2& _pos);
public:
virtual etk::String display() const;
};
}
}

View File

@ -0,0 +1,18 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/render/Element.hpp>
#include <esvg/debug.hpp>
esvg::render::ElementLineToH::ElementLineToH(bool _relative, float _posX):
Element(esvg::render::path_lineToH, _relative) {
m_pos = vec2(_posX, 0.0f);
}
etk::String esvg::render::ElementLineToH::display() const {
return etk::String("posX=") + etk::toString(m_pos.x());
}

View File

@ -0,0 +1,22 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
#include <esvg/render/Element.hpp>
namespace esvg {
namespace render {
class ElementLineToH : public esvg::render::Element {
public:
ElementLineToH(bool _relative, float _posX);
public:
virtual etk::String display() const;
};
}
}

View File

@ -0,0 +1,18 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/render/Element.hpp>
#include <esvg/debug.hpp>
esvg::render::ElementLineToV::ElementLineToV(bool _relative, float _posY):
Element(esvg::render::path_lineToV, _relative) {
m_pos = vec2(0.0f, _posY);
}
etk::String esvg::render::ElementLineToV::display() const {
return etk::String("posY=") + etk::toString(m_pos.y());
}

View File

@ -0,0 +1,23 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
#include <esvg/render/Element.hpp>
namespace esvg {
namespace render {
class ElementLineToV : public esvg::render::Element {
public:
ElementLineToV(bool _relative, float _posY);
public:
virtual etk::String display() const;
};
}
}

View File

@ -0,0 +1,18 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/render/Element.hpp>
#include <esvg/debug.hpp>
esvg::render::ElementMoveTo::ElementMoveTo(bool _relative, const vec2& _pos):
Element(esvg::render::path_moveTo, _relative) {
m_pos = _pos;
}
etk::String esvg::render::ElementMoveTo::display() const {
return etk::String("pos=") + etk::toString(m_pos);
}

View File

@ -0,0 +1,22 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
#include <esvg/render/Element.hpp>
namespace esvg {
namespace render {
class ElementMoveTo : public esvg::render::Element {
public:
ElementMoveTo(bool _relative, const vec2& _pos);
public:
virtual etk::String display() const;
};
}
}

View File

@ -0,0 +1,19 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/render/Element.hpp>
#include <esvg/debug.hpp>
esvg::render::ElementSmoothCurveTo::ElementSmoothCurveTo(bool _relative, const vec2& _pos2, const vec2& _pos):
Element(esvg::render::path_smoothCurveTo, _relative) {
m_pos = _pos;
m_pos2 = _pos2;
}
etk::String esvg::render::ElementSmoothCurveTo::display() const {
return etk::String("pos=") + etk::toString(m_pos) + " pos2=" + etk::toString(m_pos2);
}

View File

@ -0,0 +1,22 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
#include <esvg/render/Element.hpp>
namespace esvg {
namespace render {
class ElementSmoothCurveTo : public esvg::render::Element {
public:
ElementSmoothCurveTo(bool _relative, const vec2& _pos2, const vec2& _pos);
public:
virtual etk::String display() const;
};
}
}

View File

@ -0,0 +1,19 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/render/Element.hpp>
#include <esvg/debug.hpp>
esvg::render::ElementStop::ElementStop():
Element(esvg::render::path_stop) {
}
etk::String esvg::render::ElementStop::display() const {
return "";
}

View File

@ -0,0 +1,22 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
#include <esvg/render/Element.hpp>
namespace esvg {
namespace render {
class ElementStop : public esvg::render::Element {
public:
ElementStop();
public:
virtual etk::String display() const;
};
}
}

513
esvg/render/Path.cpp Normal file
View File

@ -0,0 +1,513 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/debug.hpp>
#include <esvg/render/Path.hpp>
#include <esvg/render/Element.hpp>
void esvg::render::Path::clear() {
m_listElement.clear();
}
void esvg::render::Path::stop() {
m_listElement.pushBack(ememory::makeShared<esvg::render::ElementStop>());
}
void esvg::render::Path::close(bool _relative) {
m_listElement.pushBack(ememory::makeShared<esvg::render::ElementClose>(_relative));
}
void esvg::render::Path::moveTo(bool _relative, const vec2& _pos) {
m_listElement.pushBack(ememory::makeShared<esvg::render::ElementMoveTo>(_relative, _pos));
}
void esvg::render::Path::lineTo(bool _relative, const vec2& _pos) {
m_listElement.pushBack(ememory::makeShared<esvg::render::ElementLineTo>(_relative, _pos));
}
void esvg::render::Path::lineToH(bool _relative, float _posX) {
m_listElement.pushBack(ememory::makeShared<esvg::render::ElementLineToH>(_relative, _posX));
}
void esvg::render::Path::lineToV(bool _relative, float _posY) {
m_listElement.pushBack(ememory::makeShared<esvg::render::ElementLineToV>(_relative, _posY));
}
void esvg::render::Path::curveTo(bool _relative, const vec2& _pos1, const vec2& _pos2, const vec2& _pos) {
m_listElement.pushBack(ememory::makeShared<esvg::render::ElementCurveTo>(_relative, _pos1, _pos2, _pos));
}
void esvg::render::Path::smoothCurveTo(bool _relative, const vec2& _pos2, const vec2& _pos) {
m_listElement.pushBack(ememory::makeShared<esvg::render::ElementSmoothCurveTo>(_relative, _pos2, _pos));
}
void esvg::render::Path::bezierCurveTo(bool _relative, const vec2& _pos1, const vec2& _pos) {
m_listElement.pushBack(ememory::makeShared<esvg::render::ElementBezierCurveTo>(_relative, _pos1, _pos));
}
void esvg::render::Path::bezierSmoothCurveTo(bool _relative, const vec2& _pos) {
m_listElement.pushBack(ememory::makeShared<esvg::render::ElementBezierSmoothCurveTo>(_relative, _pos));
}
void esvg::render::Path::ellipticTo(bool _relative,
const vec2& _radius,
float _angle,
bool _largeArcFlag,
bool _sweepFlag,
const vec2& _pos) {
m_listElement.pushBack(ememory::makeShared<esvg::render::ElementElliptic>(_relative, _radius, _angle, _largeArcFlag, _sweepFlag, _pos));
}
static const char* spacingDist(int32_t _spacing) {
static const char *tmpValue = " ";
if (_spacing>20) {
_spacing = 20;
}
return tmpValue + 20*4 - _spacing*4;
}
void esvg::render::Path::display(int32_t _spacing) {
ESVG_DEBUG(spacingDist(_spacing) << "Path");
for(auto &it : m_listElement) {
if (it == null) {
continue;
}
ESVG_DEBUG(spacingDist(_spacing+1) << *it);
}
}
void interpolateCubicBezier(etk::Vector<esvg::render::Point>& _listPoint,
int32_t _recurtionMax,
float _threshold,
vec2 _pos1,
vec2 _pos2,
vec2 _pos3,
vec2 _pos4,
int32_t _level,
enum esvg::render::Point::type _type) {
if (_level > _recurtionMax) {
return;
}
vec2 pos12 = (_pos1+_pos2)*0.5f;
vec2 pos23 = (_pos2+_pos3)*0.5f;
vec2 pos34 = (_pos3+_pos4)*0.5f;
vec2 delta = _pos4 - _pos1;
#ifndef __STDCPP_LLVM__
float distance2 = etk::abs(((_pos2.x() - _pos4.x()) * delta.y() - (_pos2.y() - _pos4.y()) * delta.x() ));
float distance3 = etk::abs(((_pos3.x() - _pos4.x()) * delta.y() - (_pos3.y() - _pos4.y()) * delta.x() ));
#else
float distance2 = fabs(((_pos2.x() - _pos4.x()) * delta.y() - (_pos2.y() - _pos4.y()) * delta.x() ));
float distance3 = fabs(((_pos3.x() - _pos4.x()) * delta.y() - (_pos3.y() - _pos4.y()) * delta.x() ));
#endif
if ((distance2 + distance3)*(distance2 + distance3) < _threshold * delta.length2()) {
_listPoint.pushBack(esvg::render::Point(_pos4, _type) );
return;
}
vec2 pos123 = (pos12+pos23)*0.5f;
vec2 pos234 = (pos23+pos34)*0.5f;
vec2 pos1234 = (pos123+pos234)*0.5f;
interpolateCubicBezier(_listPoint, _recurtionMax, _threshold, _pos1, pos12, pos123, pos1234, _level+1, esvg::render::Point::type::interpolation);
interpolateCubicBezier(_listPoint, _recurtionMax, _threshold, pos1234, pos234, pos34, _pos4, _level+1, _type);
}
static float vectorAngle(vec2 _uuu, vec2 _vvv) {
_uuu.safeNormalize();
_vvv.safeNormalize();
return atan2(_uuu.cross(_vvv), _uuu.dot(_vvv));
}
esvg::render::PointList esvg::render::Path::generateListPoints(int32_t _level, int32_t _recurtionMax, float _threshold) {
ESVG_VERBOSE(spacingDist(_level) << "Generate List Points ... from a path");
esvg::render::PointList out;
etk::Vector<esvg::render::Point> tmpListPoint;
vec2 lastPosition(0.0f, 0.0f);
vec2 lastAngle(0.0f, 0.0f);
int32_t lastPointId = -1;
bool PathStart = false;
// Foreach element, we move in the path:
for(auto &it : m_listElement) {
if (it == null) {
continue;
}
ESVG_VERBOSE(spacingDist(_level+1) << " Draw : " << *it);
switch (it->getType()) {
case esvg::render::path_stop:
if (tmpListPoint.size() != 0) {
if (tmpListPoint.size() == 0) {
ESVG_WARNING(spacingDist(_level+1) << " Request path stop of not starting path ...");
} else {
tmpListPoint.back().setEndPath();
out.addList(tmpListPoint);
tmpListPoint.clear();
}
}
lastAngle = vec2(0.0f, 0.0f);
// nothing alse to do ...
break;
case esvg::render::path_close:
if (tmpListPoint.size() != 0) {
if (tmpListPoint.size() == 0) {
ESVG_WARNING(spacingDist(_level+1) << " Request path close of not starting path ...");
} else {
// find the previous tart of the path ...
tmpListPoint.front().m_type = esvg::render::Point::type::join;
// Remove the last point if it is the same position...
vec2 delta = (tmpListPoint.front().m_pos - tmpListPoint.back().m_pos).absolute();
if ( delta.x() <= 0.00001
&& delta.y() <= 0.00001) {
tmpListPoint.popBack();
ESVG_VERBOSE(" Remove point Z property : " << tmpListPoint.back().m_pos << " with delta=" << delta);
}
out.addList(tmpListPoint);
tmpListPoint.clear();
}
}
lastAngle = vec2(0.0f, 0.0f);
// nothing alse to do ...
break;
case esvg::render::path_moveTo:
// stop last path
if (tmpListPoint.size() != 0) {
tmpListPoint.back().setEndPath();
out.addList(tmpListPoint);
tmpListPoint.clear();
}
// create a new one
if (it->getRelative() == false) {
lastPosition = vec2(0.0f, 0.0f);
}
lastPosition += it->getPos();
tmpListPoint.pushBack(esvg::render::Point(lastPosition, esvg::render::Point::type::start));
lastAngle = lastPosition;
break;
case esvg::render::path_lineTo:
// If no previous point, we need to create the last point has start ...
if (tmpListPoint.size() == 0) {
tmpListPoint.pushBack(esvg::render::Point(lastPosition, esvg::render::Point::type::start));
}
if (it->getRelative() == false) {
lastPosition = vec2(0.0f, 0.0f);
}
lastPosition += it->getPos();
tmpListPoint.pushBack(esvg::render::Point(lastPosition, esvg::render::Point::type::join));
lastAngle = lastPosition;
break;
case esvg::render::path_lineToH:
// If no previous point, we need to create the last point has start ...
if (tmpListPoint.size() == 0) {
tmpListPoint.pushBack(esvg::render::Point(lastPosition, esvg::render::Point::type::start));
}
if (it->getRelative() == false) {
lastPosition = vec2(0.0f, 0.0f);
}
lastPosition += it->getPos();
tmpListPoint.pushBack(esvg::render::Point(lastPosition, esvg::render::Point::type::join));
lastAngle = lastPosition;
break;
case esvg::render::path_lineToV:
// If no previous point, we need to create the last point has start ...
if (tmpListPoint.size() == 0) {
tmpListPoint.pushBack(esvg::render::Point(lastPosition, esvg::render::Point::type::start));
}
if (it->getRelative() == false) {
lastPosition = vec2(0.0f, 0.0f);
}
lastPosition += it->getPos();
tmpListPoint.pushBack(esvg::render::Point(lastPosition, esvg::render::Point::type::join));
lastAngle = lastPosition;
break;
case esvg::render::path_curveTo:
// If no previous point, we need to create the last point has start ...
if (tmpListPoint.size() == 0) {
tmpListPoint.pushBack(esvg::render::Point(lastPosition, esvg::render::Point::type::join));
}
{
vec2 lastPosStore(lastPosition);
if (it->getRelative() == false) {
lastPosition = vec2(0.0f, 0.0f);
}
vec2 pos1 = lastPosition + it->getPos1();
vec2 pos2 = lastPosition + it->getPos2();
vec2 pos = lastPosition + it->getPos();
interpolateCubicBezier(tmpListPoint,
_recurtionMax,
_threshold,
lastPosStore,
pos1,
pos2,
pos,
0,
esvg::render::Point::type::join);
lastPosition = pos;
lastAngle = pos2;
}
break;
case esvg::render::path_smoothCurveTo:
// If no previous point, we need to create the last point has start ...
if (tmpListPoint.size() == 0) {
tmpListPoint.pushBack(esvg::render::Point(lastPosition, esvg::render::Point::type::join));
}
{
vec2 lastPosStore(lastPosition);
if (it->getRelative() == false) {
lastPosition = vec2(0.0f, 0.0f);
}
vec2 pos2 = lastPosition + it->getPos2();
vec2 pos = lastPosition + it->getPos();
// generate Pos 1
vec2 pos1 = lastPosStore*2.0f - lastAngle;
interpolateCubicBezier(tmpListPoint,
_recurtionMax,
_threshold,
lastPosStore,
pos1,
pos2,
pos,
0,
esvg::render::Point::type::join);
lastPosition = pos;
lastAngle = pos2;
}
break;
case esvg::render::path_bezierCurveTo:
// If no previous point, we need to create the last point has start ...
if (tmpListPoint.size() == 0) {
tmpListPoint.pushBack(esvg::render::Point(lastPosition, esvg::render::Point::type::join));
}
{
vec2 lastPosStore(lastPosition);
if (it->getRelative() == false) {
lastPosition = vec2(0.0f, 0.0f);
}
vec2 pos = lastPosition + it->getPos();
vec2 tmp1 = lastPosition + it->getPos1();
// generate pos1 and pos2
vec2 pos1 = lastPosStore + (tmp1 - lastPosStore)*0.666666666f;
vec2 pos2 = pos + (tmp1 - pos)*0.666666666f;
interpolateCubicBezier(tmpListPoint,
_recurtionMax,
_threshold,
lastPosStore,
pos1,
pos2,
pos,
0,
esvg::render::Point::type::join);
lastPosition = pos;
lastAngle = tmp1;
}
break;
case esvg::render::path_bezierSmoothCurveTo:
// If no previous point, we need to create the last point has start ...
if (tmpListPoint.size() == 0) {
tmpListPoint.pushBack(esvg::render::Point(lastPosition, esvg::render::Point::type::join));
}
{
vec2 lastPosStore(lastPosition);
if (it->getRelative() == false) {
lastPosition = vec2(0.0f, 0.0f);
}
vec2 pos = lastPosition + it->getPos();
vec2 tmp1 = lastPosStore*2.0f - lastAngle;
// generate pos1 and pos2
vec2 pos1 = lastPosStore + (tmp1 - lastPosStore)*0.666666666f;
vec2 pos2 = pos + (tmp1 - pos)*0.66666666f;
interpolateCubicBezier(tmpListPoint,
_recurtionMax,
_threshold,
lastPosStore,
pos1,
pos2,
pos,
0,
esvg::render::Point::type::join);
lastPosition = pos;
lastAngle = tmp1;
}
break;
case esvg::render::path_elliptic:
// If no previous point, we need to create the last point has start ...
if (tmpListPoint.size() == 0) {
tmpListPoint.pushBack(esvg::render::Point(lastPosition, esvg::render::Point::type::join));
}
{
ememory::SharedPtr<esvg::render::ElementElliptic> tmpIt(ememory::dynamicPointerCast<esvg::render::ElementElliptic>(it));
float angle = tmpIt->m_angle * (M_PI / 180.0);
ESVG_TODO(spacingDist(_level+1) << " Elliptic arc: radius=" << tmpIt->getPos1());
ESVG_TODO(spacingDist(_level+1) << " angle=" << tmpIt->m_angle);
ESVG_TODO(spacingDist(_level+1) << " m_largeArcFlag=" << tmpIt->m_largeArcFlag);
ESVG_TODO(spacingDist(_level+1) << " m_sweepFlag=" << tmpIt->m_sweepFlag);
vec2 lastPosStore(lastPosition);
if (it->getRelative() == false) {
lastPosition = vec2(0.0f, 0.0f);
}
vec2 pos = lastPosition + it->getPos();
float rotationX = tmpIt->m_angle * (M_PI / 180.0);
vec2 radius = tmpIt->getPos1();
#ifdef DEBUG
m_debugInformation.addSegment(lastPosStore, pos);
#endif
vec2 delta = lastPosStore - pos;
float ddd = delta.length();
if ( ddd < 1e-6f
|| radius.x() < 1e-6f
|| radius.y() < 1e-6f) {
ESVG_WARNING("Degenerate arc in Line");
if (tmpListPoint.size() == 0) {
tmpListPoint.pushBack(esvg::render::Point(lastPosition, esvg::render::Point::type::join));
}
tmpListPoint.pushBack(esvg::render::Point(pos, esvg::render::Point::type::join));
} else {
// Convert to center point parameterization.
// http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
// procedure describe here : http://www.w3.org/TR/SVG11/implnote.html#ArcConversionCenterToEndpoint
// Compute delta'
mat2x3 matrixRotationCenter = etk::mat2x3Rotate(-rotationX);
vec2 deltaPrim = matrixRotationCenter * (delta*0.5f);
ddd = (deltaPrim.x()*deltaPrim.x())/(radius.x()*radius.x())
+ (deltaPrim.y()*deltaPrim.y())/(radius.y()*radius.y());
if (ddd > 1.0f) {
#ifndef __STDCPP_LLVM__
ddd = etk::sqrt(ddd);
#else
ddd = sqrtf(ddd);
#endif
radius *= ddd;
}
// Compute center'
float sss = 0.0f;
float ssa = radius.x()*radius.x()*radius.y()*radius.y()
- radius.x()*radius.x()*deltaPrim.y()*deltaPrim.y()
- radius.y()*radius.y()*deltaPrim.x()*deltaPrim.x();
float ssb = radius.x()*radius.x()*deltaPrim.y()*deltaPrim.y()
+ radius.y()*radius.y()*deltaPrim.x()*deltaPrim.x();
if (ssa < 0.0f) {
ssa = 0.0f;
}
if (ssb > 0.0f) {
#ifndef __STDCPP_LLVM__
sss = etk::sqrt(ssa / ssb);
#else
sss = sqrtf(ssa / ssb);
#endif
}
if (tmpIt->m_largeArcFlag == tmpIt->m_sweepFlag) {
sss *= -1.0f;
}
vec2 centerPrime(sss * radius.x() * deltaPrim.y() / radius.y(),
sss * -radius.y() * deltaPrim.x() / radius.x());
// Compute center from center'
mat2x3 matrix = etk::mat2x3Rotate(rotationX);
vec2 center = (lastPosStore + pos)*0.5f + matrix*centerPrime;
#ifdef DEBUG
m_debugInformation.addSegment(center-vec2(3.0,3.0), center+vec2(3.0,3.0));
m_debugInformation.addSegment(center-vec2(3.0,-3.0), center+vec2(3.0,-3.0));
#endif
// Calculate theta1, and delta theta.
vec2 vectorA = (deltaPrim - centerPrime) / radius;
vec2 vectorB = (deltaPrim + centerPrime) / radius * -1.0f;
#ifdef DEBUG
m_debugInformation.addSegment(center, center+vectorA*radius.x());
m_debugInformation.addSegment(center, center+vectorB*radius.y());
#endif
// Initial angle
float theta1 = vectorAngle(vec2(1.0f,0.0f), vectorA);
// Delta angle
float deltaTheta = vectorAngle(vectorA, vectorB);
// special case of invert angle...
if ( ( deltaTheta == float(M_PI)
|| deltaTheta == -float(M_PI))
&& tmpIt->m_sweepFlag == false) {
deltaTheta *= -1.0f;
}
if (tmpIt->m_largeArcFlag == true) {
// Choose large arc
if (deltaTheta > 0.0f) {
deltaTheta -= 2.0f*M_PI;
} else {
deltaTheta += 2.0f*M_PI;
}
}
// Approximate the arc using cubic spline segments.
matrix.translate(center);
// Split arc into max 90 degree segments.
// The loop assumes an iteration per end point (including start and end), this +1.
#ifndef __STDCPP_LLVM__
int32_t ndivs = int32_t(etk::abs(deltaTheta) / (M_PI*0.5f)) + 1;
#else
int32_t ndivs = int32_t(fabs(deltaTheta) / (M_PI*0.5f)) + 1;
#endif
float hda = (deltaTheta / float(ndivs)) * 0.5f;
#ifndef __STDCPP_LLVM__
float kappa = etk::abs(4.0f / 3.0f * (1.0f - etk::cos(hda)) / etk::sin(hda));
#else
float kappa = fabs(4.0f / 3.0f * (1.0f - cosf(hda)) / sinf(hda));
#endif
if (deltaTheta < 0.0f) {
kappa = -kappa;
}
vec2 pointPosPrevious(0.0,0.0);
vec2 tangentPrevious(0.0,0.0);
for (int32_t iii=0; iii<=ndivs; ++iii) {
float a = theta1 + deltaTheta * (float(iii)/(float)ndivs);
#ifndef __STDCPP_LLVM__
delta = vec2(etk::cos(a), etk::sin(a));
#else
delta = vec2(cosf(a), sinf(a));
#endif
// position
vec2 pointPos = matrix * vec2(delta.x()*radius.x(), delta.y()*radius.y());
// tangent
vec2 tangent = matrix.applyScaleRotation(vec2(-delta.y()*radius.x() * kappa, delta.x()*radius.y() * kappa));
if (iii > 0) {
vec2 zlastPosStore(lastPosition);
if (it->getRelative() == false) {
lastPosition = vec2(0.0f, 0.0f);
}
vec2 zpos1 = pointPosPrevious + tangentPrevious;
vec2 zpos2 = pointPos - tangent;
vec2 zpos = pointPos;
interpolateCubicBezier(tmpListPoint,
_recurtionMax,
_threshold,
zlastPosStore,
zpos1,
zpos2,
zpos,
0,
esvg::render::Point::type::join);
lastPosition = zpos;
lastAngle = zpos2;
}
pointPosPrevious = pointPos;
tangentPrevious = tangent;
}
}
lastPosition = pos;
}
break;
default:
ESVG_ERROR(spacingDist(_level+1) << " Unknow PATH commant (internal error)");
break;
}
}
// special case : No request end of path ==> open path:
if (tmpListPoint.size() != 0) {
ESVG_VERBOSE("Auto-end PATH");
tmpListPoint.back().setEndPath();
out.addList(tmpListPoint);
tmpListPoint.clear();
}
out.display();
return out;
}

55
esvg/render/Path.hpp Normal file
View File

@ -0,0 +1,55 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
#include <esvg/render/Element.hpp>
#include <esvg/render/PointList.hpp>
#include <ememory/memory.hpp>
#ifdef DEBUG
#include <esvg/render/SegmentList.hpp>
#endif
namespace esvg {
namespace render {
class Path {
public:
etk::Vector<ememory::SharedPtr<esvg::render::Element>> m_listElement;
#ifdef DEBUG
esvg::render::SegmentList m_debugInformation;
#endif
public:
Path() {
}
~Path() {
}
void clear();
void stop();
void close(bool _relative=false);
void moveTo(bool _relative, const vec2& _pos);
void lineTo(bool _relative, const vec2& _pos);
void lineToH(bool _relative, float _posX);
void lineToV(bool _relative, float _posY);
void curveTo(bool _relative, const vec2& _pos1, const vec2& _pos2, const vec2& _pos);
void smoothCurveTo(bool _relative, const vec2& _pos2, const vec2& _pos);
void bezierCurveTo(bool _relative, const vec2& _pos1, const vec2& _pos);
void bezierSmoothCurveTo(bool _relative, const vec2& _pos);
void ellipticTo(bool _relative,
const vec2& _radius,
float _angle,
bool _largeArcFlag,
bool _sweepFlag,
const vec2& _pos);
void display(int32_t _spacing);
esvg::render::PointList generateListPoints(int32_t _level, int32_t _recurtionMax = 10, float _threshold = 0.25f);
};
}
}

31
esvg/render/Point.cpp Normal file
View File

@ -0,0 +1,31 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/render/Point.hpp>
#include <esvg/debug.hpp>
void esvg::render::Point::setEndPath() {
if (m_type == esvg::render::Point::type::interpolation) {
ESVG_WARNING("Request stop path of an interpolate Point");
m_type = esvg::render::Point::type::stop;
return;
}
if (m_type == esvg::render::Point::type::stop) {
ESVG_WARNING("Request stop path of an STOP Point");
return;
}
if (m_type == esvg::render::Point::type::start) {
m_type = esvg::render::Point::type::single;
return;
}
m_type = esvg::render::Point::type::stop;
}
void esvg::render::Point::normalize(const vec2& _nextPoint) {
m_delta = _nextPoint - m_pos;
m_len = m_delta.length();
}

50
esvg/render/Point.hpp Normal file
View File

@ -0,0 +1,50 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
#include <esvg/render/Element.hpp>
namespace esvg {
namespace render {
class Point {
public:
enum class type {
single, //!< Point type is single, this mean that it start and stop of a path
start, //!< Point type is starting of a path
stop, //!< Point type is stoping of a path
join, //!< Point type in an user point provided inside a path
interpolation, //!< This point is dynamicly calculated to create an interpolation
};
public:
// TODO : Clean all element here ...
vec2 m_pos; //!< position of the point
enum esvg::render::Point::type m_type;
vec2 m_miterAxe;
vec2 m_orthoAxePrevious;
vec2 m_orthoAxeNext;
vec2 m_posPrevious;
vec2 m_posNext;
vec2 m_delta;
float m_len;
// TODO: Update etk::Vector to support not having it ...
Point() :
m_pos(0,0),
m_type(esvg::render::Point::type::join) {
// nothing to do ...
}
Point(const vec2& _pos, enum esvg::render::Point::type _type = esvg::render::Point::type::join) :
m_pos(_pos),
m_type(_type) {
// nothing to do ...
}
void setEndPath();
void normalize(const vec2& _nextPoint);
};
}
}

64
esvg/render/PointList.cpp Normal file
View File

@ -0,0 +1,64 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/debug.hpp>
#include <esvg/render/PointList.hpp>
esvg::render::PointList::PointList() {
// nothing to do ...
}
void esvg::render::PointList::addList(etk::Vector<esvg::render::Point>& _list) {
m_data.pushBack(_list);
// TODO : Add a checker of correct list ...
}
void esvg::render::PointList::applyMatrix(const mat2x3& _transformationMatrix) {
for (auto &it : m_data) {
for (auto &val : it) {
val.m_pos = _transformationMatrix * val.m_pos;
}
}
}
etk::Pair<vec2, vec2> esvg::render::PointList::getViewPort() {
etk::Pair<vec2, vec2> out(vec2(9999999999.0,9999999999.0),vec2(-9999999999.0,-9999999999.0));
for (auto &it : m_data) {
for (auto &it2 : it) {
out.first.setMin(it2.m_pos);
out.second.setMax(it2.m_pos);
}
}
return out;
}
void esvg::render::PointList::display() {
ESVG_VERBOSE(" Display list of points : size=" << m_data.size());
for (auto &it : m_data) {
ESVG_VERBOSE(" Find List " << it.size() << " members");
for (size_t iii=0;
iii < it.size();
++iii) {
switch (it[iii].m_type) {
case esvg::render::Point::type::single:
ESVG_VERBOSE(" [" << iii << "] Find Single " << it[iii].m_pos);
break;
case esvg::render::Point::type::start:
ESVG_VERBOSE(" [" << iii << "] Find Start " << it[iii].m_pos);
break;
case esvg::render::Point::type::stop:
ESVG_VERBOSE(" [" << iii << "] Find Stop " << it[iii].m_pos);
break;
case esvg::render::Point::type::interpolation:
ESVG_VERBOSE(" [" << iii << "] Find interpolation " << it[iii].m_pos);
break;
case esvg::render::Point::type::join:
ESVG_VERBOSE(" [" << iii << "] Find Join " << it[iii].m_pos);
break;
}
}
}
}

28
esvg/render/PointList.hpp Normal file
View File

@ -0,0 +1,28 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
#include <etk/math/Matrix2x3.hpp>
#include <etk/Pair.hpp>
#include <esvg/render/Element.hpp>
#include <esvg/render/Point.hpp>
namespace esvg {
namespace render {
class PointList {
public:
etk::Vector<etk::Vector<esvg::render::Point>> m_data;
public:
PointList();
void addList(etk::Vector<esvg::render::Point>& _list);
void display();
void applyMatrix(const mat2x3& _transformationMatrix);
etk::Pair<vec2, vec2> getViewPort();
};
}
}

38
esvg/render/Scanline.cpp Normal file
View File

@ -0,0 +1,38 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/render/Scanline.hpp>
#include <esvg/debug.hpp>
esvg::render::Scanline::Scanline(size_t _size) {
m_data.resize(_size, 0.0f);
}
size_t esvg::render::Scanline::size() const {
return m_data.size();
}
void esvg::render::Scanline::clear(float _fill) {
for (auto &it : m_data) {
it = _fill;
}
}
float esvg::render::Scanline::get(int32_t _pos) const {
if( _pos >= 0
&& size_t(_pos) < m_data.size()) {
return m_data[_pos];
}
return 0;
}
void esvg::render::Scanline::set(int32_t _pos, float _newColor) {
if( _pos >= 0
&& size_t(_pos) < m_data.size()) {
m_data[_pos] = _newColor;
}
}

29
esvg/render/Scanline.hpp Normal file
View File

@ -0,0 +1,29 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
namespace esvg {
namespace render {
class Scanline {
private:
etk::Vector<float> m_data;
public:
// constructor :
Scanline(size_t _size=32);
// destructor
~Scanline() { };
public:
size_t size() const;
void clear(float _fill);
float get(int32_t _pos) const;
void set(int32_t _pos, float _newColor);
};
}
}

39
esvg/render/Segment.cpp Normal file
View File

@ -0,0 +1,39 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/render/Segment.hpp>
#include <esvg/debug.hpp>
esvg::render::Segment::Segment() {
p0 = vec2(0,0);
p1 = vec2(0,0);
direction = 0;
}
esvg::render::Segment::Segment(const vec2& _p0, const vec2& _p1) {
// segment register all time the lower at P0n then we need to register the sens of the path
p0 = _p0;
p1 = _p1;
direction = 0;
}
void esvg::render::Segment::applyMatrix(const mat2x3& _transformationMatrix) {
p0 = _transformationMatrix * p0;
p1 = _transformationMatrix * p1;
createDirection();
}
void esvg::render::Segment::createDirection() {
if (p0.y() < p1.y()) {
direction = 1; // direction like clock
} else {
vec2 tmp(p0);
p0 = p1;
p1 = tmp;
direction = -1; // direction like anti-clock
}
}

27
esvg/render/Segment.hpp Normal file
View File

@ -0,0 +1,27 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
#include <etk/math/Matrix2x3.hpp>
namespace esvg {
namespace render {
class Segment {
public:
// TODO: Update etk::Vector to support not having it ...
Segment();
Segment(const vec2& _p0, const vec2& _p1);
vec2 p0;
vec2 p1;
int32_t direction;
void applyMatrix(const mat2x3& _transformationMatrix);
void createDirection();
};
}
}

508
esvg/render/SegmentList.cpp Normal file
View File

@ -0,0 +1,508 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/render/SegmentList.hpp>
#include <esvg/debug.hpp>
#include <etk/math/Matrix2x3.hpp>
esvg::render::SegmentList::SegmentList() {
}
#ifdef DEBUG
void esvg::render::SegmentList::addSegment(const vec2& _pos0, const vec2& _pos1) {
m_data.pushBack(Segment(_pos0, _pos1));
}
#endif
void esvg::render::SegmentList::addSegment(const esvg::render::Point& _pos0, const esvg::render::Point& _pos1) {
// Skip horizontal Segments
if (_pos0.m_pos.y() == _pos1.m_pos.y()) {
// remove /0 operation
return;
}
m_data.pushBack(Segment(_pos0.m_pos, _pos1.m_pos));
}
void esvg::render::SegmentList::addSegment(const esvg::render::Point& _pos0, const esvg::render::Point& _pos1, bool _disableHorizontal) {
// Skip horizontal Segments
if ( _disableHorizontal == true
&& _pos0.m_pos.y() == _pos1.m_pos.y()) {
// remove /0 operation
return;
}
m_data.pushBack(Segment(_pos0.m_pos, _pos1.m_pos));
}
etk::Pair<vec2, vec2> esvg::render::SegmentList::getViewPort() {
etk::Pair<vec2, vec2> out(vec2(9999999999.0,9999999999.0),vec2(-9999999999.0,-9999999999.0));
for (auto &it : m_data) {
out.first.setMin(it.p0);
out.second.setMax(it.p0);
out.first.setMin(it.p1);
out.second.setMax(it.p1);
}
return out;
}
void esvg::render::SegmentList::createSegmentList(const esvg::render::PointList& _listPoint) {
for (auto &it : _listPoint.m_data) {
// Build Segments
for (size_t iii=0, jjj=it.size()-1;
iii < it.size();
jjj = iii++) {
addSegment(it[jjj], it[iii]);
}
}
}
static vec2 getIntersect(const vec2& _point1,
const vec2& _vect1,
const vec2& _point2,
const vec2& _vect2) {
float diviseur = _vect1.x() * _vect2.y() - _vect1.y() * _vect2.x();
if(diviseur != 0.0f) {
float mmm = ( _vect1.x() * _point1.y()
- _vect1.x() * _point2.y()
- _vect1.y() * _point1.x()
+ _vect1.y() * _point2.x()
) / diviseur;
return vec2(_point2 + _vect2 * mmm);
}
ESVG_ERROR("Get divider / 0.0f");
return _point2;
}
void esvg::render::SegmentList::createSegmentListStroke(const vec2& _point1,
const vec2& _point2,
const vec2& _center,
float _width,
bool _isStart) {
int32_t nbDot = int32_t(_width);
if (nbDot <= 2) {
nbDot = 2;
}
float angleToDraw = acos((_point1 - _center).safeNormalize().dot((_point2 - _center).safeNormalize()));
float baseAngle = angleToDraw/float(nbDot);
float iii;
vec2 axe = (_point1 - _center).safeNormalize();
vec2 ppp1(_point1);
vec2 ppp2(_point2);
for (iii=baseAngle; iii<angleToDraw; iii+=baseAngle) {
mat2x3 tmpMat;
if (_isStart == true) {
tmpMat = etk::mat2x3Rotate(-iii);
} else {
tmpMat = etk::mat2x3Rotate(iii);
}
vec2 axeRotate = tmpMat * axe;
ppp2 = _center
+ axeRotate*_width*0.5f;
if (_isStart == true) {
addSegment(ppp2, ppp1);
ESVG_VERBOSE(" segment :" << ppp2 << " -> " << ppp1);
} else {
addSegment(ppp1, ppp2);
ESVG_VERBOSE(" segment :" << ppp1 << " -> " << ppp2);
}
ppp1 = ppp2;
}
if (_isStart == true) {
addSegment(_point2, ppp1);
ESVG_VERBOSE(" segment :" << _point2 << " -> " << ppp1);
} else {
addSegment(ppp1, _point2);
ESVG_VERBOSE(" segment :" << ppp1 << " -> " << _point2);
}
}
void esvg::render::SegmentList::createSegmentListStroke(esvg::render::PointList& _listPoint,
float _width,
enum esvg::cap _cap,
enum esvg::join _join,
float _miterLimit) {
for (auto &itListPoint : _listPoint.m_data) {
// generate for every point all the orthogonal elements
//
// normal edge * end path
// (mitter) * | * * * * * * * * * * * * * *
// * |<--*----this | *
// * | * this -->| *
// * * * | *
// * . | . * . . . . . . . . * *
// * . | . * | *
// * A . | . B * | *
// . * . | *
// . * * . * * * * * * * * * * * * *
// * *
// * *
for (int64_t idPevious=itListPoint.size()-1, idCurrent=0, idNext=1;
idCurrent < int64_t(itListPoint.size());
idPevious = idCurrent++, idNext++) {
if (idNext == int64_t(itListPoint.size())) {
idNext = 0;
}
if ( itListPoint[idCurrent].m_type == esvg::render::Point::type::join
|| itListPoint[idCurrent].m_type == esvg::render::Point::type::interpolation) {
if (idPevious < 0 ) {
ESVG_ERROR("an error occure a previous ID is < 0.... ");
continue;
}
if (idNext >= int64_t(itListPoint.size())) {
ESVG_ERROR("an error occure a next ID is >= nbPoint len .... ");
continue;
}
//ESVG_DEBUG("JOIN : id : prev/curr/next : " << idPevious << "/" << idCurrent << "/" << idNext);
//ESVG_DEBUG("JOIN : val : prev/curr/next : " << itListPoint[idPevious].m_pos << "/" << itListPoint[idCurrent].m_pos << "/" << itListPoint[idNext].m_pos);
vec2 vecA = itListPoint[idCurrent].m_pos - itListPoint[idPevious].m_pos;
//ESVG_DEBUG("JOIN : vecA : " << vecA);
vecA.safeNormalize();
vec2 vecB = itListPoint[idNext].m_pos - itListPoint[idCurrent].m_pos;
//ESVG_DEBUG("JOIN : vecB : " << vecB);
vecB.safeNormalize();
vec2 vecC = vecA - vecB;
//ESVG_DEBUG("JOIN : vecC : " << vecC);
if (vecC == vec2(0.0f, 0.0f)) {
// special case: 1 line ...
itListPoint[idCurrent].m_miterAxe = vec2(vecA.y(), vecA.x());
} else {
vecC.safeNormalize();
itListPoint[idCurrent].m_miterAxe = vecC;
}
itListPoint[idCurrent].m_posPrevious = itListPoint[idPevious].m_pos;
itListPoint[idCurrent].m_posNext = itListPoint[idNext].m_pos;
vecB = itListPoint[idNext].m_pos - itListPoint[idCurrent].m_pos;
vecB.safeNormalize();
itListPoint[idCurrent].m_orthoAxeNext = vec2(vecB.y(), -vecB.x());
vecB = itListPoint[idCurrent].m_pos - itListPoint[idPevious].m_pos;
vecB.safeNormalize();
itListPoint[idCurrent].m_orthoAxePrevious = vec2(vecB.y(), -vecB.x());
//ESVG_DEBUG("JOIN : miterAxe " << itListPoint[idCurrent].m_miterAxe);
} else if (itListPoint[idCurrent].m_type == esvg::render::Point::type::start) {
itListPoint[idCurrent].m_posNext = itListPoint[idNext].m_pos;
vec2 vecB = itListPoint[idNext].m_pos - itListPoint[idCurrent].m_pos;
vecB.safeNormalize();
itListPoint[idCurrent].m_miterAxe = vec2(vecB.y(), -vecB.x());
itListPoint[idCurrent].m_orthoAxePrevious = itListPoint[idCurrent].m_miterAxe;
itListPoint[idCurrent].m_orthoAxeNext = itListPoint[idCurrent].m_miterAxe;
} else if (itListPoint[idCurrent].m_type == esvg::render::Point::type::stop) {
if (idPevious < 0 ) {
ESVG_ERROR("an error occure a previous ID is < 0.... ");
continue;
}
itListPoint[idCurrent].m_posPrevious = itListPoint[idPevious].m_pos;
vec2 vecA = itListPoint[idCurrent].m_pos - itListPoint[idPevious].m_pos;
vecA.safeNormalize();
itListPoint[idCurrent].m_miterAxe = vec2(vecA.y(), -vecA.x());
itListPoint[idCurrent].m_orthoAxePrevious = itListPoint[idCurrent].m_miterAxe;
itListPoint[idCurrent].m_orthoAxeNext = itListPoint[idCurrent].m_miterAxe;
} else {
ESVG_TODO("Unsupported type of point ....");
}
}
// create segment list:
bool haveStartLine = false;
vec2 leftPoint(0,0);
vec2 rightPoint(0,0);
if (itListPoint.size() > 0) {
if (itListPoint.front().m_type == esvg::render::Point::type::join) {
const esvg::render::Point& it = itListPoint.back();
// Calculate the perpendiculary axis ...
leftPoint = itListPoint.back().m_pos
+ itListPoint.back().m_orthoAxePrevious*_width*0.5f;
rightPoint = itListPoint.back().m_pos
- itListPoint.back().m_orthoAxePrevious*_width*0.5f;
// cyclic path...
if (it.m_type == esvg::render::Point::type::interpolation) {
leftPoint = getIntersect(leftPoint, it.m_pos-it.m_posPrevious, it.m_pos, it.m_miterAxe);
rightPoint = getIntersect(rightPoint, it.m_pos-it.m_posPrevious, it.m_pos, it.m_miterAxe);
} else if (it.m_type == esvg::render::Point::type::join) {
// Calculate the perpendiculary axis ...
leftPoint = it.m_pos
+ it.m_orthoAxePrevious*_width*0.5f;
rightPoint = it.m_pos
- it.m_orthoAxePrevious*_width*0.5f;
// project on the miter Axis ...
switch (_join) {
case esvg::join_miter:
{
vec2 left = getIntersect(leftPoint, it.m_pos-it.m_posPrevious, it.m_pos, it.m_miterAxe);
vec2 right = getIntersect(rightPoint, it.m_pos-it.m_posPrevious, it.m_pos, it.m_miterAxe);
// Check the miter limit:
float limitRight = (left - it.m_pos).length() / _width * 2.0f;
float limitLeft = (right - it.m_pos).length() / _width * 2.0f;
ESVG_VERBOSE(" miter Limit: " << limitRight << " " << limitLeft << " <= " << _miterLimit);
if ( limitRight <= _miterLimit
&& limitLeft <= _miterLimit) {
leftPoint = left;
rightPoint = right;
break;
} else {
// BEVEL the miter point ...
}
}
case esvg::join_round:
case esvg::join_bevel:
{
vec2 axePrevious = (it.m_pos-it.m_posPrevious).safeNormalize();
vec2 axeNext = (it.m_posNext - it.m_pos).safeNormalize();
float cross = axePrevious.cross(axeNext);
if (cross > 0.0f) {
rightPoint = getIntersect(rightPoint, it.m_pos-it.m_posPrevious, it.m_pos, it.m_miterAxe);
leftPoint = it.m_pos
+ it.m_orthoAxeNext*_width*0.5f;
} else {
leftPoint = getIntersect(leftPoint, it.m_pos-it.m_posPrevious, it.m_pos, it.m_miterAxe);
rightPoint = it.m_pos
- it.m_orthoAxeNext*_width*0.5f;
}
break;
}
}
} else {
ESVG_ERROR("Start list point with a join, but last lement is not a join");
}
}
}
for (auto &it : itListPoint) {
switch (it.m_type) {
case esvg::render::Point::type::single:
// just do nothing ....
ESVG_VERBOSE("Find Single " << it.m_pos);
break;
case esvg::render::Point::type::start:
ESVG_VERBOSE("Find Start " << it.m_pos);
if (haveStartLine == true) {
// close previous :
ESVG_WARNING(" find a non close path ...");
addSegment(leftPoint, rightPoint);
}
haveStartLine = true;
startStopPoint(leftPoint, rightPoint, it, _cap, _width, true);
break;
case esvg::render::Point::type::stop:
ESVG_VERBOSE("Find Stop " << it.m_pos);
if (haveStartLine == false) {
ESVG_WARNING("find close path without start part ...");
break;
}
haveStartLine = false;
startStopPoint(leftPoint, rightPoint, it, _cap, _width, false);
break;
case esvg::render::Point::type::interpolation:
{
ESVG_VERBOSE("Find interpolation " << it.m_pos);
vec2 left = getIntersect(leftPoint, it.m_pos-it.m_posPrevious, it.m_pos, it.m_miterAxe);
vec2 right = getIntersect(rightPoint, it.m_pos-it.m_posPrevious, it.m_pos, it.m_miterAxe);
//Draw from previous point:
addSegment(leftPoint, left);
ESVG_VERBOSE(" segment :" << leftPoint << " -> " << left);
addSegment(right, rightPoint);
ESVG_VERBOSE(" segment :" << right << " -> " << rightPoint);
leftPoint = left;
rightPoint = right;
}
break;
case esvg::render::Point::type::join:
ESVG_VERBOSE("Find join " << it.m_pos);
switch (_join) {
case esvg::join_miter:
{
vec2 left = getIntersect(leftPoint, it.m_pos-it.m_posPrevious, it.m_pos, it.m_miterAxe);
vec2 right = getIntersect(rightPoint, it.m_pos-it.m_posPrevious, it.m_pos, it.m_miterAxe);
// Check the miter limit:
float limitRight = (left - it.m_pos).length() / _width * 2.0f;
float limitLeft = (right - it.m_pos).length() / _width * 2.0f;
ESVG_VERBOSE(" miter Limit: " << limitRight << " " << limitLeft << " <= " << _miterLimit);
if ( limitRight <= _miterLimit
&& limitLeft <= _miterLimit) {
//Draw from previous point:
addSegment(leftPoint, left);
ESVG_VERBOSE(" segment :" << leftPoint << " -> " << left);
addSegment(right, rightPoint);
ESVG_VERBOSE(" segment :" << right << " -> " << rightPoint);
leftPoint = left;
rightPoint = right;
break;
} else {
// We do a bevel join ...
ESVG_VERBOSE(" Find miter Limit ... ==> create BEVEL");
}
}
case esvg::join_round:
case esvg::join_bevel:
{
vec2 axePrevious = (it.m_pos-it.m_posPrevious).safeNormalize();
vec2 axeNext = (it.m_posNext - it.m_pos).safeNormalize();
float cross = axePrevious.cross(axeNext);
if (cross > 0.0f) {
vec2 right = getIntersect(rightPoint, it.m_pos-it.m_posPrevious, it.m_pos, it.m_miterAxe);
vec2 left1 = it.m_pos
+ it.m_orthoAxePrevious*_width*0.5f;
vec2 left2 = it.m_pos
+ it.m_orthoAxeNext*_width*0.5f;
//Draw from previous point:
addSegment(leftPoint, left1);
ESVG_VERBOSE(" segment :" << leftPoint << " -> " << left1);
if (_join != esvg::join_round) {
// Miter and bevel:
addSegment(left1, left2);
ESVG_VERBOSE(" segment :" << left1 << " -> " << left2);
}else {
createSegmentListStroke(left1,
left2,
it.m_pos,
_width,
false);
}
addSegment(right, rightPoint);
ESVG_VERBOSE(" segment :" << right << " -> " << rightPoint);
leftPoint = left2;
rightPoint = right;
} else {
vec2 left = getIntersect(leftPoint, it.m_pos-it.m_posPrevious, it.m_pos, it.m_miterAxe);
vec2 right1 = it.m_pos
- it.m_orthoAxePrevious*_width*0.5f;
vec2 right2 = it.m_pos
- it.m_orthoAxeNext*_width*0.5f;//Draw from previous point:
addSegment(leftPoint, left);
ESVG_VERBOSE(" segment :" << leftPoint << " -> " << left);
addSegment(right1, rightPoint);
ESVG_VERBOSE(" segment :" << right1 << " -> " << rightPoint);
if (_join != esvg::join_round) {
// Miter and bevel:
addSegment(right2, right1);
ESVG_VERBOSE(" segment :" << right2 << " -> " << right1);
} else {
createSegmentListStroke(right1,
right2,
it.m_pos,
_width,
true);
}
leftPoint = left;
rightPoint = right2;
}
}
break;
}
break;
}
}
}
}
void esvg::render::SegmentList::startStopPoint(vec2& _leftPoint,
vec2& _rightPoint,
const esvg::render::Point& _point,
enum esvg::cap _cap,
float _width,
bool _isStart) {
switch (_cap) {
case esvg::cap_butt:
{
vec2 left = _point.m_pos
+ _point.m_miterAxe*_width*0.5f;
vec2 right = _point.m_pos
- _point.m_miterAxe*_width*0.5f;
if (_isStart == false) {
//Draw from previous point:
addSegment(_leftPoint, left);
ESVG_VERBOSE(" segment :" << _leftPoint << " -> " << left);
addSegment(right, _rightPoint);
ESVG_VERBOSE(" segment :" << right << " -> " << _rightPoint);
}
_leftPoint = left;
_rightPoint = right;
}
if (_isStart == false) {
addSegment(_leftPoint, _rightPoint);
ESVG_VERBOSE(" segment :" << _leftPoint << " -> " << _rightPoint);
} else {
addSegment(_rightPoint, _leftPoint);
ESVG_VERBOSE(" segment :" << _rightPoint << " -> " << _leftPoint);
}
break;
case esvg::cap_round:
{
if (_isStart == false) {
vec2 left = _point.m_pos
+ _point.m_miterAxe*_width*0.5f;
vec2 right = _point.m_pos
- _point.m_miterAxe*_width*0.5f;
if (_isStart == false) {
//Draw from previous point:
addSegment(_leftPoint, left);
ESVG_VERBOSE(" segment :" << _leftPoint << " -> " << left);
addSegment(right, _rightPoint);
ESVG_VERBOSE(" segment :" << right << " -> " << _rightPoint);
}
_leftPoint = left;
_rightPoint = right;
}
int32_t nbDot = int32_t(_width);
if (nbDot <= 2) {
nbDot = 2;
}
float baseAngle = M_PI/float(nbDot);
float iii;
_leftPoint = _point.m_pos
+ _point.m_miterAxe*_width*0.5f;
_rightPoint = _point.m_pos
- _point.m_miterAxe*_width*0.5f;
createSegmentListStroke(_leftPoint,
_rightPoint,
_point.m_pos,
_width,
_isStart);
}
break;
case esvg::cap_square:
{
vec2 nextAxe;
if (_isStart == true) {
nextAxe = _point.m_posNext - _point.m_pos;
} else {
nextAxe = _point.m_posPrevious - _point.m_pos;
}
vec2 left = _point.m_pos
+ _point.m_miterAxe*_width*0.5f;
vec2 right = _point.m_pos
- _point.m_miterAxe*_width*0.5f;
mat2x3 tmpMat = etk::mat2x3Translate(nextAxe.safeNormalize()*_width*-0.5f);
left = tmpMat*left;
right = tmpMat*right;
if (_isStart == false) {
if (_isStart == false) {
//Draw from previous point:
addSegment(_leftPoint, left);
ESVG_VERBOSE(" segment :" << _leftPoint << " -> " << left);
addSegment(right, _rightPoint);
ESVG_VERBOSE(" segment :" << right << " -> " << _rightPoint);
}
}
_leftPoint = left;
_rightPoint = right;
if (_isStart == false) {
addSegment(_leftPoint, _rightPoint);
ESVG_VERBOSE(" segment :" << _leftPoint << " -> " << _rightPoint);
} else {
addSegment(_rightPoint, _leftPoint);
ESVG_VERBOSE(" segment :" << _rightPoint << " -> " << _leftPoint);
}
ESVG_VERBOSE(" segment :" << _leftPoint << " -> " << _rightPoint);
}
break;
default:
ESVG_ERROR(" Undefined CAP TYPE");
break;
}
}
void esvg::render::SegmentList::applyMatrix(const mat2x3& _transformationMatrix) {
for (auto &it : m_data) {
it.applyMatrix(_transformationMatrix);
}
}

View File

@ -0,0 +1,50 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
#include <esvg/cap.hpp>
#include <esvg/join.hpp>
#include <esvg/render/Segment.hpp>
#include <esvg/render/PointList.hpp>
namespace esvg {
namespace render {
class SegmentList {
public:
etk::Vector<esvg::render::Segment> m_data;
public:
SegmentList();
#ifdef DEBUG
void addSegment(const vec2& _pos0, const vec2& _pos1);
#endif
void addSegment(const esvg::render::Point& _pos0, const esvg::render::Point& _pos1);
void addSegment(const esvg::render::Point& _pos0, const esvg::render::Point& _pos1, bool _disableHorizontal);
void createSegmentList(const esvg::render::PointList& _listPoint);
void createSegmentListStroke(esvg::render::PointList& _listPoint,
float _width,
enum esvg::cap _cap,
enum esvg::join _join,
float _miterLimit);
private:
void startStopPoint(vec2& _leftPoint,
vec2& _rightPoint,
const esvg::render::Point& _point,
enum esvg::cap _cap,
float _width,
bool _isStart);
void createSegmentListStroke(const vec2& _point1,
const vec2& _point2,
const vec2& _center,
float _width,
bool _isStart);
public:
etk::Pair<vec2, vec2> getViewPort();
void applyMatrix(const mat2x3& _transformationMatrix);
};
}
}

203
esvg/render/Weight.cpp Normal file
View File

@ -0,0 +1,203 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/render/Weight.hpp>
#include <esvg/debug.hpp>
#include <etk/algorithm.hpp>
esvg::render::Weight::Weight() :
m_size(0,0) {
}
esvg::render::Weight::Weight(const ivec2& _size) :
m_size(_size) {
resize(_size);
}
esvg::render::Weight::~Weight() {
}
void esvg::render::Weight::resize(const ivec2& _size) {
m_size = _size;
float tmp(0);
m_data.resize(m_size.x()*m_size.y(), tmp);
if ((uint32_t)m_size.x()*m_size.y() > m_data.size()) {
ESVG_WARNING("Wrong weigth buffer size ...");
return;
}
}
const ivec2& esvg::render::Weight::getSize() const {
return m_size;
}
int32_t esvg::render::Weight::getWidth() const {
return m_size.x();
}
int32_t esvg::render::Weight::getHeight() const {
return m_size.y();
}
void esvg::render::Weight::clear(float _fill) {
for (int32_t iii=0; iii<m_size.x()*m_size.y(); iii++) {
m_data[iii] = _fill;
}
}
float esvg::render::Weight::get(const ivec2& _pos) const {
if ( _pos.x()>=0 && _pos.x()<m_size.x()
&& _pos.y()>=0 && _pos.y()<m_size.y()) {
return m_data[_pos.x()+_pos.y()*m_size.x()];
}
return 0;
}
void esvg::render::Weight::set(const ivec2& _pos, float _newColor) {
if ( _pos.x()>=0 && _pos.x()<m_size.x()
&& _pos.y()>=0 && _pos.y()<m_size.y()) {
m_data[_pos.x()+_pos.y()*m_size.x()] = _newColor;
}
}
void esvg::render::Weight::set(int32_t _posY, const esvg::render::Scanline& _data) {
if ( _posY>=0
&& _posY<m_size.y()) {
for (int32_t xxx=0; xxx<m_size.x(); ++xxx) {
m_data[xxx+_posY*m_size.x()] = _data.get(xxx);
}
}
}
void esvg::render::Weight::append(int32_t _posY, const esvg::render::Scanline& _data) {
if ( _posY>=0
&& _posY<m_size.y()) {
for (int32_t xxx=0; xxx<m_size.x(); ++xxx) {
m_data[xxx+_posY*m_size.x()] += _data.get(xxx);
}
}
}
bool sortXPosFunction(const etk::Pair<float,int32_t>& _e1, const etk::Pair<float,int32_t>& _e2) {
return _e1.first < _e2.first;
}
void esvg::render::Weight::generate(ivec2 _size, int32_t _subSamplingCount, const esvg::render::SegmentList& _listSegment) {
resize(_size);
// for each lines:
for (int32_t yyy=0; yyy<_size.y(); ++yyy) {
ESVG_VERBOSE("Weighting ... " << yyy << " / " << _size.y());
// Reduce the number of lines in the subsampling parsing:
etk::Vector<Segment> availlableSegmentPixel;
for (auto &it : _listSegment.m_data) {
if ( it.p0.y() < float(yyy+1)
&& it.p1.y() > float(yyy)) {
availlableSegmentPixel.pushBack(it);
}
}
if (availlableSegmentPixel.size() == 0) {
continue;
}
ESVG_VERBOSE(" Find Basic segments " << availlableSegmentPixel.size());
// This represent the pondaration on the subSampling
float deltaSize = 1.0f/_subSamplingCount;
for (int32_t kkk=0; kkk<_subSamplingCount ; ++kkk) {
ESVG_VERBOSE(" Scanline ... " << kkk << " / " << _subSamplingCount);
Scanline scanline(_size.x());
//find all the segment that cross the middle of the line of the center of the pixel line:
float subSamplingCenterPos = yyy + deltaSize*0.5f + deltaSize*kkk;
etk::Vector<Segment> availlableSegment;
// find in the subList ...
for (auto &it : availlableSegmentPixel) {
if ( it.p0.y() <= subSamplingCenterPos
&& it.p1.y() > subSamplingCenterPos) {
// check if we not get 2 identical lines:
if ( availlableSegment.size() > 0
&& availlableSegment.back().p1 == it.p0
&& availlableSegment.back().direction == it.direction) {
// we not add this point in this case to prevent double count of the same point.
} else {
availlableSegment.pushBack(it);
}
}
}
ESVG_VERBOSE(" Availlable Segment " << availlableSegment.size());
if (availlableSegment.size() == 0) {
continue;
}
for (auto &it : availlableSegment) {
ESVG_VERBOSE(" Availlable Segment " << it.p0 << " -> " << it.p1 << " dir=" << it.direction);
}
// x position, angle
etk::Vector<etk::Pair<float, int32_t>> listPosition;
for (auto &it : availlableSegment) {
vec2 delta = it.p0 - it.p1;
// x = coefficent*y+bbb;
float coefficient = delta.x()/delta.y();
float bbb = it.p0.x() - coefficient*it.p0.y();
float xpos = coefficient * subSamplingCenterPos + bbb;
listPosition.pushBack(etk::Pair<float,int32_t>(xpos, it.direction));
}
ESVG_VERBOSE(" List position " << listPosition.size());
// now we order position of the xPosition:
etk::algorithm::quickSort(listPosition, sortXPosFunction);
// move through all element in the point:
int32_t lastState = 0;
float currentValue = 0.0f;
int32_t lastPos = -1;
int32_t currentPos = -1;
float lastX = 0.0f;
// * | \---------------/ |
// * current pos
// * pos ...
// TODO : Code the Odd/even and non-zero ...
for (auto &it : listPosition) {
if (currentPos != int32_t(it.first)) {
// fill to the new pos -1:
#if __CPP_VERSION__ >= 2011 && !defined(__TARGET_OS__MacOs) && !defined(__TARGET_OS__IOs)
float endValue = float(etk::min(1,etk::abs(lastState))) * deltaSize;
#else
float endValue = float(etk::min(1,abs(lastState))) * deltaSize;
#endif
for (int32_t iii=currentPos+1; iii<int32_t(it.first); ++iii) {
scanline.set(iii, endValue);
}
currentPos = int32_t(it.first);
currentValue = endValue;
}
int32_t oldState = lastState;
lastState += it.second;
if (oldState == 0) {
// nothing to draw before ...
float ratio = 1.0f - (it.first - float(int32_t(it.first)));
currentValue += ratio * deltaSize;
} else if (lastState == 0) {
// something new to draw ...
float ratio = 1.0f - (it.first - float(int32_t(it.first)));
currentValue -= ratio * deltaSize;
} else {
// nothing to do ...
}
if (currentPos == int32_t(it.first)) {
scanline.set(currentPos, currentValue);
}
}
// if the counter is not at 0 ==> fill if to the end with full value ... 2.0
if (lastState != 0) {
// just past the last state to the end of the image ...
ESVG_ERROR("end of Path whith no end ... " << currentPos << " -> " << _size.x());
for (int32_t xxx=currentPos; xxx<_size.x(); ++xxx) {
scanline.set(xxx, 100.0);
}
}
append(yyy, scanline);
}
}
}

42
esvg/render/Weight.hpp Normal file
View File

@ -0,0 +1,42 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/math/Vector2D.hpp>
#include <esvg/render/Scanline.hpp>
#include <esvg/render/SegmentList.hpp>
namespace esvg {
namespace render {
class Weight {
private:
ivec2 m_size;
etk::Vector<float> m_data;
public:
// constructor :
Weight();
Weight(const ivec2& _size);
// destructor
~Weight();
// -----------------------------------------------
// -- basic tools :
// -----------------------------------------------
public:
void resize(const ivec2& _size);
const ivec2& getSize() const;
int32_t getWidth() const;
int32_t getHeight() const;
void clear(float _fill);
float get(const ivec2& _pos) const;
void set(const ivec2& _pos, float _newColor);
void set(int32_t _posY, const esvg::render::Scanline& _data);
void append(int32_t _posY, const esvg::render::Scanline& _data);
void generate(ivec2 _size, int32_t _subSamplingCount, const esvg::render::SegmentList& _listSegment);
};
}
}

20
esvg/spreadMethod.cpp Normal file
View File

@ -0,0 +1,20 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#include <esvg/spreadMethod.hpp>
#include <esvg/debug.hpp>
static const char* values[] = {
"pad",
"reflect",
"repeat"
};
etk::Stream& esvg::operator <<(etk::Stream& _os, enum esvg::spreadMethod _obj) {
_os << values[_obj];
return _os;
}

23
esvg/spreadMethod.hpp Normal file
View File

@ -0,0 +1,23 @@
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
#pragma once
#include <etk/types.hpp>
#include <etk/Stream.hpp>
namespace esvg {
enum spreadMethod {
spreadMethod_pad,
spreadMethod_reflect,
spreadMethod_repeat
};
/**
* @brief Debug operator To display the curent element in a Human redeable information
*/
etk::Stream& operator <<(etk::Stream& _os, enum esvg::spreadMethod _obj);
}

16
file.mk
View File

@ -1,16 +0,0 @@
FILE_LIST = parserSVG/Base.cpp \
parserSVG/Circle.cpp \
parserSVG/Debug.cpp \
parserSVG/Ellipse.cpp \
parserSVG/Group.cpp \
parserSVG/Line.cpp \
parserSVG/parserSVG.cpp \
parserSVG/Path.cpp \
parserSVG/Polygon.cpp \
parserSVG/Polyline.cpp \
parserSVG/Rectangle.cpp \
parserSVG/Renderer.cpp \
parserSVG/Stroking.cpp \
parserSVG/Text.cpp

36
lutin_esvg-convert.py Normal file
View File

@ -0,0 +1,36 @@
#!/usr/bin/python
import realog.debug as debug
import lutin.tools as tools
def get_type():
return "BINARY"
def get_sub_type():
return "TOOLS"
def get_desc():
return "eSVG converter in bitmap"
def get_licence():
return "MPL-2"
def get_compagny_type():
return "com"
def get_compagny_name():
return "atria-soft"
def get_maintainer():
return "authors.txt"
def configure(target, my_module):
my_module.add_src_file([
'tools/converter.cpp'
])
my_module.add_depend([
'esvg',
'test-debug'
])
return True

52
lutin_esvg-test.py Normal file
View File

@ -0,0 +1,52 @@
#!/usr/bin/python
import realog.debug as debug
import lutin.tools as tools
def get_type():
return "BINARY"
def get_sub_type():
return "TEST"
def get_desc():
return "eSVG test-unit"
def get_licence():
return "MPL-2"
def get_compagny_type():
return "com"
def get_compagny_name():
return "atria-soft"
def get_maintainer():
return "authors.txt"
def configure(target, my_module):
my_module.add_src_file([
'test/main.cpp',
'test/testCircle.cpp',
'test/testEllipse.cpp',
'test/testGroup.cpp',
'test/testLine.cpp',
'test/testParsingFile.cpp',
'test/testPath.cpp',
'test/testPolygon.cpp',
'test/testPolyline.cpp',
'test/testRectangle.cpp',
'test/testJoin.cpp',
'test/testCap.cpp',
'test/testColor.cpp',
'test/testStyle.cpp',
'test/testGradientLinear.cpp',
'test/testGradientRadial.cpp'
])
my_module.add_depend([
'esvg',
'etest',
'test-debug'
])
return True

117
lutin_esvg.py Normal file
View File

@ -0,0 +1,117 @@
#!/usr/bin/python
import realog.debug as debug
import lutin.tools as tools
def get_type():
return "LIBRARY"
def get_desc():
return "SVG image parser and generator"
def get_licence():
return "MPL-2"
def get_compagny_type():
return "com"
def get_compagny_name():
return "atria-soft"
def get_maintainer():
return "authors.txt"
def get_version():
return "version.txt"
def configure(target, my_module):
my_module.add_extra_flags()
my_module.add_depend(['etk', 'exml'])
my_module.add_src_file([
'esvg/Base.cpp',
'esvg/Circle.cpp',
'esvg/debug.cpp',
'esvg/Ellipse.cpp',
'esvg/Group.cpp',
'esvg/Line.cpp',
'esvg/esvg.cpp',
'esvg/Path.cpp',
'esvg/Polygon.cpp',
'esvg/Polyline.cpp',
'esvg/Rectangle.cpp',
'esvg/Renderer.cpp',
'esvg/Text.cpp',
'esvg/cap.cpp',
'esvg/join.cpp',
'esvg/spreadMethod.cpp',
'esvg/gradientUnits.cpp',
'esvg/Dimension.cpp',
'esvg/render/Path.cpp',
'esvg/render/Element.cpp',
'esvg/render/ElementClose.cpp',
'esvg/render/ElementStop.cpp',
'esvg/render/ElementMoveTo.cpp',
'esvg/render/ElementLineTo.cpp',
'esvg/render/ElementLineToH.cpp',
'esvg/render/ElementLineToV.cpp',
'esvg/render/ElementCurveTo.cpp',
'esvg/render/ElementSmoothCurveTo.cpp',
'esvg/render/ElementBezierCurveTo.cpp',
'esvg/render/ElementBezierSmoothCurveTo.cpp',
'esvg/render/ElementElliptic.cpp',
'esvg/render/Point.cpp',
'esvg/render/PointList.cpp',
'esvg/render/Scanline.cpp',
'esvg/render/Segment.cpp',
'esvg/render/SegmentList.cpp',
'esvg/render/Weight.cpp',
'esvg/render/DynamicColor.cpp',
'esvg/LinearGradient.cpp',
'esvg/RadialGradient.cpp'
])
my_module.add_header_file([
'esvg/Base.hpp',
'esvg/Circle.hpp',
'esvg/Ellipse.hpp',
'esvg/Group.hpp',
'esvg/Line.hpp',
'esvg/esvg.hpp',
'esvg/Path.hpp',
'esvg/Polygon.hpp',
'esvg/Polyline.hpp',
'esvg/Rectangle.hpp',
'esvg/Renderer.hpp',
'esvg/Text.hpp',
'esvg/cap.hpp',
'esvg/join.hpp',
'esvg/spreadMethod.hpp',
'esvg/gradientUnits.hpp',
'esvg/Dimension.hpp',
'esvg/render/Element.hpp',
'esvg/render/ElementStop.hpp',
'esvg/render/ElementClose.hpp',
'esvg/render/ElementMoveTo.hpp',
'esvg/render/ElementLineTo.hpp',
'esvg/render/ElementLineToH.hpp',
'esvg/render/ElementLineToV.hpp',
'esvg/render/ElementCurveTo.hpp',
'esvg/render/ElementSmoothCurveTo.hpp',
'esvg/render/ElementBezierCurveTo.hpp',
'esvg/render/ElementBezierSmoothCurveTo.hpp',
'esvg/render/ElementElliptic.hpp',
'esvg/render/Path.hpp',
'esvg/render/Scanline.hpp',
'esvg/render/Point.hpp',
'esvg/render/PointList.hpp',
'esvg/render/Segment.hpp',
'esvg/render/SegmentList.hpp',
'esvg/render/Weight.hpp',
'esvg/render/DynamicColor.hpp',
'esvg/LinearGradient.hpp',
'esvg/RadialGradient.hpp'
])
my_module.add_path(".")
return True

View File

@ -1,469 +0,0 @@
/**
*******************************************************************************
* @file parserSVG/Base.cpp
* @brief basic Element parsing (Sources)
* @author Edouard DUPIN
* @date 20/03/2012
* @par Project
* parserSVG
*
* @par Copyright
* Copyright 2011 Edouard DUPIN, all right reserved
*
* This software is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY.
*
* Licence summary :
* You can modify and redistribute the sources code and binaries.
* You can send me the bug-fix
*
* Term of the licence in in the file licence.txt.
*
*******************************************************************************
*/
#include <parserSVG/Debug.h>
#include <parserSVG/Base.h>
#include <math.h>
svg::Base::Base(PaintState parentPaintState)
{
// copy the parent painting properties ...
m_paint = parentPaintState;
}
/**
* @brief Parse the transform balise C String.
* @param[in] inputString String data inside the transform attribute
* @param[in,out] baseMatrice matrice that must be update
* @return ---
*/
void svg::Base::ParseTransform(TiXmlNode *node)
{
SVG_CHECK_INOUT(node);
const char * inputString = (char*)node->ToElement()->Attribute("transform");
if (NULL == inputString) {
return;
}
SVG_VERBOSE("find transform : \"" << inputString << "\"");
char tmpData[2048];
for (int32_t iii=0; inputString[iii]!='\0' && iii<2047; iii++) {
if (inputString[iii] == ',') {
tmpData[iii] = ' ';
} else {
tmpData[iii] = inputString[iii];
}
// end of the string ...
tmpData[iii+1] = '\0';
}
SVG_VERBOSE("find transform : \"" << tmpData << "\"");
double matrix[6];
float angle, xxx, yyy;
int32_t n;
char * pointerOnData = tmpData;
while (*pointerOnData) {
if (sscanf(pointerOnData, "matrix (%lf %lf %lf %lf %lf %lf) %n", &matrix[0], &matrix[1], &matrix[2], &matrix[3], &matrix[4], &matrix[5], &n) == 6) {
m_transformMatrix.load_from(matrix);
} else if (sscanf(pointerOnData, "translate (%f %f) %n", &xxx, &yyy, &n) == 2) {
m_transformMatrix *= agg::trans_affine_translation(xxx, yyy);
SVG_VERBOSE("Translate : " << xxx << ", " << yyy);
} else if (sscanf(pointerOnData, "translate (%f) %n", &xxx, &n) == 1) {
m_transformMatrix *= agg::trans_affine_translation(xxx, 0);
SVG_VERBOSE("Translate : " << xxx << ", " << 0);
} else if (sscanf(pointerOnData, "scale (%f %f) %n", &xxx, &yyy, &n) == 2) {
m_transformMatrix *= agg::trans_affine_scaling(xxx, yyy);
SVG_VERBOSE("Scale : " << xxx << ", " << yyy);
} else if (sscanf(pointerOnData, "scale (%f) %n", &xxx, &n) == 1) {
m_transformMatrix *= agg::trans_affine_scaling(xxx, xxx);
SVG_VERBOSE("Scale : " << xxx << ", " << xxx);
} else if (sscanf(pointerOnData, "rotate (%f %f %f) %n", &angle, &xxx, &yyy, &n) == 3) {
angle = angle / 180 * M_PI;
m_transformMatrix *= agg::trans_affine_translation(-xxx, -yyy);
m_transformMatrix *= agg::trans_affine_rotation(angle);
m_transformMatrix *= agg::trans_affine_translation(xxx, yyy);
} else if (sscanf(pointerOnData, "rotate (%f) %n", &angle, &n) == 1) {
angle = angle / 180 * M_PI;
SVG_VERBOSE("rotate : " << angle << "rad, " << (angle/M_PI*180) << "°");
m_transformMatrix *= agg::trans_affine_rotation(angle);
} else if (sscanf(pointerOnData, "skewX (%f) %n", &angle, &n) == 1) {
angle = angle / 180 * M_PI;
SVG_VERBOSE("skewX : " << angle << "rad, " << (angle/M_PI*180) << "\Uffffffff");
m_transformMatrix *= agg::trans_affine_skewing(angle, 0.0);
} else if (sscanf(pointerOnData, "skewY (%f) %n", &angle, &n) == 1) {
angle = angle / 180 * M_PI;
SVG_VERBOSE("skewY : " << angle << "rad, " << (angle/M_PI*180) << "\Uffffffff");
m_transformMatrix *= agg::trans_affine_skewing(0.0, angle);
} else {
break;
}
pointerOnData += n;
}
}
/**
* @brief Parse x, y, width, height attribute of the xml node
* @param[in] node XML node
* @param[out] pos parsed position
* @param[out] size parsed dimention
* @return ---
*/
void svg::Base::ParsePosition(const TiXmlNode *node, Vector2D<float> &pos, Vector2D<float> &size)
{
pos.x = 0;
pos.y = 0;
size.x = 0;
size.y = 0;
const char * content = node->ToElement()->Attribute("x");
if (NULL != content) {
pos.x = ParseLength(content);
}
content = node->ToElement()->Attribute("y");
if (NULL != content) {
pos.y = ParseLength(content);
}
content = node->ToElement()->Attribute("width");
if (NULL != content) {
size.x = ParseLength(content);
}
content = node->ToElement()->Attribute("height");
if (NULL != content) {
size.y = ParseLength(content);
}
}
/**
* @brief Parse a lenght of the xml element
* @param[in] dataInput Data C String with the printed lenght
* @return standart number of pixels
*/
float svg::Base::ParseLength(const char *dataInput)
{
int32_t numLength = strspn(dataInput, "0123456789+-.");
const char *unit = dataInput + numLength;
//SVG_INFO(" ==> \"" << dataInput << "\"");
float n = atof(dataInput);
//SVG_INFO(" ==> ?? = " << n );
float font_size = 20.0;
// note : ";" is for the parsing of the style elements ...
if (unit[0] == '\0' || unit[0] == ';' ) {
return n;
} else if (unit[0] == '%') { // xxx %
return n / 100.0 * m_paint.viewPort.x;
} else if (unit[0] == 'e' && unit[1] == 'm') { // xxx em
return n * font_size;
} else if (unit[0] == 'e' && unit[1] == 'x') { // xxx ex
return n / 2.0 * font_size;
} else if (unit[0] == 'p' && unit[1] == 'x') { // xxx px
return n;
} else if (unit[0] == 'p' && unit[1] == 't') { // xxx pt
return n * 1.25;
} else if (unit[0] == 'p' && unit[1] == 'c') { // xxx pc
return n * 15.0;
} else if (unit[0] == 'm' && unit[1] == 'm') { // xxx mm
return n * 3.543307;
} else if (unit[0] == 'c' && unit[1] == 'm') { // xxx cm
return n * 35.43307;
} else if (unit[0] == 'i' && unit[1] == 'n') { // xxx in
return n * 90;
}
return 0;
}
// return the next char position ... (after ';' or NULL)
const char * extractPartOfStyle(const char * input, char * outputType, char * outputData, int32_t maxLen)
{
if (*input == '\0') {
return NULL;
}
int32_t jjj = 0;
const char * outputPointer = NULL;
outputType[maxLen-1] = '\0';
outputType[0] = '\0';
outputData[maxLen-1] = '\0';
outputData[0] = '\0';
char * output = outputType;
for( int32_t iii=0; iii<maxLen-1 && input[iii]!='\0'; iii++) {
outputPointer = &input[iii];
if (input[iii] != ';') {
if (input[iii] == ' ') {
// nothing to do ... we do not copy espaces ...
} else if (input[iii] == ':') {
// change the output ...
output = outputData;
jjj = 0;
} else {
output[jjj] = input[iii];
output[jjj+1] = '\0';
jjj++;
}
} else {
break;
}
}
outputPointer++;
return outputPointer;
}
/**
* @brief Parse a Painting attribute of a specific node
* @param[in] node : basic node of the XML that might be parsed
* @return ---
*/
void svg::Base::ParsePaintAttr(const TiXmlNode *node)
{
bool fillNone = false;
bool strokeNone = false;
const char * content = node->ToElement()->Attribute("fill");
if (NULL != content) {
m_paint.fill = ParseColor(content);
if (m_paint.fill.alpha == 0) {
fillNone = true;
}
}
content = node->ToElement()->Attribute("stroke");
if (NULL != content) {
m_paint.stroke = ParseColor(content);
if (m_paint.stroke.alpha == 0) {
strokeNone = true;
}
}
content = node->ToElement()->Attribute("stroke-width");
if (NULL != content) {
m_paint.strokeWidth = ParseLength(content);
}
content = node->ToElement()->Attribute("opacity");
if (NULL != content) {
float opacity = ParseLength(content);
opacity = etk_max(0.0, etk_min(1.0, opacity));
m_paint.fill.alpha = opacity*0xFF;
m_paint.stroke.alpha = opacity*0xFF;
}
content = node->ToElement()->Attribute("fill-opacity");
if (NULL != content) {
float opacity = ParseLength(content);
opacity = etk_max(0.0, etk_min(1.0, opacity));
m_paint.fill.alpha = opacity*0xFF;
}
content = node->ToElement()->Attribute("stroke-opacity");
if (NULL != content) {
float opacity = ParseLength(content);
opacity = etk_max(0.0, etk_min(1.0, opacity));
m_paint.stroke.alpha = opacity*0xFF;
}
content = node->ToElement()->Attribute("fill-rule");
if (NULL != content) {
if (0 == strcmp(content, "nonzero") ) {
m_paint.flagEvenOdd = false;
} else if (0 == strcmp(content, "evenodd") ) {
m_paint.flagEvenOdd = true;
} else {
SVG_ERROR("not know fill-rule value : \"" << content << "\", not in [nonzero,evenodd]");
}
}
content = node->ToElement()->Attribute("stroke-linecap");
if (NULL != content) {
if (0 == strcmp(content, "butt") ) {
m_paint.lineCap = svg::LINECAP_BUTT;
} else if (0 == strcmp(content, "round") ) {
m_paint.lineCap = svg::LINECAP_ROUND;
} else if (0 == strcmp(content, "square") ) {
m_paint.lineCap = svg::LINECAP_SQUARE;
} else {
m_paint.lineCap = svg::LINECAP_BUTT;
SVG_ERROR("not know stroke-linecap value : \"" << content << "\", not in [butt,round,square]");
}
}
content = node->ToElement()->Attribute("stroke-linejoin");
if (NULL != content) {
if (0 == strcmp(content, "miter") ) {
m_paint.lineJoin = svg::LINEJOIN_MITER;
} else if (0 == strcmp(content, "round") ) {
m_paint.lineJoin = svg::LINEJOIN_ROUND;
} else if (0 == strcmp(content, "bevel") ) {
m_paint.lineJoin = svg::LINEJOIN_BEVEL;
} else {
m_paint.lineJoin = svg::LINEJOIN_MITER;
SVG_ERROR("not know stroke-linejoin value : \"" << content << "\", not in [miter,round,bevel]");
}
}
content = node->ToElement()->Attribute("style");
if (NULL != content) {
char outputType[1024] = "";
char outputValue[1024] = "";
for( const char *sss=extractPartOfStyle(content, outputType, outputValue, 1024);
NULL != sss;
sss=extractPartOfStyle(sss, outputType, outputValue, 1024) ) {
SVG_VERBOSE(" style parse : \"" << outputType << "\" with value : \"" << outputValue << "\"");
if (0 == strcmp(outputType, "fill") ) {
m_paint.fill = ParseColor(outputValue);
SVG_VERBOSE(" input : \"" << outputValue << "\" ==> " << m_paint.fill);
if (m_paint.fill.alpha == 0) {
fillNone = true;
}
} else if (0 == strcmp(outputType, "stroke") ) {
m_paint.stroke = ParseColor(outputValue);
SVG_VERBOSE(" input : \"" << outputValue << "\" ==> " << m_paint.stroke);
if (m_paint.stroke.alpha == 0) {
strokeNone = true;
}
} else if (0 == strcmp(outputType, "stroke-width") ) {
m_paint.strokeWidth = ParseLength(outputValue);
SVG_VERBOSE(" input : \"" << outputValue << "\" ==> " << m_paint.strokeWidth);
} else if (0 == strcmp(outputType, "opacity") ) {
float opacity = ParseLength(outputValue);
opacity = etk_max(0.0, etk_min(1.0, opacity));
m_paint.fill.alpha = opacity*0xFF;
m_paint.stroke.alpha = opacity*0xFF;
SVG_VERBOSE(" input : \"" << outputValue << "\" ==> " << m_paint.fill);
} else if (0 == strcmp(outputType, "fill-opacity") ) {
float opacity = ParseLength(outputValue);
opacity = etk_max(0.0, etk_min(1.0, opacity));
m_paint.fill.alpha = opacity*0xFF;
SVG_VERBOSE(" input : \"" << outputValue << "\" ==> " << m_paint.fill);
} else if (0 == strcmp(outputType, "stroke-opacity") ) {
float opacity = ParseLength(outputValue);
opacity = etk_max(0.0, etk_min(1.0, opacity));
m_paint.stroke.alpha = opacity*0xFF;
SVG_VERBOSE(" input : \"" << outputValue << "\" ==> " << m_paint.stroke);
} else if (0 == strcmp(outputType, "fill-rule") ) {
if (0 == strcmp(outputValue, "nonzero") ) {
m_paint.flagEvenOdd = false;
} else if (0 == strcmp(outputValue, "evenodd") ) {
m_paint.flagEvenOdd = true;
} else {
SVG_ERROR("not know " << outputType << " value : \"" << outputValue << "\", not in [nonzero,evenodd]");
}
} else if (0 == strcmp(outputType, "stroke-linecap") ) {
if (0 == strcmp(outputValue, "butt") ) {
m_paint.lineCap = svg::LINECAP_BUTT;
} else if (0 == strcmp(outputValue, "round") ) {
m_paint.lineCap = svg::LINECAP_ROUND;
} else if (0 == strcmp(outputValue, "square") ) {
m_paint.lineCap = svg::LINECAP_SQUARE;
} else {
m_paint.lineCap = svg::LINECAP_BUTT;
SVG_ERROR("not know " << outputType << " value : \"" << outputValue << "\", not in [butt,round,square]");
}
} else if (0 == strcmp(outputType, "stroke-linejoin") ) {
if (0 == strcmp(outputValue, "miter") ) {
m_paint.lineJoin = svg::LINEJOIN_MITER;
} else if (0 == strcmp(outputValue, "round") ) {
m_paint.lineJoin = svg::LINEJOIN_ROUND;
} else if (0 == strcmp(outputValue, "bevel") ) {
m_paint.lineJoin = svg::LINEJOIN_BEVEL;
} else {
m_paint.lineJoin = svg::LINEJOIN_MITER;
SVG_ERROR("not know " << outputType << " value : \"" << outputValue << "\", not in [miter,round,bevel]");
}
} else if (0 == strcmp(outputType, "marker-start") ) {
// TODO : ...
} else {
SVG_ERROR("not know painting element in style balise : \"" << outputType << "\" with value : \"" << outputValue << "\"");
}
}
}
// check if somewere none is set to the filling:
if (true == fillNone) {
m_paint.fill.alpha = 0;
}
if (true == strokeNone) {
m_paint.stroke.alpha = 0;
}
}
bool strnCmpNoCase(const char * input1, const char * input2, int32_t maxLen)
{
int32_t iii=0;
while ('\0' != *input1 && '\0' != *input2 && iii < maxLen) {
char in1 = *input1;
char in2 = *input2;
if (in1 != in2) {
if (in1 <= 'Z' && in1 >= 'A') {
in1 = in1 - 'A' + 'a';
}
if (in2 <= 'Z' && in2 >= 'A') {
in2 = in2 - 'A' + 'a';
}
if (in1 != in2) {
return false;
}
}
iii++;
input1++;
input2++;
}
return true;
}
/**
* @brief Parse a color specification from the svg file
* @param[in] inputData Data C String with the xml definition
* @return the parsed color
*/
color_ts svg::Base::ParseColor(const char *inputData)
{
color_ts localColor = etk::color::color_White;;
size_t len = strlen(inputData);
if( 4 < len
&& inputData[0] == 'u'
&& inputData[1] == 'r'
&& inputData[2] == 'l'
&& inputData[3] == '(') {
if (inputData[4] == '#') {
// TODO : parse gradient ...
}
SVG_ERROR(" pb in parsing the color : \"" << inputData << "\" ==> url(XXX) is not supported now ...");
} else {
localColor = etk::color::Parse(inputData);
}
SVG_VERBOSE("Parse color : \"" << inputData << "\" ==> " << localColor);
return localColor;
}
/**
* @brief Parse all the element needed in the basic node
* @param[in] node standart XML node
* @return true if no problem arrived
*/
bool svg::Base::Parse(TiXmlNode * node, agg::trans_affine& parentTrans, Vector2D<float>& sizeMax)
{
SVG_ERROR("NOT IMPLEMENTED");
sizeMax.x = 0;
sizeMax.y = 0;
return false;
}
const char * svg::Base::SpacingDist(int32_t spacing)
{
static const char *tmpValue = " ";
if (spacing>20) {
spacing = 20;
}
return tmpValue + 20*4 - spacing*4;
}
/*
void svg::Base::AggCheckChange(agg::path_storage& path, etk::VectorType<agg::rgba8> &colors, etk::VectorType<uint32_t> &pathIdx, PaintState &curentPaintProp)
{
if (curentPaintProp != m_paint) {
SVG_INFO("add path color = " << m_paint.fill);
// New color. Every new color creates new path in the path object.
colors.PushBack(agg::rgba8(m_paint.fill.red, m_paint.fill.green, m_paint.fill.blue, m_paint.fill.alpha));
uint32_t tmpPathNew = path.start_new_path();
pathIdx.PushBack(tmpPathNew);
curentPaintProp = m_paint;
}
}
*/

View File

@ -1,70 +0,0 @@
/**
*******************************************************************************
* @file parserSVG/Base.h
* @brief basic Element parsing (Header)
* @author Edouard DUPIN
* @date 20/03/2012
* @par Project
* parserSVG
*
* @par Copyright
* Copyright 2011 Edouard DUPIN, all right reserved
*
* This software is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY.
*
* Licence summary :
* You can modify and redistribute the sources code and binaries.
* You can send me the bug-fix
*
* Term of the licence in in the file licence.txt.
*
*******************************************************************************
*/
#ifndef __SVG_BASE_H__
#define __SVG_BASE_H__
#include <etk/Types.h>
#include <etk/VectorType.h>
#include <tinyXML/tinyxml.h>
#include <parserSVG/Renderer.h>
#include <agg/agg_basics.h>
#include <agg/agg_rendering_buffer.h>
#include <agg/agg_rasterizer_scanline_aa.h>
#include <agg/agg_scanline_p.h>
#include <agg/agg_renderer_scanline.h>
#include <agg/agg_path_storage.h>
#include <agg/agg_conv_transform.h>
#include <agg/agg_bounding_rect.h>
#include <agg/agg_color_rgba.h>
#include <agg/agg_pixfmt_rgba.h>
namespace svg
{
class Base
{
protected:
PaintState m_paint;
agg::trans_affine m_transformMatrix; //!< specific render of the curent element
const char * SpacingDist(int32_t spacing);
public:
Base(void) {};
Base(PaintState parentPaintState);
virtual ~Base(void) { };
virtual bool Parse(TiXmlNode * node, agg::trans_affine& parentTrans, Vector2D<float>& sizeMax);
//specific drawing for AAG librairy ...
virtual void AggDraw(svg::Renderer& myRenderer, agg::trans_affine& basicTrans) { };
virtual void Display(int32_t spacing) { };
void ParseTransform(TiXmlNode *node);
void ParsePosition(const TiXmlNode *node, Vector2D<float> &pos, Vector2D<float> &size);
float ParseLength(const char *dataInput);
void ParsePaintAttr(const TiXmlNode *node);
color_ts ParseColor(const char *inputData);
};
};
#endif

View File

@ -1,116 +0,0 @@
/**
*******************************************************************************
* @file parserSVG/Circle.cpp
* @brief basic circle parsing (Sources)
* @author Edouard DUPIN
* @date 20/03/2012
* @par Project
* parserSVG
*
* @par Copyright
* Copyright 2011 Edouard DUPIN, all right reserved
*
* This software is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY.
*
* Licence summary :
* You can modify and redistribute the sources code and binaries.
* You can send me the bug-fix
*
* Term of the licence in in the file licence.txt.
*
*******************************************************************************
*/
#include <parserSVG/Debug.h>
#include <parserSVG/Circle.h>
#include <agg/agg_conv_stroke.h>
#include <agg/agg_ellipse.h>
svg::Circle::Circle(PaintState parentPaintState) : svg::Base(parentPaintState)
{
}
svg::Circle::~Circle(void)
{
}
bool svg::Circle::Parse(TiXmlNode * node, agg::trans_affine& parentTrans, Vector2D<float>& sizeMax)
{
m_radius = 0.0;
m_position.x = 0.0;
m_position.y = 0.0;
ParseTransform(node);
ParsePaintAttr(node);
// add the property of the parrent modifications ...
m_transformMatrix *= parentTrans;
const char * content = node->ToElement()->Attribute("cx");
if (NULL != content) {
m_position.x = ParseLength(content);
}
content = node->ToElement()->Attribute("cy");
if (NULL != content) {
m_position.y = ParseLength(content);
}
content = node->ToElement()->Attribute("r");
if (NULL != content) {
m_radius = ParseLength(content);
} else {
SVG_ERROR("(l "<<node->Row()<<") Circle \"r\" is not present");
return false;
}
if (0 > m_radius) {
m_radius = 0;
SVG_ERROR("(l "<<node->Row()<<") Circle \"r\" is negative");
return false;
}
sizeMax.x = m_position.x + m_radius;
sizeMax.y = m_position.y + m_radius;
return true;
}
void svg::Circle::Display(int32_t spacing)
{
SVG_DEBUG(SpacingDist(spacing) << "Circle " << m_position << " radius=" << m_radius);
}
void svg::Circle::AggDraw(svg::Renderer& myRenderer, agg::trans_affine& basicTrans)
{
myRenderer.m_renderArea->color(agg::rgba8(m_paint.fill.red, m_paint.fill.green, m_paint.fill.blue, m_paint.fill.alpha));
// Creating an ellipse
agg::ellipse myCircle(m_position.x, m_position.y, m_radius, m_radius, 0);
// Calculate transformation matrix ...
agg::trans_affine mtx = m_transformMatrix;
mtx *= basicTrans;
// set the filling mode :
myRenderer.m_rasterizer.filling_rule((m_paint.flagEvenOdd)?agg::fill_even_odd:agg::fill_non_zero);
if (m_paint.fill.alpha != 0x00) {
agg::conv_transform<agg::ellipse, agg::trans_affine> trans(myCircle, mtx);
myRenderer.m_rasterizer.add_path(trans);
agg::render_scanlines(myRenderer.m_rasterizer, myRenderer.m_scanLine, *myRenderer.m_renderArea);
}
if (m_paint.strokeWidth > 0 && m_paint.stroke.alpha!=0x00 ) {
myRenderer.m_renderArea->color(agg::rgba8(m_paint.stroke.red, m_paint.stroke.green, m_paint.stroke.blue, m_paint.stroke.alpha));
// Drawing as an outline
agg::conv_stroke<agg::ellipse> myCircleStroke(myCircle);
myCircleStroke.width(m_paint.strokeWidth);
agg::conv_transform<agg::conv_stroke<agg::ellipse>, agg::trans_affine> transStroke(myCircleStroke, mtx);
// set the filling mode :
myRenderer.m_rasterizer.filling_rule(agg::fill_non_zero);
myRenderer.m_rasterizer.add_path(transStroke);
agg::render_scanlines(myRenderer.m_rasterizer, myRenderer.m_scanLine, *myRenderer.m_renderArea);
}
}

View File

@ -1,47 +0,0 @@
/**
*******************************************************************************
* @file parserSVG/Circle.h
* @brief basic circle parsing (Header)
* @author Edouard DUPIN
* @date 20/03/2012
* @par Project
* parserSVG
*
* @par Copyright
* Copyright 2011 Edouard DUPIN, all right reserved
*
* This software is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY.
*
* Licence summary :
* You can modify and redistribute the sources code and binaries.
* You can send me the bug-fix
*
* Term of the licence in in the file licence.txt.
*
*******************************************************************************
*/
#ifndef __SVG_CIRCLE_H__
#define __SVG_CIRCLE_H__
#include <parserSVG/Base.h>
namespace svg
{
class Circle : public svg::Base
{
private:
Vector2D<float> m_position; //!< Position of the Circle
float m_radius; //!< Radius of the Circle
public:
Circle(PaintState parentPaintState);
~Circle(void);
virtual bool Parse(TiXmlNode * node, agg::trans_affine& parentTrans, Vector2D<float>& sizeMax);
virtual void Display(int32_t spacing);
virtual void AggDraw(svg::Renderer& myRenderer, agg::trans_affine& basicTrans);
};
};
#endif

View File

@ -1,27 +0,0 @@
/**
*******************************************************************************
* @file parserSVG/Debug.h
* @brief parserSVG : log wrapper (Sources)
* @author Edouard DUPIN
* @date 18/03/2012
* @par Project
* parserSVG
*
* @par Copyright
* Copyright 2011 Edouard DUPIN, all right reserved
*
* This software is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY.
*
* Licence summary :
* You can modify and redistribute the sources code and binaries.
* You can send me the bug-fix
*
* Term of the licence in in the file licence.txt.
*
*******************************************************************************
*/
#include <parserSVG/Debug.h>
const char * parserSVGLibName = "parserSVG";

View File

@ -1,44 +0,0 @@
/**
*******************************************************************************
* @file tinySVG/Debug.h
* @brief SVG : log wrapper (header)
* @author Edouard DUPIN
* @date 18/03/2012
* @par Project
* parserSVG
*
* @par Copyright
* Copyright 2011 Edouard DUPIN, all right reserved
*
* This software is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY.
*
* Licence summary :
* You can modify and redistribute the sources code and binaries.
* You can send me the bug-fix
*
* Term of the licence in in the file licence.txt.
*
*******************************************************************************
*/
#ifndef __PARSER_SVG_DEBUG_H__
#define __PARSER_SVG_DEBUG_H__
#include <etk/Types.h>
#include <etk/Debug.h>
extern const char * parserSVGLibName;
#define SVG_CRITICAL(data) ETK_CRITICAL(parserSVGLibName, data)
#define SVG_WARNING(data) ETK_WARNING(parserSVGLibName, data)
#define SVG_ERROR(data) ETK_ERROR(parserSVGLibName, data)
#define SVG_INFO(data) ETK_INFO(parserSVGLibName, data)
#define SVG_DEBUG(data) ETK_DEBUG(parserSVGLibName, data)
#define SVG_VERBOSE(data) ETK_VERBOSE(parserSVGLibName, data)
#define SVG_ASSERT(cond, data) ETK_ASSERT(parserSVGLibName, cond, data)
#define SVG_CHECK_INOUT(cond) ETK_CHECK_INOUT(parserSVGLibName, cond)
#define SVG_TODO(cond) ETK_TODO(parserSVGLibName, cond)
#endif

Some files were not shown because too many files have changed in this diff Show More