载入中...
搜索中...
未找到
PbrMaterial.cpp
浏览该文件的文档.
7
8#include "image/ImageData.h"
9
10#include <algorithm>
11#include <cmath>
12#include <utility>
13
14namespace eve::procgen {
15
17
19 delete albedo;
20 delete normal;
21 delete roughness;
22 delete metallic;
23 delete height;
24 delete ao;
25 albedo = normal = roughness = metallic = height = ao = nullptr;
26}
27
32
36 descriptor.displayName = id;
37 registerPbrRecipe(std::move(descriptor), std::move(fn));
38}
39
41 const std::string id = descriptor.id;
42 recipes_[id] = Entry{std::move(fn), std::move(descriptor)};
43}
44
45bool PbrRecipeRegistry::has(const std::string &id) const {
46 return recipes_.find(id) != recipes_.end();
47}
48
49std::unique_ptr<PbrTextureSet> PbrRecipeRegistry::generate(const std::string &id, const Params &params,
50 std::string &error) const {
51 auto it = recipes_.find(id);
52 if (it == recipes_.end()) {
53 error = "unknown pbr recipe: " + id;
54 return {};
55 }
56 return it->second.fn(params, error);
57}
58
59const RecipeDescriptor *PbrRecipeRegistry::descriptor(const std::string &id) const {
60 const auto it = recipes_.find(id);
61 return it == recipes_.end() ? nullptr : &it->second.descriptor;
62}
63
64bool PbrRecipeRegistry::applyDefaults(const std::string &id, Params &params) const {
65 const RecipeDescriptor *schema = descriptor(id);
66 if (!schema) return false;
67 schema->applyDefaults(params);
68 return true;
69}
70
71std::vector<std::string> PbrRecipeRegistry::list() const {
72 std::vector<std::string> ids;
73 ids.reserve(recipes_.size());
74 for (const auto &kv : recipes_) ids.push_back(kv.first);
75 std::sort(ids.begin(), ids.end());
76 return ids;
77}
78
80 if (builtinsRegistered_) return;
81 for (const TextureRecipeDef &def : builtinTextureDefs()) {
82 const std::string id = "pbr." + def.id.substr(def.id.find('.') + 1);
84 descriptor.id = id;
85 descriptor.category = "Material";
86 descriptor.params.push_back(ParamDescriptor::floating("roughnessLow", "Low Roughness", def.pbr.roughnessLow, 0.f, 1.f, 0.01f));
87 descriptor.params.push_back(ParamDescriptor::floating("roughnessHigh", "High Roughness", def.pbr.roughnessHigh, 0.f, 1.f, 0.01f));
88 descriptor.params.push_back(ParamDescriptor::floating("metallic", "Metallic", def.pbr.metallic, 0.f, 1.f, 0.01f));
89 descriptor.params.push_back(ParamDescriptor::floating("normalStrength", "Normal Strength", def.pbr.normalStrength, 0.01f, 32.f, 0.05f));
90 descriptor.params.push_back(ParamDescriptor::floating("aoStrength", "AO Strength", def.pbr.aoStrength, 0.f, 5.f, 0.05f));
91 descriptor.params.push_back(ParamDescriptor::floating("heightStrength", "Height Strength", def.pbr.heightStrength, 0.f, 16.f, 0.05f));
92 registerPbrRecipe(std::move(descriptor), [def](const Params &params, std::string &error) {
93 return generatePbrSet(def, params, error);
94 });
95 }
98 // Existing registry/script entry points project the canonical Result factory.
99 const char *names[] = {"wood", "metal", "rubber", "cloth", "plastic", "steel", "glass",
100 "paper", "aluminum", "cast_iron", "cement", "paint", "marble"};
101 for (size_t i = 0; i < 13; ++i) {
102 auto schema =
103 RecipeDescriptor::grid(std::string("pbr.everyday.") + names[i], names[i], "Everyday Material", 1, 1);
104 for (auto &parameter : schema.params) {
105 if (parameter.key == "width" || parameter.key == "height") parameter.maximum = 2048;
106 }
107 schema.params.push_back(ParamDescriptor::floating("scale", "Pattern Repeats", 4.f, 1.f, 32.f, 1.f));
108 schema.params.push_back(ParamDescriptor::floating("detail", "Surface Detail", .5f, 0.f, 1.f, .01f));
109 schema.params.push_back(ParamDescriptor::floating("finish", "Polish", .5f, 0.f, 1.f, .01f));
110 schema.params.push_back(ParamDescriptor::floating("variation", "Color Variation", .4f, 0.f, 1.f, .01f));
111 registerPbrRecipe(std::move(schema),
112 [family = static_cast<EverydayMaterial>(i)](const Params &p, std::string &error) {
113 auto result = EverydayMaterials::generate(family, p);
114 if (!result.ok()) {
115 error = "Everyday material generation failed: unsupported family or size";
116 return std::unique_ptr<PbrTextureSet>{};
117 }
118 error.clear();
119 return std::move(result).takeValue();
120 });
121 }
122 builtinsRegistered_ = true;
123}
124
125std::unique_ptr<image::ImageData> grayscaleImage(const std::vector<float> &values, int w, int h) {
126 auto img = std::make_unique<image::ImageData>(w, h, "RGBA8");
127 auto *pixels = static_cast<uint8_t *>(img->getData());
128 for (int i = 0; i < w * h && i < int(values.size()); ++i) {
129 const uint8_t v = uint8_t(std::lround(std::clamp(values[size_t(i)], 0.f, 1.f) * 255.f));
130 const size_t o = size_t(i) * 4u;
131 pixels[o + 0] = pixels[o + 1] = pixels[o + 2] = v;
132 pixels[o + 3] = 255;
133 }
134 return img;
135}
136
137std::unique_ptr<PbrTextureSet> generatePbrSet(const TextureRecipeDef &def, const Params &params, std::string &error) {
138 const auto ctx = TextureGenContext::fromParams(params);
139 if (ctx.width > 4096 || ctx.height > 4096) {
140 error = "texture size too large (max 4096)";
141 return {};
142 }
143
144 // Recipe defaults, then per-call overrides.
145 PbrParams pbr = def.pbr;
146 pbr.roughnessLow = std::clamp(params.getFloat("roughnessLow", pbr.roughnessLow), 0.f, 1.f);
147 pbr.roughnessHigh = std::clamp(params.getFloat("roughnessHigh", pbr.roughnessHigh), 0.f, 1.f);
148 pbr.metallic = std::clamp(params.getFloat("metallic", pbr.metallic), 0.f, 1.f);
149 pbr.normalStrength = std::max(0.01f, params.getFloat("normalStrength", pbr.normalStrength));
150 pbr.aoStrength = std::clamp(params.getFloat("aoStrength", pbr.aoStrength), 0.f, 5.f);
151 pbr.heightStrength = std::max(0.f, params.getFloat("heightStrength", pbr.heightStrength));
152
153 std::vector<float> height;
154 fillHeightField(ctx, def.height, height);
155 const int w = ctx.width;
156 const int h = ctx.height;
157
158 auto set = std::make_unique<PbrTextureSet>();
159 set->albedo = new image::ImageData(w, h, "RGBA8");
160 std::vector<float> pigment;
161 if (def.colorField) fillHeightField(ctx, def.colorField, pigment);
162 paintHeightToImage(*set->albedo, def.colorField ? pigment : height, w, h, def.albedo, ctx.colors, ctx.pixelSize);
163 set->normal = heightToNormalImage(height, w, h, pbr.normalStrength, ctx.seamless).release();
164
165 std::vector<float> microfacet;
166 if (def.roughnessField) fillHeightField(ctx, def.roughnessField, microfacet);
167 std::vector<float> rough(size_t(w * h));
168 std::vector<float> heightMap(size_t(w * h));
169 std::vector<float> ao(size_t(w * h));
170 const int r = std::max(1, std::min(w, h) / 64); // cavity sampling radius
171 // Separable sliding box mean: O(w*h), including wrapped or clipped boundaries.
172 // This is the same cavity footprint as the original nested neighbourhood scan.
173 std::vector<float> horizontal(height.size()), neighbourhood(height.size());
174 auto wrap = [](int coordinate, int extent) { return (coordinate % extent + extent) % extent; };
175 for (int y = 0; y < h; ++y) {
176 double sum = 0.0;
177 int count = 0;
178 auto update = [&](int x, int sign) {
179 if (!ctx.seamless && (x < 0 || x >= w)) return;
180 sum += sign * double(height[size_t(y) * size_t(w) + size_t(wrap(x, w))]);
181 count += sign;
182 };
183 for (int x = -r; x <= r; ++x) update(x, 1);
184 for (int x = 0; x < w; ++x) {
185 horizontal[size_t(y) * size_t(w) + size_t(x)] = float(sum / count);
186 update(x - r, -1);
187 update(x + r + 1, 1);
188 }
189 }
190 for (int x = 0; x < w; ++x) {
191 double sum = 0.0;
192 int count = 0;
193 auto update = [&](int y, int sign) {
194 if (!ctx.seamless && (y < 0 || y >= h)) return;
195 sum += sign * double(horizontal[size_t(wrap(y, h)) * size_t(w) + size_t(x)]);
196 count += sign;
197 };
198 for (int y = -r; y <= r; ++y) update(y, 1);
199 for (int y = 0; y < h; ++y) {
200 neighbourhood[size_t(y) * size_t(w) + size_t(x)] = float(sum / count);
201 update(y - r, -1);
202 update(y + r + 1, 1);
203 }
204 }
205 for (int y = 0; y < h; ++y) {
206 for (int x = 0; x < w; ++x) {
207 const size_t i = size_t(y) * size_t(w) + size_t(x);
208 const float hh = height[i];
209 rough[size_t(i)] =
210 pbr.roughnessLow + (pbr.roughnessHigh - pbr.roughnessLow) * (def.roughnessField ? microfacet[i] : hh);
211 heightMap[i] = std::clamp(0.5f + (hh - 0.5f) * pbr.heightStrength, 0.f, 1.f);
212
213 const float local = neighbourhood[i];
214 ao[i] = std::clamp(1.f - pbr.aoStrength * std::max(0.f, local - hh), 0.f, 1.f);
215 }
216 }
217 set->roughness = grayscaleImage(rough, w, h).release();
218 set->metallic = grayscaleImage(std::vector<float>(size_t(w * h), pbr.metallic), w, h).release();
219 set->height = grayscaleImage(heightMap, w, h).release();
220 set->ao = grayscaleImage(ao, w, h).release();
221 return set;
222}
223
224} // namespace eve::procgen
double y
double x
float w
Definition AnimClip.cpp:738
std::string descriptor
float ao
float pigment
glm::vec4 p[6]
double r
float v
int h
std::uint32_t height
std::string local
std::string id
Poco::JSON::Object::Ptr result
std::vector< RecipeParam > params
graphics::PbrSurface pbr
std::string error
Definition Package.cpp:174
std::set< std::string > values
uint8_t * pixels
std::string parameter
int count
Represents raw pixel data.
Definition ImageData.h:38
static eve::Result< std::unique_ptr< PbrTextureSet > > generate(EverydayMaterial family, const Params &params)
Generate six aligned maps and optical surface metadata.
Owning, typed generation parameters.
Definition Params.h:27
EVENGINE_API_DOMAINS public API.
Definition PbrMaterial.h:68
const RecipeDescriptor * descriptor(const std::string &id) const
Look up recipe metadata.
static PbrRecipeRegistry & instance()
Access the process-wide PBR registry.
bool applyDefaults(const std::string &id, Params &params) const
Fill missing values from metadata.
std::vector< std::string > list() const
List recipe ids.
std::unique_ptr< PbrTextureSet > generate(const std::string &id, const Params &params, std::string &error) const
Generates a PBR map set and transfers its unique ownership to the caller.
void registerPbrBuiltins()
Register engine-provided PBR recipes once.
void registerPbrRecipe(const std::string &id, PbrRecipeFn fn)
Register a recipe without metadata.
bool has(const std::string &id) const
Test whether a recipe exists.
std::unordered_map< const void *, size_t > ids
Definition Snapshot.cpp:109
void registerFloorPbrRecipes(PbrRecipeRegistry &registry)
Register pbr.floor.wood and pbr.floor.tile with schema metadata.
void registerCablePbrRecipes(PbrRecipeRegistry &registry)
Register pbr.cable.steel / pbr.chain.iron / pbr.rope.hemp.
void fillHeightField(const TextureGenContext &ctx, const std::function< float(float, float, const NoiseField &)> &fn, std::vector< float > &height)
Sample a height function over the full [w×h] grid into height (clamped to [0,1]).
RecipeDescriptor makeTextureRecipeDescriptor(const TextureRecipeDef &definition)
Build editable metadata for a texture definition.
std::unique_ptr< image::ImageData > grayscaleImage(const std::vector< float > &values, int w, int h)
Builds a grayscale RGBA8 image and returns unique ownership to the caller.
const std::vector< TextureRecipeDef > & builtinTextureDefs()
All built-in texture definitions (albedo + PBR). Populated lazily.
std::unique_ptr< PbrTextureSet > generatePbrSet(const TextureRecipeDef &def, const Params &params, std::string &error)
Builds a full PBR set from a texture definition and returns unique ownership.
void paintHeightToImage(image::ImageData &img, const std::vector< float > &height, int w, int h, const ColorRamp &ramp, int bands, int pixelSize)
Paint height to image.
EverydayMaterial
Everyday surface families; no scene, GPU or registry state is retained.
std::unique_ptr< image::ImageData > heightToNormalImage(const std::vector< float > &height, int w, int h, float strength, bool seamless)
Builds a normal-map image and transfers its unique ownership to the caller.
std::function< std::unique_ptr< PbrTextureSet >(const Params &params, std::string &error)> PbrRecipeFn
Recipe returns a newly owned full PBR set, or null on failure.
Definition PbrMaterial.h:65
SettlementPipeline::Stage fn
static ParamDescriptor floating(std::string key, std::string label, float defaultValue, float minimum, float maximum, float step)
Construct a bounded floating-point descriptor.
PBR surface defaults for a generated material. Every map in a PBR set is derived from the same displa...
~PbrTextureSet()
Releases all generated maps when the owning set is destroyed.
void destroy()
Deletes all maps and nulls the pointers (defined in PbrMaterial.cpp).
image::ImageData * normal
Definition PbrMaterial.h:38
image::ImageData * height
Definition PbrMaterial.h:41
image::ImageData * ao
Definition PbrMaterial.h:42
image::ImageData * albedo
Definition PbrMaterial.h:37
image::ImageData * roughness
Definition PbrMaterial.h:39
image::ImageData * metallic
Definition PbrMaterial.h:40
Complete metadata and parameter schema shared by every procgen recipe family.
Definition ParamSchema.h:52
static RecipeDescriptor grid(std::string id, std::string displayName, std::string category, int minimumWidth, int minimumHeight, int maximumWidth=4096, int maximumHeight=4096)
Create a schema with common seed, width and height parameters.
void applyDefaults(Params &params) const
Fill missing Params values from this schema.
static EVENGINE_API_DOMAINS TextureGenContext fromParams(const Params &params)
From params.
A procedural texture is described by an albedo ramp, displacement, optional independent PBR pigment f...
std::function< float(float, float, const NoiseField &)> height
Float.
std::function< float(float, float, const NoiseField &)> colorField
Optional pigment field, independent of physical relief; empty uses height.
std::function< float(float, float, const NoiseField &)> roughnessField
Optional independent microfacet field, mapped through roughnessLow/High.