ldcheck.py

Mon, 22 Jan 2018 18:07:19 +0200

author
Santeri Piippo
date
Mon, 22 Jan 2018 18:07:19 +0200
changeset 21
8006fb8cdb77
parent 18
672ebc45685a
child 26
7c263b864371
permissions
-rwxr-xr-x

refactor

#!/usr/bin/env python3
from sys import version_info
if version_info < (3, 4):
    raise RuntimeError('Python 3.4 or newer required')

from parse import parse_ldraw_code
from colours import load_colours
from geometry import *
from pathlib import Path
import linetypes

from os.path import realpath
script_directory = Path(realpath(__file__)).parent

def load_config(filename):
    from configobj import ConfigObj
    from copy import deepcopy
    config = ConfigObj(filename, encoding = 'UTF8')
    read_config = deepcopy(config)
    if 'libraries' not in config:
        config['libraries'] = ['/path/to/ldraw']
    if config != read_config:
        config.write()
    return config

def read_ldraw(file, *, name = '', config):
    model_body = [
        parse_ldraw_code(line)
        for line in file
    ]
    model = Model(body = model_body)
    model.name = name
    return model

def library_paths(config):
    for library_path_string in config['libraries']:
        yield Path(library_path_string).expanduser()

def find_ldconfig_ldr_paths(config):
    for library_path in library_paths(config):
        yield from [
            library_path / path
            for path in ['LDConfig.ldr', 'ldconfig.ldr']
            if (library_path / path).is_file()
        ]

def hairline_score(smallest_angle):
    from math import log10
    return max(0, -log10(smallest_angle))

class Model:
    def __init__(self, body):
        self.body = body
        self.body_offset = 0
    def filter_by_type(self, type):
        yield from [
            element
            for element in self.body
            if isinstance(element, type)
        ]
    @property
    def subfile_references(self):
        yield from self.filter_by_type(linetypes.SubfileReference)
    @property
    def line_segments(self):
        yield from self.filter_by_type(linetypes.LineSegment)
    @property
    def triangles(self):
        yield from self.filter_by_type(linetypes.Triangle)
    @property
    def quadrilaterals(self):
        yield from self.filter_by_type(linetypes.Quadrilateral)

if __name__ == '__main__':
    from sys import argv
    config = load_config('ldcheck.cfg')
    for ldconfig_ldr_path in find_ldconfig_ldr_paths(config):
        with ldconfig_ldr_path.open() as ldconfig_ldr:
            load_colours(ldconfig_ldr)
    with open(argv[1], 'r') as file:
        from os.path import basename
        model = read_ldraw(file, name = basename(argv[1]), config = config)
        from testsuite import load_tests, check_model, format_report
        test_suite = load_tests()
        report = check_model(model, test_suite)
        print(format_report(report, model, test_suite))

mercurial