Skip to content
Snippets Groups Projects
import_svg.py 46.2 KiB
Newer Older
  • Learn to ignore specific revisions
  • 
        def _transformCoord(self, point):
            """
            Transform SVG-file coords
            """
    
            v = Vector((point[0], point[1], 0.0))
    
            return v * self._context['matrix']
    
        def getNodeMatrix(self):
            """
            Get transformation matrix of node
            """
    
            return SVGMatrixFromNode(self._node, self._context)
    
        def parse(self):
            """
            Parse XML node to memory
            """
    
            pass
    
        def _doCreateGeom(self):
            """
            Internal handler to create real geometries
            """
    
            pass
    
    
    Sergey Sharybin's avatar
    Sergey Sharybin committed
        def getTransformMatrix(self):
    
            """
            Get matrix created from "transform" attribute
            """
    
            transform = self._node.getAttribute('transform')
    
            if transform:
                return SVGParseTransform(transform)
    
            return None
    
        def createGeom(self):
            """
            Create real geometries
            """
    
            if self._creating:
                return
    
            self._creating = True
    
    
    Sergey Sharybin's avatar
    Sergey Sharybin committed
            matrix = self.getTransformMatrix()
    
            if matrix is not None:
                self._pushMatrix(matrix)
    
            self._doCreateGeom()
    
            if matrix is not None:
                self._popMatrix()
    
            self._creating = False
    
    
    class SVGGeometryContainer(SVGGeometry):
        """
        Container of SVG geometries
        """
    
        __slots__ = ('_geometries')  # List of chold geometries
    
        def __init__(self, node, context):
            """
            Initialize SVG geometry container
            """
    
            super().__init__(node, context)
    
            self._geometries = []
    
        def parse(self):
            """
            Parse XML node to memory
            """
    
            for node in self._node.childNodes:
                if type(node) is not xml.dom.minidom.Element:
                    continue
    
                ob = parseAbstractNode(node, self._context)
                if ob is not None:
                    self._geometries.append(ob)
    
        def _doCreateGeom(self):
            """
            Create real geometries
            """
    
            for geom in self._geometries:
                geom.createGeom()
    
        def getGeometries(self):
            """
            Get list of parsed geometries
            """
    
            return self._geometries
    
    
    class SVGGeometryPATH(SVGGeometry):
        """
        SVG path geometry
        """
    
        __slots__ = ('_splines',  # List of splines after parsing
    
    Sergey Sharybin's avatar
    Sergey Sharybin committed
                     '_styles')  # Styles, used for displaying
    
    
        def __init__(self, node, context):
            """
            Initialize SVG path
            """
    
            super().__init__(node, context)
    
            self._splines = []
    
            self._styles = SVGEmptyStyles
    
    
        def parse(self):
            """
            Parse SVG path node
            """
    
            d = self._node.getAttribute('d')
    
            pathParser = SVGPathParser(d)
            pathParser.parse()
    
            self._splines = pathParser.getSplines()
    
    Sergey Sharybin's avatar
    Sergey Sharybin committed
            self._styles = SVGParseStyles(self._node, self._context)
    
    
        def _doCreateGeom(self):
            """
            Create real geometries
            """
    
            ob = SVGCreateCurve()
            cu = ob.data
    
    
    Sergey Sharybin's avatar
    Sergey Sharybin committed
            if self._node.getAttribute('id'):
                cu.name = self._node.getAttribute('id')
    
    
    Sergey Sharybin's avatar
    Sergey Sharybin committed
            if self._styles['useFill']:
    
                cu.dimensions = '2D'
    
    Sergey Sharybin's avatar
    Sergey Sharybin committed
                cu.materials.append(self._styles['fill'])
    
            else:
                cu.dimensions = '3D'
    
            for spline in self._splines:
                act_spline = None
                for point in spline['points']:
    
                    co = self._transformCoord((point['x'], point['y']))
    
    
                    if act_spline is None:
                        cu.splines.new('BEZIER')
    
                        act_spline = cu.splines[-1]
                        act_spline.use_cyclic_u = spline['closed']
                    else:
                        act_spline.bezier_points.add()
    
                    bezt = act_spline.bezier_points[-1]
    
                    bezt.co = co
    
    
                    bezt.handle_left_type = point['handle_left_type']
                    if point['handle_left'] is not None:
                        handle = point['handle_left']
                        bezt.handle_left = self._transformCoord(handle)
    
                    bezt.handle_right_type = point['handle_right_type']
                    if point['handle_right'] is not None:
                        handle = point['handle_right']
                        bezt.handle_right = self._transformCoord(handle)
    
            SVGFinishCurve()
    
    
    class SVGGeometryDEFS(SVGGeometryContainer):
        """
        Container for referenced elements
        """
    
        def _doCreateGeom(self):
            """
            Create real geometries
            """
    
            pass
    
    
    class SVGGeometrySYMBOL(SVGGeometryContainer):
        """
        Referenced element
        """
    
        def _doCreateGeom(self):
            """
            Create real geometries
            """
    
            pass
    
    
    class SVGGeometryG(SVGGeometryContainer):
        """
        Geometry group
        """
    
        pass
    
    
    class SVGGeometryUSE(SVGGeometry):
        """
        User of referenced elements
        """
    
        def _doCreateGeom(self):
            """
            Create real geometries
            """
    
            geometries = []
            ref = self._node.getAttribute('xlink:href')
            geom = self._context['defines'].get(ref)
    
            if geom is not None:
    
    Sergey Sharybin's avatar
    Sergey Sharybin committed
                rect = SVGRectFromNode(self._node, self._context)
                self._pushRect(rect)
    
    
                self._pushMatrix(self.getNodeMatrix())
    
    Sergey Sharybin's avatar
    Sergey Sharybin committed
    
                geomMatrix = None
                nodeMatrix = None
    
                if not isinstance(geom, SVGGeometryUSE):
                    geomMatrix = geom.getTransformMatrix()
    
                if isinstance(geom, SVGGeometrySYMBOL):
                    nodeMatrix = geom.getNodeMatrix()
    
                if nodeMatrix:
                    self._pushMatrix(nodeMatrix)
    
                if geomMatrix:
                    self._pushMatrix(geomMatrix)
    
    
                if isinstance(geom, SVGGeometryContainer):
                    geometries = geom.getGeometries()
                else:
                    geometries = [geom]
    
                for g in geometries:
                    g.createGeom()
    
    
    Sergey Sharybin's avatar
    Sergey Sharybin committed
                if geomMatrix:
                    self._popMatrix()
    
                if nodeMatrix:
                    self._popMatrix()
    
    
    Sergey Sharybin's avatar
    Sergey Sharybin committed
                self._popRect()
    
    
    1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
    class SVGGeometryRECT(SVGGeometry):
        """
        SVG rectangle
        """
    
        __slots__ = ('_rect',  # coordinate and domensions of rectangle
                     '_radius',  # Rounded corner radiuses
                     '_styles')  # Styles, used for displaying
    
        def __init__(self, node, context):
            """
            Initialize new rectangle
            """
    
            super().__init__(node, context)
    
            self._rect = ('0', '0', '0', '0')
            self._radius = ('0', '0')
            self._styles = SVGEmptyStyles
    
        def parse(self):
            """
            Parse SVG rectangle node
            """
    
            self._styles = SVGParseStyles(self._node, self._context)
    
            rect = []
            for attr in ['x', 'y', 'width', 'height']:
                val = self._node.getAttribute(attr)
                rect.append(val or '0')
    
            self._rect = (rect)
    
            rx = self._node.getAttribute('rx')
            ry = self._node.getAttribute('ry')
    
            self._radius = (rx, ry)
    
        def _appendCorner(self, spline, coord, firstTime, rounded):
            """
            Append new corner to rectangle
            """
    
            handle = None
            if len(coord) == 3:
                handle = self._transformCoord(coord[2])
                coord = (coord[0], coord[1])
    
            co = self._transformCoord(coord)
    
            if not firstTime:
                spline.bezier_points.add()
    
            bezt = spline.bezier_points[-1]
            bezt.co = co
    
            if rounded:
                if handle:
                    bezt.handle_left_type = 'VECTOR'
                    bezt.handle_right_type = 'FREE'
    
                    bezt.handle_right = handle
                else:
                    bezt.handle_left_type = 'FREE'
                    bezt.handle_right_type = 'VECTOR'
                    bezt.handle_left = co
    
            else:
                bezt.handle_left_type = 'VECTOR'
                bezt.handle_right_type = 'VECTOR'
    
        def _doCreateGeom(self):
            """
            Create real geometries
            """
    
            # Run-time parsing -- percents would be correct only if
            # parsing them now
            crect = self._context['rect']
            rect = []
    
            for i in range(4):
                rect.append(SVGParseCoord(self._rect[i], crect[i % 2]))
    
            r = self._radius
            rx = ry = 0.0
    
            if r[0] and r[1]:
                rx = min(SVGParseCoord(r[0], rect[0]), rect[2] / 2)
                ry = min(SVGParseCoord(r[1], rect[1]), rect[3] / 2)
            elif r[0]:
                rx = min(SVGParseCoord(r[0], rect[0]), rect[2] / 2)
                ry = min(rx, rect[3] / 2)
                rx = ry = min(rx, ry)
            elif r[1]:
                ry = min(SVGParseCoord(r[1], rect[1]), rect[3] / 2)
                rx = min(ry, rect[2] / 2)
                rx = ry = min(rx, ry)
    
            radius = (rx, ry)
    
            # Geometry creation
            ob = SVGCreateCurve()
            cu = ob.data
    
            if self._styles['useFill']:
                cu.dimensions = '2D'
                cu.materials.append(self._styles['fill'])
            else:
                cu.dimensions = '3D'
    
            cu.splines.new('BEZIER')
    
            spline = cu.splines[-1]
            spline.use_cyclic_u = True
    
            x, y = rect[0], rect[1]
            w, h = rect[2], rect[3]
            rx, ry = radius[0], radius[1]
            rounded = False
    
            if rx or ry:
                #
                #      0 _______ 1
                #     /           \
                #    /             \
                #   7               2
                #   |               |
                #   |               |
                #   6               3
                #    \             /
                #     \           /
                #      5 _______ 4
                #
    
                # Optional third component -- right handle coord
                coords = [(x + rx, y),
                          (x + w - rx, y, (x + w, y)),
                          (x + w, y + ry),
                          (x + w, y + h - ry, (x + w, y + h)),
                          (x + w - rx, y + h),
                          (x + rx, y + h, (x, y + h)),
                          (x, y + h - ry),
                          (x, y + ry, (x, y))]
    
                rounded = True
            else:
                coords = [(x, y), (x + w, y), (x + w, y + h), (x, y + h)]
    
            firstTime = True
            for coord in coords:
                self._appendCorner(spline, coord, firstTime, rounded)
                firstTime = False
    
            SVGFinishCurve()
    
    
    class SVGGeometryELLIPSE(SVGGeometry):
        """
        SVG ellipse
        """
    
        __slots__ = ('_cx',  # X-coordinate of center
                     '_cy',  # Y-coordinate of center
                     '_rx',  # X-axis radius of circle
                     '_ry',  # Y-axis radius of circle
                     '_styles')  # Styles, used for displaying
    
        def __init__(self, node, context):
            """
            Initialize new ellipse
            """
    
            super().__init__(node, context)
    
            self._cx = '0.0'
            self._cy = '0.0'
            self._rx = '0.0'
            self._ry = '0.0'
            self._styles = SVGEmptyStyles
    
        def parse(self):
            """
            Parse SVG ellipse node
            """
    
            self._styles = SVGParseStyles(self._node, self._context)
    
            self._cx = self._node.getAttribute('cx') or '0'
            self._cy = self._node.getAttribute('cy') or '0'
            self._rx = self._node.getAttribute('rx') or '0'
            self._ry = self._node.getAttribute('ry') or '0'
    
        def _doCreateGeom(self):
            """
            Create real geometries
            """
    
            # Run-time parsing -- percents would be correct only if
            # parsing them now
            crect = self._context['rect']
    
            cx = SVGParseCoord(self._cx, crect[0])
            cy = SVGParseCoord(self._cy, crect[1])
            rx = SVGParseCoord(self._rx, crect[0])
            ry = SVGParseCoord(self._ry, crect[1])
    
            if not rx or not ry:
                # Automaic handles will work incorrect in this case
                return
    
            # Create circle
            ob = SVGCreateCurve()
            cu = ob.data
    
            if self._styles['useFill']:
                cu.dimensions = '2D'
                cu.materials.append(self._styles['fill'])
            else:
                cu.dimensions = '3D'
    
            coords = [((cx - rx, cy),
                       (cx - rx, cy + ry * 0.552),
                       (cx - rx, cy - ry * 0.552)),
    
                      ((cx, cy - ry),
                       (cx - rx * 0.552, cy - ry),
                       (cx + rx * 0.552, cy - ry)),
    
                      ((cx + rx, cy),
                       (cx + rx, cy - ry * 0.552),
                       (cx + rx, cy + ry * 0.552)),
    
                      ((cx, cy + ry),
                       (cx + rx * 0.552, cy + ry),
                       (cx - rx * 0.552, cy + ry))]
    
            spline = None
            for coord in coords:
                co = self._transformCoord(coord[0])
                handle_left = self._transformCoord(coord[1])
                handle_right = self._transformCoord(coord[2])
    
                if spline is None:
                    cu.splines.new('BEZIER')
                    spline = cu.splines[-1]
                    spline.use_cyclic_u = True
                else:
                    spline.bezier_points.add()
    
                bezt = spline.bezier_points[-1]
                bezt.co = co
                bezt.handle_left_type = 'FREE'
                bezt.handle_right_type = 'FREE'
                bezt.handle_left = handle_left
                bezt.handle_right = handle_right
    
            SVGFinishCurve()
    
    
    class SVGGeometryCIRCLE(SVGGeometryELLIPSE):
        """
        SVG circle
        """
    
        def parse(self):
            """
            Parse SVG circle node
            """
    
            self._styles = SVGParseStyles(self._node, self._context)
    
            self._cx = self._node.getAttribute('cx') or '0'
            self._cy = self._node.getAttribute('cy') or '0'
    
            r = self._node.getAttribute('r') or '0'
            self._rx = self._ry = r
    
    
    class SVGGeometryLINE(SVGGeometry):
        """
        SVG line
        """
    
        __slots__ = ('_x1',  # X-coordinate of beginning
                     '_y1',  # Y-coordinate of beginning
                     '_x2',  # X-coordinate of ending
                     '_y2')  # Y-coordinate of ending
    
        def __init__(self, node, context):
            """
            Initialize new line
            """
    
            super().__init__(node, context)
    
            self._x1 = '0.0'
            self._y1 = '0.0'
            self._x2 = '0.0'
            self._y2 = '0.0'
    
        def parse(self):
            """
            Parse SVG line node
            """
    
            self._x1 = self._node.getAttribute('x1') or '0'
            self._y1 = self._node.getAttribute('y1') or '0'
            self._x2 = self._node.getAttribute('x2') or '0'
            self._y2 = self._node.getAttribute('y2') or '0'
    
        def _doCreateGeom(self):
            """
            Create real geometries
            """
    
            # Run-time parsing -- percents would be correct only if
            # parsing them now
            crect = self._context['rect']
    
            x1 = SVGParseCoord(self._x1, crect[0])
            y1 = SVGParseCoord(self._y1, crect[1])
            x2 = SVGParseCoord(self._x2, crect[0])
            y2 = SVGParseCoord(self._y2, crect[1])
    
            # Create cline
            ob = SVGCreateCurve()
            cu = ob.data
    
            coords = [(x1, y1), (x2, y2)]
            spline = None
    
            for coord in coords:
                co = self._transformCoord(coord)
    
                if spline is None:
                    cu.splines.new('BEZIER')
                    spline = cu.splines[-1]
                    spline.use_cyclic_u = True
                else:
                    spline.bezier_points.add()
    
                bezt = spline.bezier_points[-1]
                bezt.co = co
                bezt.handle_left_type = 'VECTOR'
                bezt.handle_right_type = 'VECTOR'
    
            SVGFinishCurve()
    
    
    class SVGGeometryPOLY(SVGGeometry):
        """
        Abstract class for handling poly-geometries
        (polylines and polygons)
        """
    
        __slots__ = ('_points',  # Array of points for poly geometry
                     '_styles',  # Styles, used for displaying
                     '_closed')  # Should generated curve be closed?
    
        def __init__(self, node, context):
            """
            Initialize new poly geometry
            """
    
            super().__init__(node, context)
    
            self._points = []
            self._styles = SVGEmptyStyles
            self._closed = False
    
        def parse(self):
            """
            Parse poly node
            """
    
            self._styles = SVGParseStyles(self._node, self._context)
    
            points = self._node.getAttribute('points')
            points = points.replace(',', ' ').replace('-', ' -')
            points = points.split()
    
            prev = None
            self._points = []
    
            for p in points:
                if prev is None:
                    prev = p
                else:
                    self._points.append((float(prev), float(p)))
                    prev = None
    
        def _doCreateGeom(self):
            """
            Create real geometries
            """
    
            ob = SVGCreateCurve()
            cu = ob.data
    
            if self._closed and self._styles['useFill']:
                cu.dimensions = '2D'
                cu.materials.append(self._styles['fill'])
            else:
                cu.dimensions = '3D'
    
            spline = None
    
            for point in self._points:
                co = self._transformCoord(point)
    
                if spline is None:
                    cu.splines.new('BEZIER')
                    spline = cu.splines[-1]
                    spline.use_cyclic_u = self._closed
                else:
                    spline.bezier_points.add()
    
                bezt = spline.bezier_points[-1]
                bezt.co = co
                bezt.handle_left_type = 'VECTOR'
                bezt.handle_right_type = 'VECTOR'
    
            SVGFinishCurve()
    
    
    class SVGGeometryPOLYLINE(SVGGeometryPOLY):
        """
        SVG polyline geometry
        """
    
        pass
    
    
    class SVGGeometryPOLYGON(SVGGeometryPOLY):
        """
        SVG polygon geometry
        """
    
        def __init__(self, node, context):
            """
            Initialize new polygon geometry
            """
    
            super().__init__(node, context)
    
            self._closed = True
    
    
    
    class SVGGeometrySVG(SVGGeometryContainer):
        """
        Main geometry holder
        """
    
        def _doCreateGeom(self):
            """
            Create real geometries
            """
    
            rect = SVGRectFromNode(self._node, self._context)
    
            self._pushMatrix(self.getNodeMatrix())
            self._pushRect(rect)
    
            super()._doCreateGeom()
    
            self._popRect()
            self._popMatrix()
    
    
    class SVGLoader(SVGGeometryContainer):
        """
        SVG file loader
        """
    
    
    Sergey Sharybin's avatar
    Sergey Sharybin committed
        def getTransformMatrix(self):
            """
            Get matrix created from "transform" attribute
            """
    
            # SVG document doesn't support transform specification
            # it can't even hold attributes
    
            return None
    
    
        def __init__(self, filepath):
            """
            Initialize SVG loader
            """
    
            node = xml.dom.minidom.parse(filepath)
    
            m = Matrix()
            m = m * m.Scale(1.0 / 90.0, 4, Vector((1.0, 0.0, 0.0)))
            m = m * m.Scale(-1.0 / 90.0, 4, Vector((0.0, 1.0, 0.0)))
    
            rect = (1, 1)
    
            self._context = {'defines': {},
                             'transform': [],
                             'rects': [rect],
                             'rect': rect,
                             'matrix': m,
                             'materials': {}}
    
            super().__init__(node, self._context)
    
    
    svgGeometryClasses = {
        'svg': SVGGeometrySVG,
        'path': SVGGeometryPATH,
        'defs': SVGGeometryDEFS,
        'symbol': SVGGeometrySYMBOL,
        'use': SVGGeometryUSE,
    
        'rect': SVGGeometryRECT,
        'ellipse': SVGGeometryELLIPSE,
        'circle': SVGGeometryCIRCLE,
        'line': SVGGeometryLINE,
        'polyline': SVGGeometryPOLYLINE,
        'polygon': SVGGeometryPOLYGON,
    
        'g': SVGGeometryG}
    
    
    def parseAbstractNode(node, context):
        name = node.tagName.lower()
    
    Sergey Sharybin's avatar
    Sergey Sharybin committed
    
        if name.startswith('svg:'):
            name = name[4:]
    
    
        geomClass = svgGeometryClasses.get(name)
    
        if geomClass is not None:
            ob = geomClass(node, context)
            ob.parse()
    
            return ob
    
        return None
    
    
    def load_svg(filepath):
        """
        Load specified SVG file
        """
    
        if bpy.ops.object.mode_set.poll():
            bpy.ops.object.mode_set(mode='OBJECT')
    
        loader = SVGLoader(filepath)
        loader.parse()
        loader.createGeom()
    
    
    def load(operator, context, filepath=""):
    
        load_svg(filepath)
    
        return {'FINISHED'}