File size: 3,820 Bytes
b642dd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
from OCC.Core.STEPControl import STEPControl_Reader
from OCC.Core.IFSelect import IFSelect_RetDone
from OCC.Core.StlAPI import StlAPI_Writer
from OCC.Core.BRepMesh import BRepMesh_IncrementalMesh
import os
import sys
import math

class TeeOutput:
    def __init__(self, *files):
        self.files = files
    def write(self, data):
        for f in self.files:
            f.write(data)
            f.flush()
    def flush(self):
        for f in self.files:
            f.flush()

def remove_extension(fname):
    lower = fname.lower()
    if lower.endswith(".step"):
        return fname[:-5]
    elif lower.endswith(".stp"):
        return fname[:-4]
    return fname

def step_to_stl(step_file_path, output_stl_path,
                mesh_linear_deflection=0.05,
                mesh_angular_deflection=0.3):
    """Convert a single STEP file to STL (dense mesh)."""
    print(f"\nReading STEP file: {step_file_path}")
    step_reader = STEPControl_Reader()
    status = step_reader.ReadFile(step_file_path)
    if status != IFSelect_RetDone:
        raise ValueError(f"Cannot read STEP file: {step_file_path}")

    print("STEP file read successfully.")
    step_reader.TransferRoots()
    shape = step_reader.OneShape()

    if shape.IsNull():
        raise ValueError("No shape found in STEP file.")

    print("Generating dense mesh...")
    # Smaller linear deflection → denser mesh
    mesh = BRepMesh_IncrementalMesh(shape, mesh_linear_deflection, True,
                                    mesh_angular_deflection, True)
    mesh.Perform()
    if not mesh.IsDone():
        raise RuntimeError("Mesh generation failed.")

    print("Mesh generation complete. Writing STL...")
    stl_writer = StlAPI_Writer()
    stl_writer.SetASCIIMode(False)  # Binary STL for compact size
    success = stl_writer.Write(shape, output_stl_path)

    if not success:
        raise RuntimeError(f"Failed to write STL: {output_stl_path}")

    print(f"STL saved successfully: {output_stl_path}")

def process_step_folder(input_dir, output_dir,
                        mesh_linear_deflection=0.05,
                        mesh_angular_deflection=0.3):
    """Process all STEP/STP files in a directory and convert to STL."""
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    log_path = os.path.join(output_dir, "conversion_log.txt")
    log_file = open(log_path, "a", buffering=1)
    sys.stdout = TeeOutput(sys.stdout, log_file)

    files = sorted([f for f in os.listdir(input_dir)
                    if f.lower().endswith((".step", ".stp"))])
    total = len(files)
    if total == 0:
        print("No STEP files found in directory.")
        return

    print(f"Found {total} STEP files in '{input_dir}'")
    processed = 0

    for fname in files:
        step_path = os.path.join(input_dir, fname)
        stl_name = remove_extension(fname) + ".stl"
        stl_path = os.path.join(output_dir, stl_name)

        try:
            step_to_stl(step_path, stl_path,
                        mesh_linear_deflection=mesh_linear_deflection,
                        mesh_angular_deflection=mesh_angular_deflection)
            processed += 1
        except Exception as e:
            print(f"❌ Failed to process {fname}: {e}")

        print(f"Progress: {processed}/{total} files complete.")

    log_file.close()
    print(f"\nConversion complete! {processed}/{total} STL files saved to '{output_dir}'")

if __name__ == "__main__":
    input_folder = r"C:\Users\nandh\Desktop\diffusionNet\step"
    output_folder = os.path.join(os.path.dirname(input_folder), "stl")

    # Smaller deflection → denser mesh (try 0.01 for very dense)
    process_step_folder(
        input_folder,
        output_folder,
        mesh_linear_deflection=0.01,  # denser mesh
        mesh_angular_deflection=0.2
    )