Blender V4.3
stl_export_writer.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
9#include <cstdint>
10#include <cstdio>
11#include <stdexcept>
12
13/* SEP macro from BLI path utils clashes with SEP symbol in fmt headers. */
14#undef SEP
15#include <fmt/format.h>
16
17#include "stl_data.hh"
18#include "stl_export_writer.hh"
19
20#include "BLI_fileops.h"
21
22namespace blender::io::stl {
23
24FileWriter::FileWriter(const char *filepath, bool ascii) : tris_num_(0), ascii_(ascii)
25{
26 file_ = BLI_fopen(filepath, "wb");
27 if (file_ == nullptr) {
28 throw std::runtime_error("STL export: failed to open file");
29 }
30
31 /* Write header */
32 if (ascii_) {
33 fmt::print(file_, "solid \n");
34 }
35 else {
36 const char header[BINARY_HEADER_SIZE] = {};
37 fwrite(header, 1, BINARY_HEADER_SIZE, file_);
38 /* Write placeholder for number of triangles, so that it can be updated later (after all
39 * triangles have been written). */
40 fwrite(&tris_num_, sizeof(uint32_t), 1, file_);
41 }
42}
43
45{
46 if (file_ == nullptr) {
47 return;
48 }
49 if (ascii_) {
50 fmt::print(file_, "endsolid \n");
51 }
52 else {
53 fseek(file_, BINARY_HEADER_SIZE, SEEK_SET);
54 fwrite(&tris_num_, sizeof(uint32_t), 1, file_);
55 }
56 fclose(file_);
57}
58
60{
61 tris_num_++;
62 if (ascii_) {
63 fmt::print(file_,
64 "facet normal {} {} {}\n"
65 " outer loop\n"
66 " vertex {} {} {}\n"
67 " vertex {} {} {}\n"
68 " vertex {} {} {}\n"
69 " endloop\n"
70 "endfacet\n",
71
72 data.normal.x,
73 data.normal.y,
74 data.normal.z,
75 data.vertices[0].x,
76 data.vertices[0].y,
77 data.vertices[0].z,
78 data.vertices[1].x,
79 data.vertices[1].y,
80 data.vertices[1].z,
81 data.vertices[2].x,
82 data.vertices[2].y,
83 data.vertices[2].z);
84 }
85 else {
86 fwrite(&data, sizeof(data), 1, file_);
87 }
88}
89
90} // namespace blender::io::stl
File and directory operations.
FILE * BLI_fopen(const char *filepath, const char *mode) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
FileWriter(const char *filepath, bool ascii)
void write_triangle(const PackedTriangle &data)
constexpr size_t BINARY_HEADER_SIZE
Definition stl_data.hh:21
unsigned int uint32_t
Definition stdint.h:80