Pepsimulberry Technical Blog

website·Indexed 29 days ago

https://pepsimulberry.cn

A collection of technical guides and articles covering a variety of development topics, including Three.js performance optimization, Electron cross-platform desktop applications, MySQL database concepts, Sequelize, jQuery, and Husky.

Tokens
6.8K
Snippets
34
Records
43
Agent score
50%

What's inside Pepsimulberry

  1. Introduction to jQuery

    jQuery is a fast, small, and feature-rich JavaScript library providing core functionality for DOM manipulation, selectors, event handling, animation, and AJAX. When the jQuery library is executed, it adds a jquery function to the window object, typically accessed via the $ alias.

    Key characteristics:

    • Pros: Excellent cross-browser support (IE9+), reducing the need for browser-specific code.
    • Cons: The library size is relatively large (over 200kb since v1.5), it does not support component-based development, and it has limited capabilities for managing complex project architectures compared to modern frameworks.
  2. Overview of Electron Framework

    Electron is a framework used to build cross-platform desktop applications using standard web technologies: JavaScript, HTML, and CSS.
  3. Prevent memory leaks using the dispose method

    Three.js does not automatically release GPU resources. To avoid memory leaks and unnecessary rendering overhead, explicitly call the .dispose() method on geometries, materials, and textures when they are no longer needed.
  4. Optimize window resize events in Three.js

    When handling window resize events, update the camera aspect ratio, projection matrix, and renderer size. It is recommended to cap the pixel ratio to 2 to avoid excessive GPU load on high-DPI screens.
    window.addEventListener("resize", () => {
      // Update aspect ratio
      camera.aspect = window.innerWidth / window.innerHeight;
      // Update camera projection matrix
      camera.updateProjectionMatrix();
      // Update renderer size
      renderer.setSize(window.innerWidth, window.innerHeight);
      // Cap pixel ratio to 2 for performance
      renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
    });
  5. Compress glTF models using gltf-pipeline and Draco

    Use gltf-pipeline to compress glTF 3D models, which reduces file size and improves loading performance. This tool utilizes Google's Draco library to compress 3D mesh data. To use compressed models in Three.js, you must configure a DRACOLoader and pass it to the GLTFLoader.
    # Install gltf-pipeline globally
    npm install -g gltf-pipeline
    // Node.js script to compress a glTF file
    const fs = require('fs');
    const gltfPipeline = require('gltf-pipeline');
    
    const inputFilePath = 'path/to/your/input.gltf';
    const outputFilePath = 'path/to/your/output.gltf';
    const gltf = fs.readFileSync(inputFilePath);
    
    gltfPipeline.processGltf(gltf, { dracoOptions: { compressionLevel: 10 } })
      .then((results) => {
        fs.writeFileSync(outputFilePath, Buffer.from(results.gltf));
        console.log('Optimization complete.');
      });
  6. Implement Frustum Culling to reduce rendering load

    Frustum Culling is a technique that prevents the GPU from rendering objects that are outside the camera's field of view. In Three.js, this is controlled by the frustumCulled property on meshes. While it is enabled by default (true), you can ensure it is active across a complex scene by traversing the scene graph.
    // Ensure all meshes in the scene have frustum culling enabled
    scene.traverse((object) => {
      if (object instanceof THREE.Mesh) {
        object.frustumCulled = true;
      }
    });
  7. Implement conditional rendering to reduce GPU load

    By default, Three.js render loops run continuously, consuming GPU resources even when the scene is static. To optimize performance, implement a render switch (flag) that only enables rendering when necessary (e.g., during user interaction or animation updates) and disables it after a period of inactivity.
    let renderEnabled = false;
    let timeOut: number;
    
    const animate = () => {
      requestAnimationFrame(animate);
      
      // Only execute render and updates if enabled
      if (renderEnabled) {
        controls.update(clock.getDelta());
        renderer.render(scene, camera);
      }
      stats.update();
    };
    
    // Call this function to trigger rendering for a specific duration
    const timeRender = (time: number = 3000) => {
      renderEnabled = true;
      clearTimeout(timeOut);
      timeOut = setTimeout(() => {
        renderEnabled = false;
      }, time);
    };
    
    animate();
  8. Prerequisites for using Husky

    To use Husky in a project, the following conditions must be met:

    1. Git must be installed on the computer.
    2. The project must be a Git repository (containing a .git folder). If it is not, initialize it using git init.
  9. Configure EditorConfig for consistent coding styles

    EditorConfig helps maintain consistent coding styles across different IDEs. Create an .editorconfig file in the project root. For VS Code users, install the 'EditorConfig for VS Code' extension.
    root = true
    
    [*] # All files
    charset = utf-8
    indent_style = space
    indent_size = 2
    end_of_line = lf
    trim_trailing_whitespace = true
    insert_final_newline = true
    
    [*.md] # Markdown files
    max_line_length = off
    trim_trailing_whitespace = false
  10. Integrate ESLint with Prettier in Vue projects

    To prevent conflicts between ESLint and Prettier, install the necessary plugins and update the ESLint configuration to include Prettier rules.
    npm install eslint-plugin-prettier eslint-config-prettier -D
    // ESLint configuration extends array
    extends: [
      "plugin:vue/vue3-essential",
      "eslint:recommended",
      "@vue/typescript/recommended",
      "@vue/prettier",
      "@vue/prettier/@typescript-eslint",
      'plugin:prettier/recommended'
    ],
  11. Implement user authentication tokens with jsonwebtoken

    Tokens are unique identifiers generated by the backend to verify the identity of a specific user (e.g., distinguishing User A from User B). The jsonwebtoken library is commonly used to implement this functionality.
    npm install --save jsonwebtoken
  12. Optimize performance using BufferGeometry

    Use BufferGeometry instead of the traditional Geometry class to improve rendering performance, especially when handling large amounts of vertex data. BufferGeometry is more efficient because it stores vertex data in typed arrays (like Float32Array) and passes them directly to the GPU via WebGL buffers, reducing CPU overhead and memory consumption.