MineRender

repository·master·Indexed 41 days ago

https://github.com/inventivetalentdev/minerender

A tool for generating interactive 2D and 3D renders of Minecraft environments, entities, models, and GUIs. Version 1.4.13 provides specialized renderers including EntityRender for 3D entities, GuiRender for UI elements, ModelRender for blocks and items, and CombinedRender for composing multiple elements into a single scene using Three.js.

Tokens
9.9K
Snippets
32
Records
34
Agent score
99%

What's inside MineRender

  1. Initialize ModelRender for Minecraft models

    master

    The ModelRender class is used to render Minecraft models (blocks and items) in a 3D or 2D environment. It extends a base Render class and manages the lifecycle of model parsing, texture loading, and instanced rendering.

    Constructor Options

    When instantiating ModelRender, you can provide an options object with the following properties:

    • type (string): Specifies the model type, either 'block' or 'item'. Defaults to 'block'.
    • centerCubes (boolean): If true, centers the cube's rotation point. Defaults to false.
    • assetRoot (string): The root directory used to fetch asset files. Defaults to DEFAULT_ROOT.
    • useWebWorkers (boolean): If true, offloads model parsing and merging to Web Workers for better performance.
    • camera (object): Configuration for the camera:
      • type (string): e.g., 'perspective'.
      • x, y, z (number): Camera position.
      • target (number[]): The [x, y, z] coordinates the camera looks at.

    Initialization

    Pass an HTMLElement as the second argument to attach the renderer to a specific DOM element. If omitted, it defaults to document.body.

    import { ModelRender } from 'minerender/model';
    
    const options = {
        type: 'block',
        assetRoot: '/path/to/assets',
        useWebWorkers: true,
        camera: {
            type: 'perspective',
            x: 35,
            y: 25,
            z: 20,
            target: [0, 0, 0]
        }
    };
    
    const renderer = new ModelRender(options, document.getElementById('render-container'));
  2. Configure MineRender with defaultOptions

    master

    When initializing a renderer, you can pass an options object to customize the behavior. The defaultOptions object defines the following configuration keys:

    Debugging

    • showAxes (boolean): Show the scene's axes.
    • showOutlines (boolean): Show bounding boxes.
    • showGrid (boolean): Show coordinate grid.

    Controls

    An object containing settings for OrbitControls:

    • controls.enabled (boolean, default: true): Toggle controls.
    • controls.zoom (boolean, default: true): Toggle zoom.
    • controls.rotate (boolean, default: true): Toggle rotation.
    • controls.pan (boolean, default: true): Toggle panning.
    • controls.keys (boolean, default: true): Toggle keyboard controls.

    Camera

    An object defining camera properties:

    • camera.type (string, default: "perspective"): Use "perspective" or "orthographic".
    • camera.x (number): Camera X-position.
    • camera.y (number): Camera Y-position.
    • camera.z (number): Camera Z-position.
    • camera.target (number[]): [x, y, z] array where the camera should look.
    • camera.zoom (number): Camera zoom level.

    Rendering & Performance

    • frameRateLimit (number): Limit render calls to a specific FPS. Set to -1 for unlimited.
    • enableStats (boolean): Toggle stats.js info overlay.
    • pauseHidden (boolean): Pause rendering for elements not currently on screen.
    • autoResize (boolean): Automatically resize the canvas and camera when the window or container resizes.
    • sendStats (boolean): If true, sends usage statistics to minerender.org.
    • forceContext (boolean): Forces context restoration/loss when elements enter/leave the screen.

    Canvas

    • canvas.width (number): Explicit width for the canvas.
    • canvas.height (number): Explicit height for the canvas.
    const options = {
        showAxes: true,
        controls: {
            zoom: false
        },
        camera: {
            type: "perspective",
            x: 50,
            y: 50,
            z: 50,
            target: [0, 0, 0]
        },
        frameRateLimit: 60
    };
  3. Configure EntityRender options

    master

    When instantiating EntityRender, you can provide an options object to customize the rendering behavior.

    Key options include:

    • assetRoot: A string representing the base URL or path used to resolve asset files. This is used when calling loadTextureAsBase64 to find textures under the /entity/ path.
    • showOutlines: A boolean that, when enabled, adds a THREE.WireframeGeometry and a THREE.BoxHelper to every cube within the entity model to help visualize the geometry.
    const options = {
        assetRoot: 'https://example.com/assets/',
        showOutlines: true
    };
    const renderer = new EntityRender(options);
  4. Configure GuiRender options

    master

    When instantiating GuiRender, you can provide an options object to customize the rendering environment.

    KeyTypeDefaultDescription
    assetRootstringDEFAULT_ROOTThe base path used to resolve Minecraft asset textures.
    controls.enabledbooleantrueEnables/disables user interaction controls.
    controls.zoombooleantrueEnables/disables zooming.
    controls.rotatebooleanfalseEnables/disables rotation.
    controls.panbooleantrueEnables/disables panning.
    camera.typestring"perspective"The type of Three.js camera to use.
    camera.x/y/znumber0/0/50Initial camera position.
    camera.targetnumber[][0, 0, 0]The point the camera looks at.

    Note: assetRoot should point to a directory that contains a minecraft/ subfolder containing the textures.

  5. Configure SkinRender options

    master

    When instantiating SkinRender, you can provide an options object to customize the rendering environment.

    Key configuration keys:

    • camera: An object defining the camera properties:
      • type: Camera type (e.g., "perspective").
      • x, y, z: Camera position coordinates.
      • target: An array [x, y, z] representing the point the camera looks at.
    • makeNonTransparentOpaque: (boolean) If true, the renderer attempts to remove partial transparency from the skin texture (useful for certain rendering modes).
    const options = {
        camera: {
            type: "perspective",
            x: 20,
            y: 35,
            z: 20,
            target: [0, 18, 0]
        },
        makeNonTransparentOpaque: true
    };
  6. Use the EntityRender class to render Minecraft entities

    master

    The EntityRender class is used to render 3D Minecraft entities in a web environment using Three.js. It handles loading entity models (JSON) and textures, merging parent model data, and constructing the 3D scene.

    Constructor

    new EntityRender(options, element)

    • options (Object): Configuration for the renderer.
      • assetRoot (string): The root directory to fetch asset files from. Defaults to DEFAULT_ROOT.
      • showOutlines (boolean): If true, renders wireframe outlines and bounding boxes around entity cubes.
    • element (HTMLElement): The DOM element to which the renderer will be attached. Defaults to document.body.

    Rendering Entities

    render(entities, cb)

    • entities (Array<Object|string>): An array of entities to render.
      • If an entity is a string, it is treated as both the model and the texture name.
      • If an entity is an Object, it should follow this shape:
        • model (string): The name of the entity model file.
        • texture (string): The name of the entity texture file.
        • textureScale (number): The scale of the texture (defaults to 1).
    • cb (Function): An optional callback function executed once all entities in the array have been successfully loaded and added to the scene.

    Note: The renderer fetches models from https://minerender.org/res/models/entities/{model}.json.

    import EntityRender from './path/to/entity/index.js';
    
    const options = {
        assetRoot: 'https://your-assets.com/',
        showOutlines: true
    };
    
    const renderer = new EntityRender(options, document.getElementById('render-container'));
    
    const entitiesToRender = [
        'zombie', // Simple string usage (model and texture are both 'zombie')
        {
            model: 'skeleton',
            texture: 'skeleton_texture',
            textureScale: 1
        }
    ];
    
    renderer.render(entitiesToRender, () => {
        console.log('All entities rendered!');
    });
  7. Resolve model variants with findMatchingVariant()

    master

    The findMatchingVariant function finds a matching key in a blockstate's variants object based on a selector string.

    Parameters:

    • variants: The variants object from a Minecraft blockstate JSON.
    • selector: A comma-separated string of properties and values (e.g., "facing=north,water=false").

    Behavior:

    • It converts the selector string into an object.
    • It iterates through the available variants and returns the first one where all selector properties match the variant's properties.
    • If no match is found, it returns null.
    • If the selector is empty or invalid, it returns an empty string "".
    import { findMatchingVariant } from './src/model/modelFunctions';
    
    const variants = {
      '"": { "model": "block/stone" },
      '"facing=north"': { "model": "block/stone_north" },
      '"facing=south"': { "model": "block/stone_south" }
    };
    
    const match = findMatchingVariant(variants, 'facing=north');
    // match === '"facing=north"'
  8. Scale UV coordinates

    master

    The scaleUv function calculates scaled UV coordinates based on a target size and a reference scale (defaulting to 16, which is standard for Minecraft textures).

    Parameters:

    • uv (number): The original UV coordinate.
    • size (number): The target size.
    • scale (number, optional): The reference scale (defaults to 16).
    import { scaleUv } from './functions.js';
    
    const scaled = scaleUv(0.5, 32, 16);
    // Returns 1.0
  9. Manage MineRender caches and instances

    master

    The ModelRender.cache object provides access to internal caches and methods to manage the lifecycle of rendered assets and instances. You can inspect loaded textures, merged models, and instance counts, or clear them to free up memory.

    Available cache properties:

    • loadedTextures: Cache of loaded textures.
    • mergedModels: Cache of merged models.
    • instanceCount: Current number of model instances.
    • texture: Cache of textures.
    • canvas: Cache of canvases.
    • material: Cache of materials.
    • geometry: Cache of geometries.
    • instances: Cache of instances.
    • animated: Array of functions used for animated textures.

    Available management methods:

    • resetInstances(): Deletes properties from modelInstances and instanceCache.
    • clearAll(): Clears all caches including textures, canvases, materials, geometries, instances, and the animated textures array.
    // Accessing caches
    const textures = ModelRender.cache.texture;
    const instanceCount = ModelRender.cache.instanceCount;
    
    // Clearing all cached assets
    ModelRender.cache.clearAll();
    
    // Resetting only instances
    ModelRender.cache.resetInstances();
  10. Export scene content to images or 3D formats

    master

    The Render base class provides several methods to export the current scene content:

    Export to Image

    toImage(trim, mime) Returns the canvas content as a Base64 encoded image string.

    • trim (boolean, default: false): If true, trims transparent pixels from the edges.
    • mime (string, default: "image/png"): The MIME type of the image.

    Export to 3D Formats

    • toObj(): Returns the scene content in .obj format (geometries only, no textures) as a string.
    • toGLTF(exportOptions): Returns a Promise that resolves with the .gltf file content (geometries + textures). Accepts exportOptions for the GLTFExporter.
    • toPLY(exportOptions): Returns the scene content in .ply format as a string. Accepts exportOptions for the PLYExporter.
    // Export as a trimmed PNG
    const imgData = render.toImage(true, 'image/png');
    
    // Export as GLTF
    render.toGLTF({ binary: true }).then(gltf => {
        console.log('GLTF content:', gltf);
    });
    
    // Export as OBJ
    const objData = render.toObj();
  11. Use CombinedRender to render multiple elements together

    master

    The CombinedRender class acts as a renderer-wrapper that allows you to combine multiple individual renderers (such as GuiRender, ModelRender, or SkinRender) into a single scene. This is useful for rendering complex scenes, such as a player and a block simultaneously.

    To use CombinedRender:

    1. Instantiate it with options and an optional element (the DOM element to attach to).
    2. Call .init(renders) passing an array of renderer objects.
    3. Call .render() to start the animation loop.

    Note: init() must be called before render().

    import CombinedRender from 'minerender/src/combined/index';
    
    // 1. Setup options and target element
    const options = { /* your options */ };
    const element = document.getElementById('render-container');
    
    // 2. Instantiate
    const combined = new CombinedRender(options, element);
    
    // 3. Initialize with an array of renderers (e.g., ModelRender, SkinRender)
    combined.init([
        new CombinedRender.ModelRender(modelOptions),
        new CombinedRender.SkinRender(skinOptions)
    ]);
    
    // 4. Start rendering
    combined.render();