当前位置:网站首页>Three of three JS (WEB GL) model deletion / scene emptying / simple sorting of memory release
Three of three JS (WEB GL) model deletion / scene emptying / simple sorting of memory release
2022-04-23 05:19:00 【Xiankui xan】
Three And three.js (webgl) Deletion of model / The emptying of the scene / Memory release Simple arrangement of
Catalog
3、 ... and 、 The model in the scene group (mesh)
Four 、 Empty scene scene , Free memory
One 、 Brief introduction
Three js Some knowledge of development , It is convenient to encounter similar problems later , Be able to check and use in time .
This section describes , three.js (webgl) Deletion of model / The emptying of the scene / Memory release Simple arrangement of , For everyone to think about a direction of optimization , If there are shortcomings , Welcome to point out , Or you have a better way , Welcome to leave a message .
adopt Threejs Development Web3D When applied , You may need to delete model objects in the scene , If you want to start from a scene
Scene
Or group objectsGroup
Delete a 3D model object , It's not just.remove()
, Remember to·dispose()
.Developing 3D Scene time , If you need to dynamically add or delete models 、 scene , When the page is switched and re rendered , To avoid memory overlap , You need to manually clear the memory occupied by the scene , Avoid overflow and waste of resources .
Two 、 Realization principle
1、 General model remember , Right geometry and material Conduct dispose(), In the face of Model mesh Conduct remove()
2、 Empty scene scene , Free memory , The key points are as follows
- Use dispose() Clearing the vertex buffer of all mesh model geometry takes up memory
- Use object.clear() Destroy model objects , Clear page memory
- Pause requestAnimationFrame() Method , Avoid meaningless operation
- Empty canvas canvas , empty dom And related elements
3、 ... and 、 The model in the scene group (mesh)
1、 Delete objects in the scene Scene
A sub object Group
, And release the group object Group
The vertex buffer of all mesh model geometry in takes up memory
deleteObject(group) {
// Recursively traverse group objects group Free all memory occupied by the bound geometry of the descendant mesh model
group.traverse(function(obj) {
if (obj.type === 'Mesh') {
obj.geometry.dispose();
obj.material.dispose();
}
})
// Delete scene objects scene The children of group
scene.remove(group);
}
2、 Another way , eliminate Group
clearGroup(group) {
// Release Geometry and texture of material
const clearCache = (item) => {
item.geometry.dispose();
item.material.dispose();
};
// Recursively release... Under an object Geometry and texture of material
const removeObj = (obj) => {
let arr = obj.children.filter((x) => x);
arr.forEach((item) => {
if (item.children.length) {
removeObj(item);
} else {
clearCache(item);
item.clear();
}
});
obj.clear();
arr = null;
};
// remove group
removeObj(group);
}
Remember :
1) If it's in the scene
scene.remove(group); // Delete the group
2) If it is In the group
groups.remove(group);// Delete the model
Four 、 Empty scene scene , Free memory
// Empty scene , Include scene Animation in the scene , Sub object ,renderer,camera,control, And the variables you have used are left blank etc.
clearScene() {
cancelAnimationFrame(this.animationId);
this.scene.traverse((child) => {
if (child.material) {
child.material.dispose();
}
if (child.geometry) {
child.geometry.dispose();
}
child = null;
});
// The parameters in the scene are released, cleaned or left empty
this.sceneDomElement.innerHTML = '';
this.renderer.forceContextLoss();
this.renderer.dispose();
this.scene.clear();
this.flows = [];
this.scene = null;
this.camera = null;
this.controls = null;
this.renderer.domElement = null;
this.renderer = null;
this.sceneDomElement = null;
console.log('clearScene');
}
5、 ... and 、 Reference supplement :Three.js Memory release problem ( If not handled correctly , May not have released , It also takes up memory )
Refer to the post :Three.js Memory release problem
1、 Conventional methods cannot completely eliminate scene Some in the scene geometry、texture etc. , And even if the page leaves, it will not automatically free memory . Open Task Manager , You might see CPU Always occupied , It gets higher and higher when switching pages .
// Be careful : Release the scene here , Not necessary to deal with scene Of a sub object geometry 、material etc.
beforeDestroy() {
try {
scene.clear();
renderer.dispose();
renderer.forceContextLoss();
renderer.content = null;
cancelAnimationFrame(animationID) // Remove animationFrame
let gl = renderer.domElement.getContext("webgl");
gl && gl.getExtension("WEBGL_lose_context").loseContext();
}catch (e) {
console.log(e)
}
}
2、 There's a package here track Method , To manage the release of mesh、geometry、texture、object3D、 Externally loaded obj Model 、gltf Model, etc Release
1)TrackResource Method :
import * as THREE from 'three/build/three.module'
export default class ResourceTracker {
constructor() {
this.resources = new Set();
}
track(resource) {
if (!resource) {
return resource;
}
// handle children and when material is an array of materials or
// uniform is array of textures
if (Array.isArray(resource)) {
resource.forEach(resource => this.track(resource));
return resource;
}
if (resource.dispose || resource instanceof THREE.Object3D) {
this.resources.add(resource);
}
if (resource instanceof THREE.Object3D) {
this.track(resource.geometry);
this.track(resource.material);
this.track(resource.children);
} else if (resource instanceof THREE.Material) {
// We have to check if there are any textures on the material
for (const value of Object.values(resource)) {
if (value instanceof THREE.Texture) {
this.track(value);
}
}
// We also have to check if any uniforms reference textures or arrays of textures
if (resource.uniforms) {
for (const value of Object.values(resource.uniforms)) {
if (value) {
const uniformValue = value.value;
if (uniformValue instanceof THREE.Texture ||
Array.isArray(uniformValue)) {
this.track(uniformValue);
}
}
}
}
}
return resource;
}
untrack(resource) {
this.resources.delete(resource);
}
dispose() {
for (const resource of this.resources) {
if (resource instanceof THREE.Object3D) {
if (resource.parent) {
resource.parent.remove(resource);
}
}
if (resource.dispose) {
resource.dispose();
}
}
this.resources.clear();
}
}
2) introduce track, initialization
import ResourceTracker from "../../../common/3D/dispose";
// In the outer definition resMgr and track
let resMgr = new ResourceTracker();
const track = resMgr.track.bind(resMgr);
3) Will all mesh、geometry、texture、object3D、 Externally loaded obj Model 、gltf Models and so on need add to scene The object , Call it all track Method
let xxx = track(new Three.Vector3());
obj.geometry.computeBoundingBox();
obj.geometry.boundingBox.getCenter(center);
let wrapper = track(new Three.Object3D());
wrapper.position.set(center.x,center.y,center.z);
obj.position.set(-center.x,-center.y,-center.z);
wrapper.add(obj);
scene.add(wrapper);
return warpper;
4)track To the 3D Object memory release
beforeDestroy() {
try {
scene.clear();
resMgr && resMgr.dispose()
renderer.dispose();
renderer.forceContextLoss();
renderer.content = null;
cancelAnimationFrame(animationID)
let gl = renderer.domElement.getContext("webgl");
gl && gl.getExtension("WEBGL_lose_context").loseContext();
console.log(renderer.info) // see memery Field can be
}catch (e) {
console.log(e)
}
}
版权声明
本文为[Xiankui xan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230516339358.html
边栏推荐
- 项目经理值得一试的思维方式:项目成功方程式
- Simple application of parallel search set (red alarm)
- 5 minutes to understand MySQL row column conversion
- Asynchronous iterator & asynchronous generator & asynchronous context manager
- Detailed explanation of concurrent topics
- What are instruction cycles, machine cycles, and clock cycles?
- 《2021年IT行业项目管理调查报告》重磅发布!
- 学习笔记:Unity CustomSRP-10-Point and Spot Shadows
- 数据安全问题已成隐患,看vivo如何让“用户数据”重新披甲
- Good test data management, in the end how to do?
猜你喜欢
Backup MySQL database with Navicat
4 个最常见的自动化测试挑战及应对措施
MySQL foreign key constraint
What are the most popular recruitment technical skills in 2022? You can't think of it
The introduction of lean management needs to achieve these nine points in advance
了解 DevOps,必读这十本书!
Where, on when MySQL external connection is used
Discussion on flow restriction
When is it appropriate for automated testing? (bottom)
《2021年IT行业项目管理调查报告》重磅发布!
随机推荐
calendar. Pit point of getactualmaximum (calendar. Day_of_month)
4 个最常见的自动化测试挑战及应对措施
How to add beautiful code blocks in word | a very complete method to sort out and compare
At pgconf Asia Chinese technology forum, listen to Tencent cloud experts' in-depth understanding of database technology
MySQL realizes row to column SQL
学习笔记:Unity CustomSRP-13-ColorGrading
Machine learning - linear regression
How to exit VIM
Using MySQL with Oracle
开源规则引擎——ice:致力于解决灵活繁复的硬编码问题
App Store年交易额100万美元只缴15%佣金,中小开发者心里很矛盾
Mac enters MySQL terminal command
Study notes: unity customsrp-12-hdr
MySQL slow query
Restful toolkit of idea plug-in
Golang memory escape
Power consumption parameters of Jinbei household mute box series
Some experience in using MySQL / tidb database [slowly updating...]
Summary of MySQL knowledge points
Low code and no code considerations