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