载入中...
搜索中...
未找到
BuildingAssembly.cpp
浏览该文件的文档.
1#include <algorithm>
2#include <limits>
3#include <set>
7
8namespace eve::building {
9using namespace assembly_detail;
10PreparedAssembly::PreparedAssembly(std::unique_ptr<PreparedAssemblyData> data) : data_(std::move(data)) {}
11PreparedAssembly::PreparedAssembly(PreparedAssembly&&) noexcept = default;
12PreparedAssembly& PreparedAssembly::operator=(PreparedAssembly&&) noexcept = default;
13PreparedAssembly::~PreparedAssembly() = default;
14std::span<const PlacedBuilding> PreparedAssembly::preview() const {
15 return data_ ? std::span<const PlacedBuilding>(data_->preview) : std::span<const PlacedBuilding>{};
16}
17namespace {
19 const std::map<int, int>& remap, EdgeCurveGroupId id) {
20 if (!source.surfaceSamples.empty())
21 return fail<EdgeCurveGroup>("Surface-attached curves must be recaptured on their provider");
22 auto out = source;
23 out.id = id;
24 out.level = source.level - from.level + to.level;
25 int q = (to.quarterTurns - from.quarterTurns + 4) % 4;
26 for (auto& p : out.controlPoints) {
27 float x = p.x - from.x, y = p.y - from.y;
28 for (int i = 0; i < q; ++i) {
29 float old = x;
30 x = y;
31 y = -old;
32 }
33 p.x = x + to.x;
34 p.y = y + to.y;
35 }
36 for (int& member : out.instanceIds) {
37 auto it = remap.find(member);
38 if (it == remap.end()) return fail<EdgeCurveGroup>("Capture requires complete curve membership");
39 member = it->second;
40 }
41 return Result<EdgeCurveGroup>::success(std::move(out));
42}
43} // namespace
44Result<BuildingBlueprint> AssemblyService::capture(const PlacementWorld& w, std::span<const int> members, AssetGuid id,
46 auto grid = checkGrid(w);
47 if (!grid.ok() || id.isNil() || members.empty())
48 return fail<BuildingBlueprint>("Capture requires a valid grid, asset identity and selection");
50 b.id = id;
51 b.cellSize = w.getCellSize();
52 b.floorHeight = w.getFloorHeight();
53 b.definitions = Value::Object{};
54 std::map<int, int> remap;
55 int key = 0;
56 for (int member : members)
57 if (!w.hasBuilding(member) || !remap.emplace(member, ++key).second)
58 return fail<BuildingBlueprint>("Missing or duplicate capture member");
59 for (int member : members) {
60 const auto& p = w.buildings_.at(member);
61 for (int support : p.supportInstanceIds)
62 if (!remap.contains(support))
63 return fail<BuildingBlueprint>("Selection has structural support outside the house");
64 auto transformed = transformPart(p, w, origin, {});
65 if (!transformed.ok()) return fail<BuildingBlueprint>("Could not transform captured part");
66 auto local = std::move(transformed).takeValue();
67 local.instanceId = remap.at(member);
68 local.edgeCurveGroupId = {};
69 local.worldX -= w.getOriginX();
70 local.worldY -= w.getOriginY();
71 local.garrison.clear();
72 local.garrisonRevision = Revision::zero();
73 // Arbitrary properties may contain foreign entity ids; only definition defaults transfer.
74 local.props.clear();
75 b.parts.push_back({{uint32_t(local.instanceId)}, codec::snapshot(local)});
76 const auto* def = BuildingRegistry::find(p.buildingId);
77 if (!def) return fail<BuildingBlueprint>("Missing captured definition");
78 b.definitions.set(p.buildingId, definitionValue(*def));
79 }
80 for (auto curveId : w.edgeCurveGroupIds()) {
81 const auto& curve = w.edgeCurveGroups_.at(curveId.value);
82 if (std::none_of(curve.instanceIds.begin(), curve.instanceIds.end(),
83 [&](int member) { return remap.contains(member); }))
84 continue;
85 auto transformed = transformedCurve(curve, origin, {}, remap, {uint64_t(b.curves.size() + 1)});
86 if (!transformed.ok()) return fail<BuildingBlueprint>("Selection contains a partial or surface-attached curve");
88 payload.group = std::move(transformed).takeValue();
89 for (int member : payload.group.instanceIds) payload.instances.push_back(b.parts[size_t(member - 1)].local);
90 b.curves.push_back(std::move(payload));
91 }
92 return Result<BuildingBlueprint>::success(std::move(b));
93}
94Result<PreparedAssembly> AssemblyService::prepareState(const PlacementWorld& w,
95 std::unique_ptr<PlacementWorld> candidate, AssemblyId id) {
96 auto valid = validateFinal(*candidate);
97 if (!valid.ok()) return Result<PreparedAssembly>::failure(valid.status());
98 auto before = snapshotWorld(w);
99 if (!before.ok()) return fail<PreparedAssembly>("Cannot snapshot source world");
100 auto token = std::make_unique<PreparedAssemblyData>();
101 token->epoch = w.assemblyState_->epoch;
102 token->before = std::move(before).takeValue();
103 token->admission = admissionStamp(w);
104 token->definitions = definitionsFor(*candidate);
105 token->id = id;
106 if (auto it = candidate->assemblyState_->records.find(id); it != candidate->assemblyState_->records.end())
107 for (const auto& [key, member] : it->second.members) token->preview.push_back(candidate->buildings_.at(member));
108 token->candidate = std::move(candidate);
110}
111Result<PreparedAssembly> AssemblyService::preparePlacement(const PlacementWorld& w, const BuildingBlueprint& b,
113 auto encoded = encodeBlueprint(b);
114 if (!encoded.ok() || id.isNil() || w.assemblyState_->records.contains(id) || b.cellSize != w.getCellSize() ||
115 b.floorHeight != w.getFloorHeight())
116 return fail<PreparedAssembly>("Invalid blueprint, incompatible scale or duplicate house identity");
117 if (b.parts.size() > size_t(std::numeric_limits<int>::max() - w.instanceCounter_) ||
118 w.assemblyState_->nextSlot == std::numeric_limits<uint32_t>::max())
119 return fail<PreparedAssembly>("World identity capacity exhausted");
120 auto candidate = w.cloneState();
122 a.id = id;
123 a.blueprint = b.id;
124 a.blueprintVersion = b.version;
125 a.frame = pose;
126 std::map<int, int> remap;
127 for (const auto& part : b.parts) {
128 auto p = codec::runtime(part.local);
129 p.worldX += w.getOriginX();
130 p.worldY += w.getOriginY();
131 auto transformed = transformPart(p, w, {}, pose);
132 if (!transformed.ok()) return fail<PreparedAssembly>("Invalid transformed blueprint part");
133 p = std::move(transformed).takeValue();
134 p.instanceId = PlacementSystem::nextInstanceId(*candidate);
135 p.edgeCurveGroupId = {};
136 remap.emplace(part.local.instanceId, p.instanceId);
137 a.members.emplace(part.id.value, p.instanceId);
138 a.nextPartKey = std::max(a.nextPartKey, part.id.value + 1);
139 candidate->instanceOrder_.push_back(p.instanceId);
140 candidate->buildings_.emplace(p.instanceId, std::move(p));
141 }
142 for (const auto& c : b.curves) {
143 auto curve = transformedCurve(c.group, {}, pose, remap, {candidate->nextEdgeCurveGroupId_++});
144 if (!curve.ok()) return fail<PreparedAssembly>("Invalid transformed curve");
145 const auto curveId = curve.value().id.value;
146 candidate->edgeCurveGroups_.emplace(curveId, std::move(curve).takeValue());
147 }
148 candidate->assemblyState_->records.emplace(id, std::move(a));
149 candidate->assemblyState_->handles[id] =
150 eve::RuntimeHandle<AssemblyHandleTag>(candidate->assemblyState_->nextSlot++, 1);
151 return prepareState(w, std::move(candidate), id);
152}
153Result<PreparedAssembly> AssemblyService::prepareMove(const PlacementWorld& w, AssemblyId id, AssemblyPose pose) {
154 auto it = w.assemblyState_->records.find(id);
155 if (it == w.assemblyState_->records.end())
156 return fail<PreparedAssembly>("House not found", DiagnosticCode::NotFound);
157 auto candidate = w.cloneState();
158 std::map<int, int> remap;
159 for (const auto& [key, member] : it->second.members) {
160 auto p = transformPart(w.buildings_.at(member), w, it->second.frame, pose);
161 if (!p.ok()) return fail<PreparedAssembly>("Cannot transform house member");
162 candidate->buildings_.at(member) = std::move(p).takeValue();
164 }
165 for (auto& [curveId, curve] : candidate->edgeCurveGroups_) {
166 if (std::none_of(curve.instanceIds.begin(), curve.instanceIds.end(), [&](int m) { return remap.contains(m); }))
167 continue;
168 auto moved = transformedCurve(curve, it->second.frame, pose, remap, curve.id);
169 if (!moved.ok()) return fail<PreparedAssembly>("Cannot move a shared or surface-attached curve");
170 curve = std::move(moved).takeValue();
171 }
172 candidate->assemblyState_->records.at(id).frame = pose;
173 return prepareState(w, std::move(candidate), id);
174}
175Result<PreparedAssembly> AssemblyService::prepareRemoval(const PlacementWorld& w, AssemblyId id) {
176 auto a = assembly(w, id);
177 if (!a.ok()) return fail<PreparedAssembly>("House not found", DiagnosticCode::NotFound);
178 auto candidate = w.cloneState();
179 for (const auto& [key, member] : a.value().members)
180 PlacementSystem::removeBuildingUnchecked(candidate.get(), member);
181 candidate->assemblyState_->records.erase(id);
182 candidate->assemblyState_->handles.erase(id);
183 return prepareState(w, std::move(candidate), id);
184}
185Result<PreparedAssembly> AssemblyService::prepareRemodel(const PlacementWorld& w, AssemblyId id,
186 std::span<const PlacedBuilding> members) {
187 auto old = assembly(w, id);
188 if (!old.ok()) return Result<PreparedAssembly>::failure(old.status());
189 if (members.empty()) return prepareRemoval(w, id);
190 auto candidate = w.cloneState();
191 auto a = old.value();
192 std::map<int, uint32_t> keys;
193 uint32_t nextKey = a.nextPartKey;
194 for (const auto& [key, member] : a.members) {
195 keys[member] = key;
196 candidate->buildings_.erase(member);
197 }
198 std::erase_if(candidate->instanceOrder_, [&](int member) { return keys.contains(member); });
199 a.members.clear();
200 std::set<int> seen;
201 for (auto p : members) {
202 uint32_t key = 0;
203 if (p.instanceId) {
204 auto it = keys.find(p.instanceId);
205 if (it == keys.end() || !seen.insert(p.instanceId).second)
206 return fail<PreparedAssembly>("Remodel cannot steal or duplicate a member");
207 key = it->second;
208 } else {
209 if (candidate->instanceCounter_ == std::numeric_limits<int>::max() ||
210 nextKey >= uint32_t(std::numeric_limits<int>::max()))
211 return fail<PreparedAssembly>("Member identity capacity exhausted");
212 p.instanceId = PlacementSystem::nextInstanceId(*candidate);
213 key = nextKey++;
214 }
215 a.members.emplace(key, p.instanceId);
216 candidate->instanceOrder_.push_back(p.instanceId);
217 candidate->buildings_.emplace(p.instanceId, std::move(p));
218 }
219 // Curves remain authoritative only if all exact addresses survive; partial edits dissolve them.
220 std::erase_if(candidate->edgeCurveGroups_, [&](const auto& entry) {
221 for (int member : entry.second.instanceIds) {
222 auto current = candidate->buildings_.find(member);
223 auto previous = w.buildings_.find(member);
224 if (current == candidate->buildings_.end() || previous == w.buildings_.end() ||
225 current->second.edge != previous->second.edge ||
226 current->second.buildingId != previous->second.buildingId ||
227 current->second.level != previous->second.level)
228 return true;
229 }
230 return false;
231 });
232 a.nextPartKey = nextKey;
233 candidate->assemblyState_->records[id] = std::move(a);
234 return prepareState(w, std::move(candidate), id);
235}
237 if (!token.data_ || token.data_->epoch != w.assemblyState_->epoch)
238 return fail<AssemblyReceipt>("Expired prepared house operation", DiagnosticCode::Conflict);
239 auto& t = *token.data_;
240 auto current = snapshotWorld(w);
241 auto defs = checkDefinitions(t.definitions);
242 const bool currentOk = current.ok();
243 const bool definitionsOk = defs.ok();
244 if (!currentOk || current.value() != t.before || !definitionsOk || admissionStamp(w) != t.admission)
245 return fail<AssemblyReceipt>("World or definitions changed since preparation", DiagnosticCode::Conflict);
246 auto valid = validateFinal(*t.candidate);
247 if (!valid.ok()) return Result<AssemblyReceipt>::failure(valid.status());
248 auto after = snapshotWorld(*t.candidate);
249 if (!after.ok()) return fail<AssemblyReceipt>("Cannot capture commit receipt");
250 AssemblyReceipt receipt{t.id, std::move(t.before), std::move(after).takeValue()};
251 // Invalidate other prepared tokens after every commit; existing assembly handles are
252 // intentionally invalidated too, and callers resolve persistent identities again.
253 t.candidate->assemblyState_->epoch = nextEpoch();
254 w.swapState(*t.candidate);
255 if (w.publishEvents_) {
257 e.action = "reset";
258 e.worldId = w.getId();
259 PlacementSystem::pushEvent(std::move(e));
260 }
261 return Result<AssemblyReceipt>::success(std::move(receipt));
262}
263Result<BuildingAssembly> AssemblyService::assembly(const PlacementWorld& w, AssemblyId id) {
264 auto it = w.assemblyState_->records.find(id);
265 if (it == w.assemblyState_->records.end())
266 return fail<BuildingAssembly>("House not found", DiagnosticCode::NotFound);
267 return Result<BuildingAssembly>::success(it->second);
268}
269Result<AssemblyHandle> AssemblyService::handle(const PlacementWorld& w, AssemblyId id) {
270 auto it = w.assemblyState_->handles.find(id);
271 if (it == w.assemblyState_->handles.end()) return fail<AssemblyHandle>("House not found", DiagnosticCode::NotFound);
272 return Result<AssemblyHandle>::success({it->second, w.assemblyState_->epoch});
273}
274Result<BuildingAssembly> AssemblyService::resolve(const PlacementWorld& w, AssemblyHandle h) {
275 if (h.ownerEpoch != w.assemblyState_->epoch)
276 return fail<BuildingAssembly>("Stale house handle", DiagnosticCode::Conflict);
277 for (const auto& [id, slot] : w.assemblyState_->handles)
278 if (slot == h.slot) return assembly(w, id);
279 return fail<BuildingAssembly>("Stale house slot", DiagnosticCode::NotFound);
280}
281std::optional<AssemblyId> AssemblyService::owner(const PlacementWorld& w, int member) {
282 for (const auto& [id, a] : w.assemblyState_->records)
283 for (const auto& [key, m] : a.members)
284 if (m == member) return id;
285 return std::nullopt;
286}
287std::vector<AssemblyId> AssemblyService::assemblies(const PlacementWorld& w) {
288 std::vector<AssemblyId> result;
289 for (const auto& [id, a] : w.assemblyState_->records) result.push_back(id);
290 return result;
291}
292} // namespace eve::building
double y
double m[16]
double x
Value::Object payload
float w
Definition AnimClip.cpp:738
eve::EntitySpatialPose pose
glm::vec4 p[6]
SQObjectPtr key
Definition ECS.cpp:155
std::array< double, 10 > q
std::int32_t second
std::int32_t c
int h
std::string local
std::string to
std::string from
std::string id
Poco::JSON::Object::Ptr result
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanGpuFrameToken token
glm::dvec3 origin
float t
std::string slot
std::unordered_map< std::uint32_t, std::uint32_t > remap
ScriptStructure out
std::string_view source
double current
Heightmap curve
float(ui::Theme::* member)[4]
std::map< std::string, std::span< const std::uint8_t > > members
std::size_t at
Move-only operation result carrying either a value or Status.
Definition Result.h:176
Process-local slot identity tagged by the registry that owns it.
std::map< std::string, Value > Object
Definition Value.h:34
格子型建筑放置世界(脚本可直接操作)。
Move-only proof of a fully validated house operation. @ownership Owns its candidate; destruction canc...
PreparedAssembly(PreparedAssembly &&) noexcept
Id128 public API.
Definition Identity.h:111
Value definitionsFor(const PlacementWorld &w)
Value definitionValue(const BuildingDefinition &d)
Result< void > checkDefinitions(const Value &value)
Result< void > checkGrid(const PlacementWorld &world)
Result< PlacedBuilding > transformPart(const PlacedBuilding &part, const PlacementWorld &world, AssemblyPose from, AssemblyPose to)
建筑放置模块入口:定义 / 放置世界 / 鬼影 / 变更事件的脚本绑定点。 设计文档:docs/dev/建筑放置系统设计.md
Definition Building.cpp:10
Integer grid-vertex origin, floor offset and quarter turns: (x,y) maps to (y,-x) for one turn.
Owning before/after domain states for exact, conflict-checked undo and redo.
Owning house membership; poses remain authoritative on the world instances.
Versioned house recipe; admission validates all fields before use. @ownership Owns local parts,...
一次成功放置变更的事件(供脚本 poll / C++ hook)。
std::string action
place / remove / move / rotate
Strong world-local identity of one authoritative edge-curve group.
World-owned authoritative description and membership of one committed edge curve.
已放置的建筑实例。
Owning curve group and all exact members, shared by runtime and editor persistence.