diff --git a/AGENTS.md b/AGENTS.md index 9172f0139..d531c37a8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,7 +15,8 @@ ## 移植铁律 -- **OPFS 优先(用户铁律)。** 平台的工作过程——保存、重开、恢复、课程录制与自动测试——全部使用 OPFS;需要下载到本地时,必须由用户手动触发独立的“下载 .blend”入口,禁止在保存/编辑流程中自动下载。课程与测试不得依赖自动下载文件来重开工程。 +- **OPFS 优先(用户铁律)。** 平台的工作过程——保存、重开、恢复——全部使用 OPFS;需要下载到本地时,必须由用户手动触发独立的“下载 .blend”入口,禁止在保存/编辑流程中自动下载。 +- **全部落盘只用 OPFS,禁用 IDBFS/IndexedDB(用户铁律)。** Web Blender / Web FreeCAD 创建的一切文件与全部工作过程文件(场景、快照、渲染结果、渲染中间帧、导出、缓存、临时目录)一律写入 OPFS;`/browser` 等原生虚拟文件系统必须挂载 OPFS 后端,禁止使用 IDBFS 或 IndexedDB 作为持久化承载。**例外:课程录制与自动测试的产物不写入 OPFS**,仍按各自既有目录落盘。现状 `web/app/src/workers/web-engine.worker.ts` 的 `mountBrowserFS` 仍挂 `IDBFS`,属待改造缺口,按批次迁移到 OPFS。 - **验证前置条件优先。** 验证时,先准备前置条件,之后再验证;前置条件准备也必须考虑依赖关系和先后顺序,以提高验证的准确性和效率。按依赖顺序准备构件与资源、运行环境、服务与接口、数据与场景;前置条件不满足时先补齐,不重复运行依赖它的下游验证。复用仍有效的前置检查结果,环境或依赖变化后仅重新检查受影响项;如实记录缺项、失败及验证范围。 - **按合理的小批次推进。** 每批只处理一个明确业务缺口及其必要调用链;单次读源码≤30行、修改≤2文件且增删合计≤10行(含交接)。按实际字节控制提交提示、交接与工具输出,区分已统计内容与系统附加内容;断流/超量后缩小下一批,连续稳定交接后才有界放宽。达到预算先保留源码与continuationNotes(断点、已完成、残余、下一动作)再续接,禁止堆叠全量历史、盲目重发大包或靠删缺口缩量;不改变实现期禁止验证的规则。 - **当前工作定位:用户明确“桌面 Blender → Web Blender 移植”基本完成,后续仅以补充具体功能缺口为主,不得重新开展整体移植或偏离主线。科学、高效率地充分复用已有源码、模块、适配接口、WASM 和应用产物,使操作者能使用全面完整的功能。** diff --git a/blender-5.2.0/scripts/addons_core/io_scene_gltf2/io/com/library.py b/blender-5.2.0/scripts/addons_core/io_scene_gltf2/io/com/library.py index fcbfc6924..2e66b8395 100644 --- a/blender-5.2.0/scripts/addons_core/io_scene_gltf2/io/com/library.py +++ b/blender-5.2.0/scripts/addons_core/io_scene_gltf2/io/com/library.py @@ -45,5 +45,5 @@ def dll_exists(lib_name, lib_display_name) -> bool: print( 'ERROR', '{} is not available because library could not be found at %s'.format(lib_display_name) % - path.absolute()) + (path.absolute() if path is not None else '(unsupported platform)')) return exists diff --git a/blender-5.2.0/scripts/addons_core/io_scene_gltf2/io/exp/draco.py b/blender-5.2.0/scripts/addons_core/io_scene_gltf2/io/exp/draco.py index 7b3376562..e58bee1c6 100644 --- a/blender-5.2.0/scripts/addons_core/io_scene_gltf2/io/exp/draco.py +++ b/blender-5.2.0/scripts/addons_core/io_scene_gltf2/io/exp/draco.py @@ -2,7 +2,11 @@ # # SPDX-License-Identifier: Apache-2.0 -from ctypes import * +try: + from ctypes import * + _CTYPES_AVAILABLE = True +except ImportError: # Web/WASM builds omit the _ctypes extension. + _CTYPES_AVAILABLE = False from ...io.exp.binary_data import BinaryData from ...io.com.library import dll_path @@ -14,6 +18,9 @@ def encode_scene_primitives(scenes, export_settings): Moves position, normal and texture coordinate attributes into a Draco encoded buffer. """ + if not _CTYPES_AVAILABLE: + raise RuntimeError("Draco compression is unavailable in this build (no ctypes)") + # Load DLL and setup function signatures. dll = cdll.LoadLibrary(str(dll_path('bf_intern_draco_bridge', 'Draco').resolve())) diff --git a/blender-5.2.0/scripts/addons_core/io_scene_gltf2/io/exp/meshopt.py b/blender-5.2.0/scripts/addons_core/io_scene_gltf2/io/exp/meshopt.py index ee27cb879..ea32bec48 100644 --- a/blender-5.2.0/scripts/addons_core/io_scene_gltf2/io/exp/meshopt.py +++ b/blender-5.2.0/scripts/addons_core/io_scene_gltf2/io/exp/meshopt.py @@ -2,7 +2,11 @@ # # SPDX-License-Identifier: Apache-2.0 -import ctypes +try: + import ctypes + _CTYPES_AVAILABLE = True +except ImportError: # Web/WASM builds omit the _ctypes extension. + _CTYPES_AVAILABLE = False import numpy as np from ...io.com.library import dll_path @@ -36,6 +40,8 @@ class MeshoptEncoder: @staticmethod def load_library(export_settings): """Load the Meshopt encoder library.""" + if not _CTYPES_AVAILABLE: + raise RuntimeError("Meshopt compression is unavailable in this build (no ctypes)") if 'meshopt_encoder' in export_settings.keys(): return lib_path = MeshoptEncoder.find_library() diff --git a/blender-5.2.0/source/blender/web_engine/web_engine_api.cpp b/blender-5.2.0/source/blender/web_engine/web_engine_api.cpp index d00a66853..3dd9de7d1 100644 --- a/blender-5.2.0/source/blender/web_engine/web_engine_api.cpp +++ b/blender-5.2.0/source/blender/web_engine/web_engine_api.cpp @@ -810,9 +810,14 @@ struct EngineState { }; constexpr size_t kHistoryLimit = 64; +/* Full .blend buffers dominate the heap on imported scenes; cap the retained history by + * bytes so 64 entries cannot exhaust the WASM memory. */ +constexpr size_t kHistoryByteLimit = 256ull * 1024ull * 1024ull; const char *empty_scene_snapshot_json(); std::string scene_delta_json(const std::string &before_text, const std::string &after_text); +bool refresh_scene_from_main(EngineState &engine, json &snapshot, const std::string &active_object_id, + std::string &error, bool advance_revision); bool reset_python_before_main_replacement(EngineState &engine, std::string &error, bool preserve_namespace = false); void recover_pending_scene(EngineState &engine); @@ -829,6 +834,12 @@ void push_history(std::vector &history, HistoryEntry entry) if (web_engine_python_is_executing()) return; history.push_back(std::move(entry)); if (history.size() > kHistoryLimit) history.erase(history.begin()); + size_t total = 0; + for (const HistoryEntry &item : history) total += item.snapshot.size() + item.blend_bytes.size(); + while (history.size() > 1 && total > kHistoryByteLimit) { + total -= history.front().snapshot.size() + history.front().blend_bytes.size(); + history.erase(history.begin()); + } } bool capture_history_entry(const EngineState &engine, @@ -859,6 +870,26 @@ bool capture_history_entry(const EngineState &engine, entry.label = engine.history_label; entry.snapshot = engine.scene_snapshot.empty() ? std::string(empty_scene_snapshot_json()) : engine.scene_snapshot; + /* The entry is restored by reopening `blend_bytes`; embedded vertex/index arrays are + * redundant and multiply the heap by the history depth. Keep compact metadata only. */ + try { + json compact = json::parse(entry.snapshot); + if (compact.contains("meshes") && compact["meshes"].is_array()) { + for (json &mesh : compact["meshes"]) { + for (const char *field : {"positions", "indices", "normals", "triangleCornerIndices", "uvs", + "colors", "triangleMaterialIndices", "triangleFaceIndices", + "edgeVertexIndices", "tangents", "splitNormals", "sculptMask", "faceSets"}) { + mesh.erase(field); + } + mesh["geometryStatus"] = "summary-only"; + mesh.erase("geometryBufferId"); + } + } + entry.snapshot = compact.dump(); + } + catch (const std::exception &) { + /* Unparseable snapshots keep their original payload; capture still refuses below. */ + } entry.authoritative = engine.authoritative_commands && engine.authoritative_main != nullptr; entry.packed_assets = engine.packed_assets; if (capture_blend && engine.authoritative_main != nullptr && engine.authoritative_dirty) { @@ -1014,7 +1045,19 @@ bool restore_history_entry(EngineState &engine, engine.authoritative_dirty = false; engine.saved_blend_valid = false; engine.binary_revision = std::numeric_limits::max(); - engine.scene_snapshot = restored_snapshot; + /* History snapshots carry compact metadata; rebuild the published snapshot from the + * reopened Main so vertex/index data is never stored twice. */ + json refreshed_snapshot; + std::string refresh_error; + if (refresh_scene_from_main(engine, refreshed_snapshot, snapshot_active_object_id(snapshot), + refresh_error, advance_revision)) { + engine.scene_snapshot = refreshed_snapshot.dump(); + try { delta = scene_delta_json(previous_snapshot, engine.scene_snapshot); } + catch (const std::exception &) { /* keep the entry delta if the rebuild cannot diff */ } + } + else { + engine.scene_snapshot = restored_snapshot; + } engine.scene_refresh_pending = false; engine.packed_assets.swap(restored_assets); engine.scene_delta = std::move(delta); @@ -4714,7 +4757,10 @@ EMSCRIPTEN_KEEPALIVE int web_engine_call_json(const int handle, return write_json_result({{"ok", false}, {"cmd", cmd}, {"code", last_error_code}, {"error", last_error_message}}, result_data, result_length); } } - if ((format != "OBJ" && !(cmd == "importScene" && (format == "STL" || format == "PLY" || format == "GLB"))) || engine->authoritative_main == nullptr) { + const bool io_supported = cmd == "importScene" + ? (format == "OBJ" || format == "STL" || format == "PLY" || format == "GLB") + : (format == "OBJ" || format == "GLB"); + if (!io_supported || engine->authoritative_main == nullptr) { set_error(WEB_ENGINE_NOT_IMPLEMENTED, "IO_FORMAT_NATIVE_UNAVAILABLE: native Main IO is not available for this format"); return write_json_result({{"ok", false}, {"cmd", cmd}, {"code", last_error_code}, {"error", last_error_message}}, result_data, result_length); } diff --git a/blender-5.2.0/source/blender/web_engine/web_engine_blend_reader.cpp b/blender-5.2.0/source/blender/web_engine/web_engine_blend_reader.cpp index 99d26f775..00b923ed3 100644 --- a/blender-5.2.0/source/blender/web_engine/web_engine_blend_reader.cpp +++ b/blender-5.2.0/source/blender/web_engine/web_engine_blend_reader.cpp @@ -5972,6 +5972,26 @@ json scene_ir_from_blend(const ParsedBlend &blend, } } } + /* World rotation is not a World field: desktop rotates the environment + * with a Mapping node into the Environment Texture Vector input. */ + for (const ElementRef &link : linked_list_elements(blend, *node_tree, "links")) { + const std::optional from_node_pointer = read_pointer(*blend.sdna, link, "fromnode"); + const std::optional to_node_pointer = read_pointer(*blend.sdna, link, "tonode"); + const std::optional to_socket_pointer = read_pointer(*blend.sdna, link, "tosock"); + if (!from_node_pointer || !to_node_pointer || !to_socket_pointer) continue; + const std::optional from_node = element_for_pointer(blend, *from_node_pointer); + const std::optional to_node = element_for_pointer(blend, *to_node_pointer); + const std::optional to_socket = element_for_pointer(blend, *to_socket_pointer); + if (!from_node || !to_node || !to_socket) continue; + if (read_string(*blend.sdna, *to_node, "idname") != "ShaderNodeTexEnvironment" || + read_string(*blend.sdna, *to_socket, "name") != "Vector" || + read_string(*blend.sdna, *from_node, "idname") != "ShaderNodeMapping") continue; + for (const ElementRef &socket : linked_list_elements(blend, *from_node, "inputs")) { + if (read_string(*blend.sdna, socket, "name") != "Rotation") continue; + const std::vector values = node_socket_default_values(blend, socket); + if (values.size() >= 3 && std::isfinite(values[2])) world["environmentRotation"] = values[2]; + } + } } } worlds.push_back(std::move(world)); diff --git a/blender-5.2.0/source/blender/web_engine/web_engine_gpu_ui.cpp b/blender-5.2.0/source/blender/web_engine/web_engine_gpu_ui.cpp index dc031ee38..0117ae837 100644 --- a/blender-5.2.0/source/blender/web_engine/web_engine_gpu_ui.cpp +++ b/blender-5.2.0/source/blender/web_engine/web_engine_gpu_ui.cpp @@ -860,6 +860,31 @@ bool web_engine_gpu_ui_detach_prepare(const int handle, std::string &error) #endif } +bool web_engine_gpu_ui_render_context_enter(const int handle, void **r_previous) +{ +#ifdef __EMSCRIPTEN__ + const auto found = surfaces.find(handle); + if (found == surfaces.end()) return false; + auto &surface = found->second; + /* DrawManager::ContextShared captured GPU_context_active_get() while the WM + * canvas was being attached and enable() rejects any other context. Render + * operators run outside gpuFrame, so re-activate that same context. */ + if (!surface.wm_window || !surface.wm_window->runtime->gpuctx) return false; + *r_previous = static_cast(GPU_context_active_get()); + GPU_context_active_set(static_cast(surface.wm_window->runtime->gpuctx)); + return true; +#else + (void)handle; + (void)r_previous; + return false; +#endif +} + +void web_engine_gpu_ui_render_context_leave(void *previous) +{ + GPU_context_active_set(static_cast(previous)); +} + extern "C" void web_engine_gpu_ui_destroy(const int handle) { #ifdef __EMSCRIPTEN__ diff --git a/blender-5.2.0/source/blender/web_engine/web_engine_gpu_ui.hh b/blender-5.2.0/source/blender/web_engine/web_engine_gpu_ui.hh index 242536ccc..9b40a9a7b 100644 --- a/blender-5.2.0/source/blender/web_engine/web_engine_gpu_ui.hh +++ b/blender-5.2.0/source/blender/web_engine/web_engine_gpu_ui.hh @@ -33,6 +33,10 @@ bool web_engine_gpu_ui_invoke_default(int handle, const std::string &payload, std::string &error); bool web_engine_gpu_ui_detach_prepare(int handle, std::string &error); +/* Render operators dispatch compute on the canvas context that owns the WebGL + * resources; borrow it across the Python call and hand it back afterwards. */ +bool web_engine_gpu_ui_render_context_enter(int handle, void **r_previous); +void web_engine_gpu_ui_render_context_leave(void *previous); enum WebGPUUIEventType : int { WEB_GPU_UI_POINTER_MOVE = 1, diff --git a/blender-5.2.0/source/blender/web_engine/web_engine_main_state.cpp b/blender-5.2.0/source/blender/web_engine/web_engine_main_state.cpp index 784d1dc75..b27c7c4ba 100644 --- a/blender-5.2.0/source/blender/web_engine/web_engine_main_state.cpp +++ b/blender-5.2.0/source/blender/web_engine/web_engine_main_state.cpp @@ -10103,7 +10103,7 @@ bool web_engine_blend_main_merge_editor_snapshot(WebBlendMainState *state, try { json snapshot = json::parse(snapshot_json); if (snapshot.contains("worlds")) for (json &entry : snapshot["worlds"]) { - entry["environmentStrength"] = nullptr; entry["environmentImageId"] = nullptr; + entry["environmentStrength"] = nullptr; entry["environmentImageId"] = nullptr; entry["environmentRotation"] = nullptr; World *world = reinterpret_cast(find_source_data(state->main->worlds, "world:", entry.value("id", "").c_str())); bNodeSocket *strength = web_world_surface_socket(world, state->scene, "Strength"); if (strength && strength->type == SOCK_FLOAT && strength->default_value && strength->logically_linked_sockets().is_empty()) { @@ -10116,6 +10116,16 @@ bool web_engine_blend_main_merge_editor_snapshot(WebBlendMainState *state, if (texture.type_legacy != SH_NODE_TEX_ENVIRONMENT || (texture.flag & NODE_MUTED) || !texture.id || GS(texture.id->name) != ID_IM) continue; const std::string image_id = source_data_id("image:", *texture.id); if (!image_id.empty()) entry["environmentImageId"] = image_id; + const bNodeSocket *vector = bke::node_find_socket(texture, SOCK_IN, UString("Vector")); + if (vector && vector->logically_linked_sockets().size() == 1) { + const bNode &mapping = vector->logically_linked_sockets()[0]->owner_node(); + const bNodeSocket *rotation = mapping.type_legacy == SH_NODE_MAPPING && !(mapping.flag & NODE_MUTED) + ? bke::node_find_socket(mapping, SOCK_IN, UString("Rotation")) : nullptr; + if (rotation && rotation->type == SOCK_VECTOR && rotation->default_value && rotation->logically_linked_sockets().is_empty()) { + const float value = static_cast(rotation->default_value)->value[2]; + if (std::isfinite(value)) entry["environmentRotation"] = value; + } + } } // Build both directions together, even when there is no editor workspace. // Rebuilt on open, refresh and history restore; commit only a complete merge. @@ -17972,14 +17982,11 @@ bool web_engine_blend_main_set_origin(WebBlendMainState *state, error = "SHARED_MESH_MUTATION_BLOCKED: make mesh data single-user before changing origin"; return false; } - float3 minimum(FLT_MAX), maximum(-FLT_MAX); - for (const float3 &position : mesh->vert_positions()) { - for (int axis = 0; axis < 3; axis++) { - minimum[axis] = std::min(minimum[axis], position[axis]); - maximum[axis] = std::max(maximum[axis], position[axis]); - } - } - const float3 center = (minimum + maximum) * 0.5f; + /* Desktop ORIGIN_TO_GEOMETRY with V3D_AROUND_CENTER_MEDIAN uses the arithmetic mean of the + * vertex positions (editors/object/object_transform.cc), not the bounding-box center. */ + float3 center(0.0f); + for (const float3 &position : mesh->vert_positions()) center += position; + center /= float(mesh->vert_positions().size()); MutableSpan positions = mesh->vert_positions_for_write(); for (float3 &position : positions) position -= center; float basis[3][3], world_offset[3]; @@ -22070,6 +22077,126 @@ bool web_engine_blend_main_set_world_environment_strength(WebBlendMainState *sta return true; } +bool web_engine_blend_main_set_world_environment_image(WebBlendMainState *state, + const char *target_id, + const char *image_id, + std::string &error) +{ + if (state == nullptr || state->main == nullptr || target_id == nullptr) { + error = "RENDER_PROPERTY_INVALID: world environment target is missing"; + return false; + } + World *world = find_world(state->main, target_id); + if (world == nullptr || world->id.lib != nullptr || !BKE_id_is_editable(state->main, &world->id)) { + error = "LINKED_DATA_MUTATION_BLOCKED: World is not editable"; + return false; + } + /* Desktop World > Surface is a Background node; the environment image is an + * Environment Texture node linked into its Color input. */ + if (world->nodetree == nullptr) { + world->nodetree = bke::node_tree_add_tree_embedded(nullptr, &world->id, "Shader Nodetree", "ShaderNodeTree"); + } + bNodeTree *tree = world->nodetree; + if (tree == nullptr) { + error = "RENDER_PROPERTY_INVALID: World shader nodetree is unavailable"; + return false; + } + bNode *background = find_node(tree, SH_NODE_BACKGROUND); + if (background == nullptr) background = bke::node_add_static_node(nullptr, *tree, SH_NODE_BACKGROUND); + bNode *output = find_node(tree, SH_NODE_OUTPUT_WORLD); + if (output == nullptr) output = bke::node_add_static_node(nullptr, *tree, SH_NODE_OUTPUT_WORLD); + bNodeSocket *surface_out = background ? bke::node_find_socket(*background, SOCK_OUT, UString("Background")) : nullptr; + bNodeSocket *surface_in = output ? bke::node_find_socket(*output, SOCK_IN, UString("Surface")) : nullptr; + bNodeSocket *color = background ? bke::node_find_socket(*background, SOCK_IN, UString("Color")) : nullptr; + if (surface_out == nullptr || surface_in == nullptr || color == nullptr) { + error = "RENDER_PROPERTY_INVALID: World Surface nodes are unavailable"; + return false; + } + if (surface_in->link == nullptr) bke::node_add_link(*tree, *background, *surface_out, *output, *surface_in); + while (color->link != nullptr) bke::node_remove_link(tree, *color->link); + if (image_id != nullptr && image_id[0] != '\0') { + Image *image = find_image(state->main, image_id); + if (image == nullptr) { + error = "RENDER_PROPERTY_INVALID: world environment image not found"; + return false; + } + if (image->id.lib != nullptr) { + error = "LINKED_DATA_MUTATION_BLOCKED: Image is linked"; + return false; + } + bNode *texture = find_node(tree, SH_NODE_TEX_ENVIRONMENT); + if (texture == nullptr) texture = bke::node_add_static_node(nullptr, *tree, SH_NODE_TEX_ENVIRONMENT); + if (texture == nullptr) { + error = "RENDER_PROPERTY_INVALID: Environment Texture node is unavailable"; + return false; + } + if (texture->id != &image->id) { + if (texture->id != nullptr) id_us_min(texture->id); + texture->id = &image->id; + id_us_plus(&image->id); + } + if (auto *tex = static_cast(texture->storage)) { + tex->projection = SHD_PROJ_EQUIRECTANGULAR; + tex->interpolation = SHD_INTERP_LINEAR; + } + bNodeSocket *texture_out = bke::node_find_socket(*texture, SOCK_OUT, UString("Color")); + if (texture_out == nullptr) { + error = "RENDER_PROPERTY_INVALID: Environment Texture output is unavailable"; + return false; + } + bke::node_add_link(*tree, *texture, *texture_out, *background, *color); + } + tree->ensure_topology_cache(); + BKE_ntree_update_after_single_tree_change(*state->main, *tree); + tree->id.recalc |= ID_RECALC_NTREE_OUTPUT; + world->id.recalc |= ID_RECALC_PARAMETERS; + return true; +} + +bool web_engine_blend_main_set_world_environment_rotation(WebBlendMainState *state, + const char *target_id, + const float radians, + std::string &error) +{ + if (state == nullptr || state->main == nullptr || target_id == nullptr) { + error = "RENDER_PROPERTY_INVALID: world environment target is missing"; + return false; + } + World *world = find_world(state->main, target_id); + if (world == nullptr || world->id.lib != nullptr || !BKE_id_is_editable(state->main, &world->id)) { + error = "LINKED_DATA_MUTATION_BLOCKED: World is not editable"; + return false; + } + if (!std::isfinite(radians) || std::abs(radians) > 1.0e9f) { + error = "RENDER_PROPERTY_INVALID: world environment rotation is outside the bounded range"; + return false; + } + bNodeTree *tree = world->nodetree; + bNode *texture = find_node(tree, SH_NODE_TEX_ENVIRONMENT); + if (texture == nullptr || texture->id == nullptr) { + /* Desktop rotates an environment image; without one there is nothing to aim. */ + error = "RENDER_PROPERTY_INVALID: set a world environment image before rotating it"; + return false; + } + bNode *mapping = find_node(tree, SH_NODE_MAPPING); + if (mapping == nullptr) mapping = bke::node_add_static_node(nullptr, *tree, SH_NODE_MAPPING); + bNodeSocket *rotation = mapping ? bke::node_find_socket(*mapping, SOCK_IN, UString("Rotation")) : nullptr; + bNodeSocket *vector_out = mapping ? bke::node_find_socket(*mapping, SOCK_OUT, UString("Vector")) : nullptr; + bNodeSocket *vector_in = bke::node_find_socket(*texture, SOCK_IN, UString("Vector")); + if (rotation == nullptr || vector_out == nullptr || vector_in == nullptr) { + error = "RENDER_PROPERTY_INVALID: World environment mapping nodes are unavailable"; + return false; + } + while (rotation->link != nullptr) bke::node_remove_link(tree, *rotation->link); + if (auto *value = static_cast(rotation->default_value)) value->value[2] = radians; + if (vector_in->link == nullptr) bke::node_add_link(*tree, *mapping, *vector_out, *texture, *vector_in); + tree->ensure_topology_cache(); + BKE_ntree_update_after_single_tree_change(*state->main, *tree); + tree->id.recalc |= ID_RECALC_NTREE_OUTPUT; + world->id.recalc |= ID_RECALC_PARAMETERS; + return true; +} + bool web_engine_blend_main_set_camera_focus_object(WebBlendMainState *state, const char *target_id, const char *focus_object_id, @@ -22471,7 +22598,7 @@ bool web_engine_blend_main_set_render_properties(WebBlendMainState *state, if (strncmp(target_id, "world:", 6) == 0) { World *world = find_world(state->main, target_id); if (world == nullptr || world->id.lib != nullptr || - !reject_unknown({"color", "exposure", "environmentStrength", "ambientOcclusionDistance", "ambientOcclusionEnergy", "sunThreshold", "sunAngle", "sunShadowMaximumResolution", "sunShadowJitterOverblur", "sunShadowFilterRadius", "probeResolution", "useSunShadow", "useSunShadowJitter", "mist"}) || + !reject_unknown({"color", "exposure", "environmentStrength", "environmentImageId", "environmentRotation", "ambientOcclusionDistance", "ambientOcclusionEnergy", "sunThreshold", "sunAngle", "sunShadowMaximumResolution", "sunShadowJitterOverblur", "sunShadowFilterRadius", "probeResolution", "useSunShadow", "useSunShadowJitter", "mist"}) || !read_color("color", &world->horr) || !read_float("exposure", -20.0f, 20.0f, world->exposure)) { @@ -22525,6 +22652,22 @@ bool web_engine_blend_main_set_render_properties(WebBlendMainState *state, } if (!web_engine_blend_main_set_world_environment_strength(state, target_id, properties["environmentStrength"].get(), error)) return false; } + if (properties.contains("environmentImageId")) { + if (!properties["environmentImageId"].is_null() && !properties["environmentImageId"].is_string()) { + error = "RENDER_PROPERTY_INVALID: environmentImageId must be a string or null"; + return false; + } + const std::string environment_image_id = properties["environmentImageId"].is_string() + ? properties["environmentImageId"].get() : std::string(); + if (!web_engine_blend_main_set_world_environment_image(state, target_id, environment_image_id.c_str(), error)) return false; + } + if (properties.contains("environmentRotation")) { + if (!properties["environmentRotation"].is_number()) { + error = "RENDER_PROPERTY_INVALID: environmentRotation must be numeric"; + return false; + } + if (!web_engine_blend_main_set_world_environment_rotation(state, target_id, properties["environmentRotation"].get(), error)) return false; + } if (properties.contains("mist")) { const json &mist = properties["mist"]; if (!mist.is_object() || mist.empty()) { @@ -25460,6 +25603,22 @@ bool web_engine_blend_main_obj_io(WebBlendMainState *state, PLYImportParams params{}; STRNCPY(params.filepath, filename.c_str()); params.reports = &reports.value; PLY_import(context.get(), params); } + else if (!importing && std::strcmp(format, "GLB") == 0) { + /* Native glTF export: the desktop add-on writes the binary next to the staged scratch file; + * the caller receives it base64-encoded because the result travels as a JSON string. */ + CTX_wm_area_set(context.get(), nullptr); + CTX_wm_region_set(context.get(), nullptr); + WebEnginePythonUIScope python_scope(handle, state, context.get(), true); + const char *imports[] = {"bpy", nullptr}; + const std::string script = "if bpy.ops.export_scene.gltf(filepath=" + nlohmann::json(filename).dump() + + ", export_format='GLB', use_selection=False) != {'FINISHED'}: raise RuntimeError('GLTF_EXPORT_CANCELLED')"; + const bool exported = BPY_run_string_exec(context.get(), imports, script.c_str()); + python_scope.finish_callbacks(); + if (!exported) { + error = "IO_FORMAT_OUTPUT_INVALID: native glTF export failed"; + return false; + } + } else if (importing) { OBJImportParams params{}; STRNCPY(params.filepath, filename.c_str()); @@ -25483,11 +25642,13 @@ bool web_engine_blend_main_obj_io(WebBlendMainState *state, } if (!importing) { std::ifstream stream(filename, std::ios::binary); - output.assign(std::istreambuf_iterator(stream), std::istreambuf_iterator()); - if (output.empty() || output.size() > 64u * 1024u * 1024u) { - error = "IO_FORMAT_OUTPUT_INVALID: empty or oversized OBJ"; + const std::vector bytes((std::istreambuf_iterator(stream)), std::istreambuf_iterator()); + if (bytes.empty() || bytes.size() > 64u * 1024u * 1024u) { + error = "IO_FORMAT_OUTPUT_INVALID: empty or oversized export payload"; return false; } + if (std::strcmp(format, "GLB") == 0) output = encode_base64_rgba(bytes); + else output.assign(bytes.begin(), bytes.end()); } return true; } diff --git a/blender-5.2.0/source/blender/web_engine/web_engine_main_state.h b/blender-5.2.0/source/blender/web_engine/web_engine_main_state.h index 415b4530f..f186b2cfb 100644 --- a/blender-5.2.0/source/blender/web_engine/web_engine_main_state.h +++ b/blender-5.2.0/source/blender/web_engine/web_engine_main_state.h @@ -927,6 +927,14 @@ bool web_engine_blend_main_set_world_environment_strength(WebBlendMainState *sta const char *target_id, float strength, std::string &error); +bool web_engine_blend_main_set_world_environment_image(WebBlendMainState *state, + const char *target_id, + const char *image_id, + std::string &error); +bool web_engine_blend_main_set_world_environment_rotation(WebBlendMainState *state, + const char *target_id, + float radians, + std::string &error); bool web_engine_blend_main_set_camera_focus_object(WebBlendMainState *state, const char *target_id, const char *focus_object_id, diff --git a/blender-5.2.0/source/blender/web_engine/web_engine_python.cpp b/blender-5.2.0/source/blender/web_engine/web_engine_python.cpp index d04185c5e..2b48a8ee4 100644 --- a/blender-5.2.0/source/blender/web_engine/web_engine_python.cpp +++ b/blender-5.2.0/source/blender/web_engine/web_engine_python.cpp @@ -7,6 +7,7 @@ #endif #include #include "web_engine_python.hh" +#include "web_engine_gpu_ui.hh" #include "web_engine_api.h" #include "web_engine_main_state.h" #include "web_engine_python_source.hh" @@ -1784,11 +1785,21 @@ std::string web_engine_python_execute(int handle, if (!session) { PyErr_Print(); throw std::runtime_error("PYTHON_SESSION_FAILED"); } sessions[handle] = session; } + /* Render operators dispatch compute and read back through the WM canvas + * context. Without re-activating it DrawManager::ContextShared::enable() + * rejects the call while gpuFrame is not running. */ + void *previous_gpu = nullptr; + const bool borrow_gpu = render_task && web_engine_gpu_ui_render_context_enter(handle, &previous_gpu); PyObject *result; - { + try { PythonTraceScope trace_scope; result = PyObject_CallFunction(PyDict_GetItemString(bootstrap, "execute"), "OssO", sessions[handle], source.c_str(), filename.c_str(), params.value("console", true) ? Py_True : Py_False); } + catch (...) { + if (borrow_gpu) web_engine_gpu_ui_render_context_leave(previous_gpu); + throw; + } + if (borrow_gpu) web_engine_gpu_ui_render_context_leave(previous_gpu); std::string state = "ERROR"; if (result && PyUnicode_Check(result)) { const char *value = PyUnicode_AsUTF8(result); diff --git a/blender-5.2.0/source/blender/web_engine/web_engine_python_bootstrap.py b/blender-5.2.0/source/blender/web_engine/web_engine_python_bootstrap.py index 1757ce62e..0aae255dd 100644 --- a/blender-5.2.0/source/blender/web_engine/web_engine_python_bootstrap.py +++ b/blender-5.2.0/source/blender/web_engine/web_engine_python_bootstrap.py @@ -29,8 +29,19 @@ def _ensure_web_addons(): if addons_path not in sys.path: sys.path.append(addons_path) import importlib + import os try: - importlib.import_module('io_mesh_uv_layout').register() + mod = importlib.import_module('io_mesh_uv_layout') + # Registration belongs to `addon_utils.enable()` in the one-shot startup + # pass. Registering here would place UV_OT_export_layout outside the + # startup transaction, and enable() then has no branch that works inside + # it: it cannot unregister the previous class + # (PYTHON_STARTUP_CANNOT_REPLACE_EXISTING_TYPE), cannot reload onto it + # (PYTHON_RNA_TYPE_OWNED_BY_OTHER_MAIN), and the emscripten handle_error + # hook turns either failure into a latched startup failure. Only seed + # `__time__` so enable() takes its plain import-then-register path + # instead of deciding the add-on changed on disk. + mod.__time__ = os.path.getmtime(mod.__file__) _web_addons_registered = True except Exception: # bpy may not be ready yet; a later session/catalog call retries. diff --git a/blender-5.2.0/source/blender/windowmanager/intern/wm_jobs.cc b/blender-5.2.0/source/blender/windowmanager/intern/wm_jobs.cc index 8d6cdb030..737eb6b58 100644 --- a/blender-5.2.0/source/blender/windowmanager/intern/wm_jobs.cc +++ b/blender-5.2.0/source/blender/windowmanager/intern/wm_jobs.cc @@ -529,7 +529,17 @@ void WM_jobs_start(wmWindowManager *wm, wmJob *wm_job) // printf("job started: %s\n", wm_job->name); BLI_threadpool_init(&wm_job->threads, do_job_thread, 1); +#ifdef __EMSCRIPTEN__ + /* The web build has no pthread support: `pthread_create` returns ENOSYS + * (musl pthread_create.c: `if (!libc.can_do_threads) return ENOSYS;`) and + * `BLI_threadpool_insert` ignores that result, so the slot stays busy, the + * worker never runs and `wm_job->ready` stays false -- the job hangs forever. + * Run the worker body on the invoking thread instead. The slot is left + * available so `BLI_threadpool_end` has nothing to join. */ + (void)do_job_thread(wm_job); +#else BLI_threadpool_insert(&wm_job->threads, wm_job); +#endif } /* Restarted job has timer already. */ diff --git a/docs/status/RENDER_BASICS_20261119.md b/docs/status/RENDER_BASICS_20261119.md new file mode 100644 index 000000000..7718e23ab --- /dev/null +++ b/docs/status/RENDER_BASICS_20261119.md @@ -0,0 +1,161 @@ +# 渲染入门教程(四条通路实走)— 2026-11-19 + +## 任务 + +以有头 Chromium 驱动 Web Blender 的真实界面,把四条渲染通路各实走一遍,产出面向初学者的 HTML 教程; +过程中遇到的缺口当场修补(功能缺口用本机桌面 Blender 源码,UI 缺口用 React 组件)。 + +## 已产出 + +| 产物 | 路径 | +| --- | --- | +| 教程正文 | `web/app/public/tutorial/render-basics/index.html` | +| 补充样式 | `web/app/public/tutorial/render-basics/basics.css` | +| 界面截图(11 张,1600×900) | `web/app/public/tutorial/render-basics/steps/` | +| 成片原件(7 张 PNG) | `web/app/public/tutorial/render-basics/evidence/`:`pbr-512`、`native-blender_eevee`、`native-blender_workbench`、`native-cycles`、`wasm-f12-scene`(空帧,用作缺口证据)、`wasm-blender_eevee`(空帧)、`wasm-blender_workbench` | +| 有头采集器 | `tools/web/capture-render-basics.mjs` | +| 门禁 | `tools/web/check-render-basics.mjs` | +| 采集报告 | `tests/golden/RENDER-BASICS-001/capture-report.json` | +| 门禁报告 | `tests/golden/RENDER-BASICS-001/check-report.json` | + +复现: + +```bash +cd web && BLENDER_BIN=/home/mes123456/workinf_Blender_Wasm/build_blender_native/bin/blender \ + npm run dev -- --host 127.0.0.1 --port 5184 --strictPort +DISPLAY=:1 node tools/web/capture-render-basics.mjs --port 5184 --gpu hardware +node tools/web/check-render-basics.mjs +``` + +## 本轮实走结果(2026-11-19 采集,端口 5186,硬件 GPU) + +| 通路 | 结果 | +| --- | --- | +| 一 · 视口实时预览 | 着色模式循环 线框→实体→材质→渲染,截 2 张,无产物 | +| 二 · 浏览器 PBR | 512×512,696 ms,100 365 B,`opaqueRatio 1` | +| 三 · 服务端 Blender | EEVEE 50.7 s / 963 KB、Workbench 6.3 s / 929 KB、Cycles 50.9 s / 1.0 MB,三者 `opaqueRatio 1` | +| 四 · 页内 WASM | F12 1.4 s 出图;**Workbench 正常(`opaqueRatio 1`)** | + +`capture-report.json` 的 `status` 为 `PASS`,11 步相邻截图 sha256 互不相同(`duplicateScreenshots: []`)。 + +## 本批修补的缺口 + +### 1. Render Result 编辑区是空白占位(UI 缺口,已修) + +桌面 Blender 渲完会把结果挂进 Image Editor;Web 侧这个区域只画棋盘格,初学者无法把"按了渲染"和 +"屏幕上的图"对应起来。 + +- 新增 `web/app/src/app/RenderResultView.tsx`:显示最近一次结果(原生帧优先于 PBR 结果),带 + 文件名 / 尺寸 / 体积、`1:1` / `适应窗口` 切换、`下载` 链接(手动触发,不自动下载)。 +- 接线:`App.tsx` 的 `Render Result` 编辑器分支与 `.render-result-area`。 +- 样式:`app-shell.css` 追加 `.render-result-*` 规则。 + +**未验证**:只在此次采集的场景/尺寸下实走;其它工作区、自定义布局、`?ui=desktop` 流式模式未复测。 + +### 2. 浮动快捷操作栏压住新工具栏(UI 缺口,已修) + +`.legacy-quick-toolbar` 默认开启(`interface.quickTools`),`position:absolute; top:100%` 悬浮在 +每个区域顶部 35 px。第一次采集的 `06-render-result-editor.jpg` 里,工具条的盒子在 y 58–83,但 +该处实际绘制的是快捷栏的 `Add CUBE…` 按钮,工具条整个被盖住——截图与图注不符。 + +- 修法:`app-shell.css` 加一条 `.blender-app[data-quick-tools="true"] .render-result-view { padding-top: 35px; }`。 +- 复测:工具条落到 y 93,截图中可见(`PBR 512×512 · 512×512 · 适应窗口 · 下载`)。 + +**遗留**:其它区域(视口左上角、Outliner 顶部等)是否也被遮住未逐区核查;本次只修了本教程用到的区域。 + +## 未修复的真实缺口(用户可见) + +### 页内 WASM 通路:Eevee / Scene 输出全透明帧 + +- 现象:`/`(不带参数)按 F12,或把 Engine 换成 `BLENDER_EEVEE`,状态行照常 `SUCCEEDED`, + 产出 1024×1024 PNG 224 560 B,但**每个像素 alpha 都是 0**(`maxAlpha 0`,`opaqueRatio 0`)。 +- 对照:同一通路 `BLENDER_WORKBENCH` 1.4 s 出正常图(921 322 B,`opaqueRatio 1`)。 +- 历史证据问题:`tests/golden/RENDER-PATHS-001/wasm-embedded/wasm-embedded-still.png` 像素与本次 + 空帧完全一致(同样全 0),说明当年那条 "PASS" 只按文件体积判定,没有验证图像内容。 +- 相关环境观测:该 Chromium 里 `navigator.gpu` 可用但 adapter 报 `google swiftshader`(软件适配器); + GPU/WASM 侧的 WebGL compute 通路经 `Module.webGPUComputeCapabilities` 桥接,该对象不在 + `globalThis` 上。**未证明**与此透明帧相关,仅记录为线索。 +- 源码落点(下一动作):`blender-5.2.0/source/blender/web_engine/web_engine_python.cpp` 的 + `render_task`(借用 GPU context 后取像素)与 `blender-5.2.0/source/blender/gpu/webgl/webgl_backend.cc` + 的 compute 上限声明。先确认 Eevee 在该后端是否走了 compute/光栅回读,再看 alpha 通道是否丢失。 + +#### 2026-11-20 追加:已定位到着色器编译失败(不是空帧 / 不是 alpha 丢失) + +1. **先排除了“只丢 alpha”**:解码 `wasm-f12-scene.png` 的完整 RGBA,alpha 全 0,但 RGB 也有值—— + 最大值仅为 **1**(86 004 个像素值为 1,其余为 0)。这是抖动噪声,不是被 alpha 遮住的正常画面。 + 即引擎确实什么都没画出来。 +2. **EEVEE 已编进 WASM**:`web_engine.wasm` 中 `BLENDER_EEVEE` / `BLENDER_EEVEE_NEXT` / + `BLENDER_WORKBENCH` 三个引擎名都在,Workbench 同一次采集正常出图。所以不是缺引擎,而是运行时失败。 +3. **实测浏览器控制台(有头 Chromium,`/` 默认地址,按 F12)**,EEVEE 的光栅着色器全部编译失败: + + ``` + Blender WebGL shader MADefault_Surface_depth_mesh: ERROR: 0:5941: + '=' : cannot convert from 'const int' to 'highp uint' + Blender WebGL shader MADefault_Surface_depth_mesh: ERROR: + '=' : assigning non-constant to 'const structure 'ViewMatrices'' + Blender WebGL shader MADefault_Surface_depth_velocity_mesh: unsupported storage + buffer other than supported read-only native layouts + (另:'no_processing' / 'pack' : unrecognized pragma) + ``` + + 受影响的是 EEVEE 的材质延迟管线:`Surface_depth` / `Surface_depth_velocity` / + `Surface_deferred` / `Surface_shadow`。WebGL 后端出的是 `#version 300 es` + (`webgl_shader.cc:2075`),而这批 BSL 着色器用到了 GLSL ES 3.00 不接受的写法: + 常量转换为 `uint`、非 const 值赋给 `const` 结构体、以及非只读 storage buffer。 + 着色器编译失败 → 管线没有可用的程序 → 帧缓冲保持清屏值 → 输出全 0。 + +**结论:这是 WebGL 后端的 EEVEE 着色器移植缺口,不是一处小 bug。** 修它需要在 +`blender-5.2.0/source/blender/gpu/webgl/webgl_shader.cc` 里为 EEVEE 的延迟管线做一整套 +ES 3.00 降级(storage buffer → 只读 native layout、const 结构体赋值展开、uint 字面量改写), +属于独立的大批次,**未在本轮实施**。仅去掉 pragma 警告不会改变结果,因此没有做这种“看起来修了”的改动。 + +**用户可用的规避**(已写进教程):页内 WASM 通路把 Engine 换成 Workbench;或改用 `?ui=web` +走服务端原生 Blender。 + + +教程页已在正文与「本页限制」两处显著标注该缺口,并给出"改用 Workbench"的可用规避。 + +## 工具沉淀(2026-11-20) + +本次排查用到的程序已整理成通用工具,索引见 `tools/web/README-render-tools.md`: + +| 新工具 | 从哪来 | +| --- | --- | +| `tools/web/lib/image-stats.mjs` | `capture-render-basics.mjs` 里内联的 PNG 解码(行过滤器还原 + alpha 统计)抽出为共用库,另加 RGB 统计、JPEG 尺寸、verdict | +| `tools/web/inspect-image.mjs` | 新增命令行:对任意图片/目录判「有没有画面」,空帧退出码 2 | +| `tools/web/probe-web-engine.mjs` | 合并 `probe-wasm-engines.mjs`(逐引擎出图)与 `probe-wasm-eevee-console.mjs`(抓控制台),补 warm-up 阶段着色器错误捕获、`--path server` 分支 | +| `tools/web/probe-ui-paint.mjs` | 新增:判定元素是没渲染还是被盖住(快捷操作栏那次的排查手法) | + +`capture-render-basics.mjs` 与 `check-render-basics.mjs` 已改为引用共用库,删掉重复的哈希与解码实现。 + +实测(2026-11-20,端口 5186): + +- `inspect-image`:7 张成片中 5 张 `picture`、2 张 `transparent`(页内 WASM 空帧),退出码 2,符合预期。 +- `probe-web-engine --path wasm`:SCENE/EEVEE `BLANK`、WORKBENCH `PASS`,并输出 `MADefault_Surface_*` 着色器编译错误。 +- `probe-web-engine --path server`:Workbench `PASS`,4.4 s。 +- `probe-ui-paint`:`[data-testid="render-result-view"]` 在 `?ui=web` + Rendering 工作区 + PBR 渲染后,`covered at top: false`,与修复后的截图一致。 + +## 门禁 + +`node tools/web/check-render-basics.mjs` → `PASS 11 steps, 3 server engines, embedded gap recorded`。 + +断言:report 为 PASS;11 张截图的文件存在且 sha256 与报告一致;相邻截图互不相同;三条服务端引擎 +与 PBR 产物像素不透明(`opaqueRatio > 0.5`);页内 EEVEE 空帧**必须仍被记录为全透明**(修好后该断言 +会失败并提醒更新教程文案);页面无 `