Self-adaptive texture atlas compression system and method based on Unity engine
By developing an adaptive texture atlas compression system in the Unity engine, the problem of difficult texture resource optimization in the existing technology is solved, and efficient texture resource management and atlas construction are realized, and processing efficiency and space utilization are improved.
Patent Information
- Application Number
- CN202510502243.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-04-22
- Publication Date
- 2025-05-27
- Estimated Expiration
- 2045-04-22
AI Technical Summary
In terms of texture resource optimization, the existing technology has difficulty in adapting to dynamic content updates, dynamic batch technology leads to performance bottlenecks and multi-threaded data conflicts, offline tool chains and engine pipelines are split, resulting in missing configuration hot updates, and translucent texture processing edge jagging problems.
Adaptive texture atlas compression system based on Unity engine is adopted, and dynamic texture resource management and atlas construction are realized through texture resource import module, texture resource setting module, picture atlas setting module and graphics algorithm module. The system adopts a double-buffer configuration management mechanism and an improved CityHash algorithm to achieve efficient synchronization and conflict evasion of configuration data.
It realizes automated resource management while maintaining visual quality, improves the processing efficiency of texture resources and the space utilization of the drawing set, and avoids texture memory waste and rendering quality loss.
Abstract
Description
Technical Field
[0001] The present invention relates to the field of graphics processing, and specifically to an adaptive texture atlas compression system and method based on the Unity engine. Background Art
[0002] In the field of game development, texture resource optimization is a key technology for improving rendering performance and reducing memory occupancy. Especially for mobile devices, texture compression and atlas layout efficiency directly affect the application fluency. As a mainstream development platform, the built-in texture pipeline of the Unity engine adopts a fixed compression strategy, which is difficult to adapt to the dynamic content update scenario. Developers need to manually adjust the atlas parameters periodically to balance quality and performance, resulting in fragmented workflows. With the development of open-world games and real-time 3D applications, the demand for adaptive texture compression technology is becoming increasingly urgent, and automated resource management needs to be achieved while maintaining visual quality.
[0003] In the existing technical solutions, the solutions based on fixed compression formats such as ETC2 / ASTC reduce texture memory through block compression, but cannot dynamically adjust the compression parameters to adapt to content changes. The technology based on runtime dynamic batching uses the CPU to calculate the texture layout in real time. Although a certain degree of flexibility is achieved, the high-frequency calculation leads to a sharp increase in the main thread load, and there is a lack of an effective version control mechanism. There are also offline atlas generation tools that generate optimized atlases through preprocessing, but their static configurations cannot respond to runtime content updates, and resources need to be exported repeatedly and the application needs to be restarted, seriously damaging the development iteration efficiency.
[0004] The existing technologies mainly have the following deficiencies: The fixed compression format solutions are difficult to adapt to dynamic content updates, resulting in wasted texture memory or quality loss; The dynamic batching technology causes performance bottlenecks due to the lack of an incremental update mechanism, and multi-threaded resource competition is likely to cause data inconsistency; The offline toolchain is separated from the engine pipeline, and hot configuration updates cannot be achieved, and the edge jaggedness and seam problems are prominent when processing semi-transparent textures; In addition, the existing solutions do not consider runtime parameter adjustment in the transparent pixel detection and polygon simplification links, resulting in it being difficult to balance the atlas space utilization rate and rendering quality. Summary of the Invention
[0005] Aiming at the deficiencies of the existing technologies, the present invention provides an adaptive texture atlas compression system and method based on the Unity engine to solve the problems of wasted texture memory or decreased visual quality caused by the inability of the fixed compression format solutions to dynamically adjust parameters as mentioned in the above background art; the performance bottlenecks and multi-threaded data conflicts caused by the lack of an incremental update mechanism in the dynamic batching technology; the lack of hot configuration updates caused by the separation of the offline atlas tool and the engine pipeline and the edge jaggedness defects generated during the processing of semi-transparent textures; the problem that it is difficult to balance the atlas space utilization rate and rendering quality due to the lack of support for runtime parameter dynamic adjustment in the existing transparent pixel detection and polygon simplification technologies.
[0006] To achieve the above objectives, the present invention is implemented through the following technical solutions: An adaptive texture atlas compression system and method based on the Unity engine, including a texture resource import module for converting PNG images into DYN files and generating configuration data, texture data, and sprite data in the Unity engine. The configuration data includes texture size, transparent pixel threshold, and polygon generation parameters. The sprite data records the position and size of sub-textures in the atlas; A texture resource setting module, connected to the texture resource import module and adopting a double-buffer configuration management mechanism, writes the modified configuration data by the user into the edit buffer and periodically merges the incremental changes into the running buffer through an asynchronous thread. When merging, it detects the hash value difference based on the improved CityHash algorithm and only synchronizes the configuration fields with changes. When the user actively submits the modification, the asynchronous thread is suspended to give priority to hash verification; An atlas setting module for dynamically modifying the atlas configuration data and saving it to a DYN file, a DYN-META file, or a resource GUID file. The dynamic modification triggers the Unity resource pipeline to regenerate the atlas texture; A graphics algorithm module, including an edge detection unit, a polygon generation unit, a polygon rasterization unit, and an arrangement unit: The edge detection unit scans non-transparent pixels row by row from the bottom of the texture, records the coordinates of the first non-transparent pixel, and determines the edge extension direction based on the transparency difference of adjacent pixels to generate closed polygon vertex data. After generation, it performs a ratio check of the number of vertices to the area of the non-transparent pixel region of the original texture and triggers a rescan when the deviation exceeds 5%; The polygon generation unit calls the open-source geometric calculation library Clipper to perform geometric operations on the closed polygon vertex data, including compensating for edge pixel loss by an expansion offset amount of a preset vertex expansion distance through an offset operation; then using the Douglas-Peucker algorithm to simplify the vertices and clip the regions exceeding the original boundary, and finally merging them into polygons and dynamically adjusting parameters according to the texture resolution. When the texture resolution is lower than 512×512 pixels, the expansion offset amount and the vertex merging threshold increase by half of the reference value; The polygon rasterization unit converts the polygon into pixel data through the active edge table algorithm and generates a difference hash map by dividing the preset canvas in the arrangement unit into equal-sized grid cells and calculating the variance of the pixel occupancy rate in each cell; The layout unit mutually arranges pixel data onto the preset canvas and outputs the final atlas. During the arrangement, it traverses all possible offset positions and calculates the overlapping state of the rasterized mask in parallel through multiple threads to select a position with no overlap and the minimum space occupancy. At the same time, it reads the current expansion offset of the polygon generation unit as the step reference value; The atlas construction module is used to merge multiple PNG images into a DYN file and generate a tightly arranged atlas texture through the graphic algorithm module.
[0007] Preferably, the texture resource import module realizes the conversion from PNG to DYN file by rewriting the texture import pipeline of the Unity engine; specifically, during the operation, the module first parses the pixel data of the original PNG file, scans the RGBA channels pixel by pixel to extract the texture size and the distribution of transparent areas, and then filters out invalid pixels according to the preset transparent pixel threshold, where the transparent pixel threshold is a pixel with an Alpha value lower than 0.1; after the filtering is completed, texture data including a Mipmap chain is generated through the built-in TextureImporter interface of Unity, and the generation parameters of the Mipmap chain include the compression format, the anisotropic filtering level, and the maximum resolution limit; at the same time, the module calls the SpriteEditor tool to generate sprite data, and the sprite data records the rectangular area coordinates and size offsets of the sub-textures in the atlas; after the conversion is completed, the texture resource import module creates a.dyn file in the Unity resource manager and registers the default configuration data, where the default configuration data includes the texture size, the initial value of the transparent pixel threshold is 0.1, and the polygon generation parameters are an expansion offset of 2px and a vertex simplification rate of 30%; the generation process of the configuration data is to parse the pixel information of the original image to extract the texture size and the transparent area and filter out invalid pixels according to the preset transparent pixel threshold, and generate texture data including a Mipmap chain and compression format settings through the built-in texture processing pipeline of Unity; after the registration is completed, it triggers the refresh of the resource pipeline to force Unity to recompile the asset database to load the newly generated DYN file; the sub-texture refers to an independent texture unit in the atlas after the original PNG file is processed, and its position and size are recorded by the sprite data, which is used for accurate positioning through UV coordinates during rendering; the expansion offset is the contour expansion distance dynamically adjusted according to the texture resolution, which is used to compensate for pixel loss during compression or rasterization, and the calculation formula is the actual offset = reference offset × 1.2 + 2 pixels, where the default value of the reference offset is 2 pixels, that is, the resolution ≥ 512 × 512, or 3 pixels, that is, the resolution < 512 × 512.
[0008] Preferably, the texture resource setting module adopts a double-buffer configuration management mechanism, which includes an editing buffer and a running buffer; when the user modifies the configuration parameters through the Unity editor interface, all changes are first written to the memory-mapped file of the editing buffer, and the memory-mapped file stores the configuration fields and their timestamps in JSON format; the asynchronous thread scans the editing buffer at a period of 200 ms, traverses all configuration fields during scanning and calls the improved CityHash algorithm to calculate the hash value difference. The improved CityHash algorithm converts floating-point parameters into 16-bit fixed-point encoding and then calculates the hash value. Only the configuration fields with changes are synchronized, and when the synchronization operation is actively submitted by the user, the asynchronous thread is suspended to give priority to executing the hash check. For example, the transparent pixel threshold is converted into 16-bit fixed-point encoding, including 1 sign bit, 7 integer bits, and 8 fractional bits, and then the hash calculation is performed; if a hash difference is detected, only the changed fields are extracted and encrypted and packaged into a transaction log. The file header of the transaction log includes an incrementing UUID of the version identifier, a CRC32 checksum, and a timestamp; after packaging, the incremental data is injected into the Unity resource pipeline through a low-priority asynchronous thread. When injecting, the write handle of the resource database is locked to prevent data competition; if the user actively submits a modification during the execution of the asynchronous thread, the asynchronous thread is immediately interrupted and the hash check is given priority. After the check passes, the data in the editing buffer is directly copied to the running buffer, and the version identifier of the transaction log is updated to mark the forced submission operation.
[0009] Preferably, the edge detection unit scans non-transparent pixels row by row from the bottom of the texture to generate a closed polygon; in specific implementation, the module traverses upward from the bottom row of the texture, scans pixel points from left to right in each row, and records its coordinates (x, y) as the starting point when detecting the first pixel with an Alpha value ≥ 0.1; subsequently, the edge extension direction is determined based on 8-neighborhood connectivity analysis. The 8-neighborhood analysis sequentially checks the Alpha values of the pixels in the upper, lower, left, right, and four diagonal directions of the current pixel, and selects the adjacent pixel with an Alpha value ≥ 0.1 and not yet visited as the next edge point; during edge tracing, a vertex linked list is constructed in real time, and a closed polygon is formed when returning to the starting point again; after generation, the module performs a vertex number check, calculates the ratio of the number of polygon vertices to the area of the non-transparent region of the original texture. The area is obtained by counting the total number of non-transparent pixels multiplied by the single-pixel area (1 / texture resolution); if the vertex number / area ratio exceeds a preset threshold, such as allowing 1 vertex per 100 pixels, it is determined that the contour extraction is abnormal and a rescan is triggered. When rescanning, the starting row offset is adjusted by +5 rows to avoid repeated errors.
[0010] Preferably, the polygon generation unit calls the Clipper library to perform geometric processing on the polygon output by edge detection; first, it executes an outward expansion to a specified distance along the normal direction of the polygon vertices with the expansion offset as the reference value, that is, the reference value is 2px, and the normal direction is determined by calculating the cross product of adjacent side vectors; after the outward expansion, the Douglas-Peucker algorithm is used to simplify the vertices, and the algorithm iteratively deletes redundant vertices with the maximum vertical distance tolerance as the threshold; subsequently, the area exceeding the original texture boundary is cropped, and the cropping is achieved by calculating the intersection of the polygon vertices and the texture boundary rectangle (0, 0, width, height); finally, the vertices of adjacent polygons are merged to form a single contour, and when merging, adjacent points with a vertex spacing less than the merging threshold of 1px as the reference value are detected and average coordinate interpolation is performed; when the texture resolution is lower than 512x512, the module dynamically adjusts the parameters, increasing the expansion offset to 3px and the vertex merging threshold to 1.5px to adapt to the jagged edge characteristics of low-resolution textures.
[0011] Preferably, the polygon rasterization unit uses the active edge table algorithm to convert the polygon into pixel data; when initializing the algorithm, an edge table is constructed, and each edge records the starting point (x_start, y_start), the ending point (x_end, y_end), the current x coordinate, and the reciprocal of the slope (dx / dy); the scan line is traversed and moved up row by row starting from the lowest y value of the polygon, and the active edge table is updated at each scan line: remove the edges with y_end ≤ the current y, and add new edges with y_start ≤ the current y; the edges in the active edge table are sorted by the x coordinate and paired up to form horizontal line segments, and pixels are filled between each pair of edges; when filling, according to the requirements of the Unity's TextureFormat.RGBA32 format, the pixel data is encapsulated with 4-byte memory alignment, and the Alpha channel is set to 255 (opaque) or 0 (transparent); after rasterization is completed, a binary mask is generated, and the mask is a two-dimensional array, and the array element 1 represents occupied and 0 represents free.
[0012] Preferably, the layout unit mutually arranges the rasterized mask in a mutually exclusive manner to a preset canvas in the layout unit; wherein the preset canvas refers to a virtual layout area dynamically generated based on system configuration. First, the preset canvas is divided into grid units, and the size of the grid unit is dynamically calculated as 1 / 64 of the maximum canvas width and height according to the canvas size configured by the atlas setting module and maintains a 1:1 mapping relationship with the rendering resolution of the ShaderLab shader, and a spatial index is created to accelerate collision detection; when traversing all possible offset positions, multi-threaded parallel computing is started, and each thread is responsible for an offset area to calculate the overlapping state of the mask and the existing occupation of the canvas; when there is no overlap, the space utilization rate is calculated as the mask area divided by the bounding box area, and the position with the highest utilization rate is selected; if it is detected that the layout gap exceeds 2px, the step size is reduced to 50% of the original value to improve the positioning accuracy; if the layout fails 3 times in a row, the offset is increased by 200% of the current step size to skip the dense area; after the layout is completed, the Texture2D.PackTextures method is called to verify the UV coordinates. When it is detected that the edge pixels of the sub-texture overflow, the layout gap is automatically shrunk, decreasing by 0.5px each time until there is no overflow.
[0013] Preferably, the atlas setting module realizes real-time preview by customizing the ShaderLab shader; the generation of the difference hash map is divided into three steps: the canvas is divided into max(width,height) / 64 grid units; calculate the proportion of occupied pixels in each unit = number of occupied pixels / total area of the unit; traverse all version snapshots and calculate the variance of the occupancy ratio of the same unit in different versions; the units with a variance exceeding the hash threshold of the running buffer are marked as optimized areas, where the threshold is defaulted to 0.25; the ShaderLab shader reads the hash map data in a streaming manner through the ScriptableObject API and injects it into the GPU video memory in the OnPostRender event of the Unity editor; during rendering, colors are mapped according to the variance value, with a variance of 0 - 0.25 being a green gradient, 0.25 - 0.5 being yellow, and above 0.5 being red; the rendering result is directly overlaid on the output frame buffer of the running buffer to achieve zero-latency preview.
[0014] Preferably, the transaction log uses atomic writing to ensure data consistency; when writing, a temporary file is first created, and the version identifier, CRC32 checksum, and encrypted incremental data are written into the temporary file; after completion, the system-level file replacement operation is called to atomically replace the temporary file with the official log; when resuming from a breakpoint, the unfinished log file is read, the version identifier is parsed to locate the last valid transaction, and the data integrity is verified according to the CRC32 checksum; if the verification fails, the corrupted log is deleted and an automatic rollback is triggered, and the rollback restores the configuration data from the previous valid version snapshot.
[0015] Preferably, the layout unit dynamically adjusts the number of threads and step parameters when the CPU usage rate exceeds 70%. When adjusting, at least one CPU core is reserved for the low-priority tasks of the asynchronous threads; when it is detected that the layout gap is too large, the step size is reduced to improve the positioning accuracy. If the continuous layout failure times reach 3 times, the offset is increased to avoid local dense areas; after the layout result is verified by the refined collision detection algorithm without pixel overlap, it is output to the atlas texture file. The collision detection algorithm and the multi-threaded parallel computing process use mutex locks to achieve timing synchronization, and when dynamically adjusting the step size, the step size ≥ (current offset × 1.2 + 2 pixels).
[0016] Preferably, the layout unit dynamically adjusts the number of threads according to the CPU usage rate; when the CPU usage rate is lower than 70%, the maximum number of threads is started, that is, the logical core number - 1. When it exceeds 70%, the number of threads is linearly reduced to reserve at least one CPU core for the asynchronous threads; the thread priorities are divided into two levels: the layout calculation thread is set to the Normal priority, and the asynchronous log writing thread is set to the Lowest priority; the threads synchronize the access to the canvas space index through mutex locks, and the tryLock mechanism is used when obtaining the lock. After 100 ms of timeout, the current offset position is skipped to avoid deadlocks.
[0017] Preferably, when a configuration conflict or data corruption is detected, an automatic rollback is triggered; the rollback process includes: extracting the previous stable version identifier from the transaction log; locating the corresponding.dyn.meta file backup according to the identifier; parsing the backup file to restore the configuration fields to the edit buffer; calling the ForceReserializeAssets method of the Unity resource pipeline to force the re-serialization of the assets; after the restoration is completed, a rollback report is generated. The report records the exception timestamp, the affected fields, and the restoration result, and outputs a warning message through the Unity editor console.
[0018] The present invention provides an adaptive texture atlas compression system and method based on the Unity engine, having the following beneficial effects: Through the collaborative work of the dual-buffer configuration management mechanism and the improved CityHash algorithm in the present invention, efficient synchronization of configuration data and conflict avoidance are achieved; the asynchronous incremental merging mechanism of the edit buffer and the running buffer ensures real-time response to user modification operations while avoiding main thread blocking; the dynamic parameter coordinator automatically adjusts polygon generation and arrangement parameters according to texture resolution, significantly improving the processing accuracy of low-resolution textures and the operation efficiency of high-resolution textures; the strict alignment optimization of the active edge table algorithm and the Unity native memory format enables the rasterization process to seamlessly adapt to the engine rendering pipeline; the multi-threaded arrangement engine combines refined collision detection to maximize the utilization rate of the atlas space on the premise of ensuring no pixel overlap, and finally achieves the optimal balance between processing speed and resource occupancy.
[0019] The present invention adopts the atomic operation and CRC check mechanism of the transaction log to ensure the integrity and recoverability of configuration changes in case of abnormal interruption; the breakpoint resumption function quickly locates unfinished transactions through version identifiers and effectively prevents the spread of data corruption in combination with the automatic rollback mechanism; the real-time preview function uses the precise mapping of the difference hash map and the customized ShaderLab shader to intuitively display the spatial optimization effects of different configuration versions; the dynamic thread scheduling strategy reserves a dedicated resource channel for asynchronous log writing while maintaining the efficiency of arrangement calculation; the polygon vertex check and UV coordinate reverse verification constitute a dual fault tolerance system to ensure the quality of the atlas throughout the entire link from geometry generation to final output; finally, a texture processing solution with stability, visualization, and self-repair capabilities is formed. Detailed implementation manners
[0020] The technical solutions in the embodiments of the present invention will be described clearly and completely below. Apparently, the described embodiments are only a part of the embodiments of the present invention, rather than all of the embodiments. All other embodiments obtained by those of ordinary skill in the art based on the embodiments of the present invention without creative efforts shall fall within the protection scope of the present invention.
[0021] Example 1: An embodiment of the present invention provides an adaptive texture atlas compression system and method based on the Unity engine. In a game development scenario, the system is used to integrate scattered UI icons into an adaptive texture atlas. Developers select a group of PNG files to be processed in the Unity editor, such as 50 button icons of different sizes, and start the conversion process through the texture resource import module. The module first parses the pixel data of each PNG file, detects the transparent area by row-by-row scanning, and sets the transparent pixel threshold to consider pixels with an Alpha value ≤ 0.05 as invalid. For an icon with a size of 1024×1024, the module generates texture data in the ASTC_6x6 compression format and creates sprite data to record the initial position of each sub-texture. For example, the rectangular area of Icon_01 is (0,0,256,256). The configuration data is written to a temporary edit buffer, with the initial expansion offset set to 2px and the vertex simplification rate set to 25%. Subsequently, developers adjust the parameters through the texture resource setting module, increase the transparent pixel threshold to 0.1 to retain the semi-transparent edge, and the modified configuration data triggers an incremental synchronization of an asynchronous thread. The asynchronous thread scans the edit buffer at intervals of 200ms, calculates the changed fields using the improved CityHash algorithm after detecting the hash value difference. Among them, the 16-bit fixed-point encoding of the threshold field changes from 0x0005 to 0x000A, generates a transaction log with a version identifier of UUID_001 and encrypts it into the resource pipeline. After the atlas construction module is started, it calls the edge detection unit to process each icon, scans row by row from the bottom of the texture until the first pixel with Alpha ≥ 0.1 is found, such as the coordinates (12,8), and generates a polygon with 32 vertices by tracking the edge through 8-neighborhood analysis. The polygon generation unit performs geometric correction, expands the vertices outward by 3px to compensate for compression losses, deletes redundant vertices to 24 using the Douglas-Peucker algorithm, and merges adjacent vertices after cropping the area beyond the original boundary to form a single contour. The rasterization module uses the active edge table algorithm to convert the polygon into a binary mask and encapsulates the pixel data in the RGBA32 format. The layout unit arranges 50 masks on a 4096×4096 canvas, starts 8-thread parallel computing, each thread is responsible for detecting the offset positions of 6-7 icons, accelerates the collision detection through spatial indexing, and finally selects a layout scheme with a space utilization rate of 92% and generates a UV coordinate mapping table. When it is detected that the layout gap of Icon_17 exceeds 3px, the module reduces the step size from 2px to 1px to reposition until the gap ≤ 1px. After the layout is completed, the real-time preview function renders a differential hash map through the ShaderLab shader, compares the occupancy variance of the grid cells with a size of 64×64 between the current version and the historical version, and marks 3 areas with excessive variance for developers to optimize. Finally, the system automatically saves the configuration to a.dyn file and updates the transaction log version to UUID_002, completing the entire atlas construction process.
[0022] Embodiment 2: This embodiment is based on Embodiment 1: Special optimization is carried out for low-resolution textures below 512×512; when the developer imports 20 character skill icons of 256×256, the texture resource import module automatically detects the resolution and adjusts the initial parameters, sets the dilation offset to 3px, and the vertex merging threshold to 1.5px; when the edge detection unit executes, it starts scanning from the +5 rows position at the bottom of the texture to avoid misdetecting jagged edges. After detecting the first valid pixel, enhanced 8-neighborhood analysis is adopted, and isolated pixels are additionally filtered. For example, if there are no valid pixels in 3 consecutive directions, it is regarded as noise; when the polygon generation unit calls the Clipper library to perform contour expansion, the offset is dynamically increased to 4.5px to compensate for the edge jaggedness of low resolution, and at the same time the vertex simplification tolerance is increased to 1.2px, so that the average number of simplified vertices is reduced from 18 to 14; when the layout unit starts, after detecting that the CPU usage rate of the system is 85%, it automatically adjusts the thread strategy, reduces the number of working threads from 8 to 4 and reserves 2 cores for the asynchronous logging thread; during the layout process, the module adopts a dynamic step strategy, sets the initial step to 3px, and when it detects that the layout fails 3 times continuously in a local area, the step is increased to 6px to skip the dense area; the rasterized mask data is transmitted through the NativeArray interface to ensure consistency with the memory alignment requirements of the Unity Job System; the real-time preview function optimizes the difference hash map for small-size textures, adjusts the grid cell size to 32×32 to improve the detection accuracy, and uses bilinear interpolation to eliminate pixelated jaggedness when the ShaderLab shader reads the binary stream; when the write of the transaction log is delayed due to high system load, the breakpoint resumption mechanism is automatically activated, records the current layout progress to the log file UUID_003 and releases the resource lock; after the developer adjusts the canvas size from 2048×2048 to 1024×1024, the system triggers an automatic rollback mechanism, restores from the transaction log UUID_002 to the previous valid configuration, and preferentially reuses the processed polygon data when recalculating the layout scheme to reduce the calculation amount; in the finally generated atlas texture, 20 icons are arranged with a space utilization rate of 89%, and the UV coordinate mapping table is secondarily verified to ensure no pixel overlap; compared with Embodiment 1, this embodiment improves the atlas generation efficiency of low-resolution textures by 40% and reduces the memory occupancy by 25% through resolution-adaptive parameter adjustment, dynamic thread control, and enhanced edge detection.
[0023] Although the embodiments of the present invention have been shown and described, it will be understood by those of ordinary skill in the art that various changes, modifications, substitutions and variations can be made in these embodiments without departing from the principles and spirit of the present invention, and the scope of the present invention is defined by the appended claims and their equivalents.
Claims
1. An adaptive texture atlas compression system based on Unity engine, characterized in that: include: The texture resource import module is used to convert PNG images into DYN files and generate configuration data, texture data and sprite data in the Unity engine. The configuration data includes texture size, transparent pixel threshold and polygon generation parameters. The sprite data records the position and size of the sub-texture in the atlas. The texture resource setting module is connected to the texture resource import module and adopts a double buffer configuration management mechanism. The configuration data modified by the user is written into the editing buffer and the incremental changes are periodically merged into the running buffer through an asynchronous thread. When merging, the hash value difference is detected based on the improved CityHash algorithm, and only the configuration fields that have changed are synchronized. When the user actively submits the modification, the asynchronous thread is suspended to perform the hash check first. An atlas setting module, used to dynamically modify atlas configuration data and save it to a DYN file, a DYN-META file or a resource GUID file. The dynamic modification triggers the Unity resource pipeline to regenerate the atlas texture; Graphics algorithm module, including edge detection unit, polygon generation unit, polygon rasterization unit and arrangement unit: The edge detection unit scans non-transparent pixels row by row from the bottom of the texture, records the coordinates of the first non-transparent pixel and determines the edge extension direction according to the transparency difference of adjacent pixels to generate closed polygon vertex data, performs a ratio check of the number of vertices and the area of the original texture non-transparent pixel region after generation, and triggers rescanning when the deviation exceeds 5%; The polygon generation unit calls the open source geometric calculation library Clipper to perform geometric operations on the closed polygon vertex data, including using an offset operation to make the expansion offset of the preset vertex expansion distance compensate for the edge pixel loss; The Douglas-Peucker algorithm is then used to simplify vertices and clip areas beyond the original boundaries. Finally, they are merged into polygons and the parameters are dynamically adjusted according to the texture resolution. When the texture resolution is lower than 512×512 pixels, the expansion offset and vertex merging threshold are increased by half of the baseline value. The polygon rasterization unit converts the polygon into pixel data by using an active edge table algorithm, and calculates the variance of the pixel occupancy rate in each unit by dividing the preset canvas in the arrangement unit into equal-sized grid units to generate a difference hash map; The arrangement unit mutually exclusively arranges the pixel data to the preset canvas and outputs the final atlas, traverses all possible offset positions during arrangement and calculates the overlapping state of the rasterization mask in parallel through multi-threading to select a position without overlap and with the smallest space occupation, and at the same time reads the current expansion offset of the polygon generation unit as a step reference value; The atlas construction module is used to merge multiple PNG images into a DYN file and generate a compactly arranged atlas texture through the graphics algorithm module.
2. The adaptive texture atlas compression system based on the Unity engine according to claim 1, characterized in that: When converting PNG and pictures into DYN files, the texture resource import module rewrites the processing logic of the Unity engine for the DYN file to dynamically generate configuration data. At the same time, the editing buffer is scanned at fixed time intervals through the asynchronous thread. When a hash value difference is detected, the improved CityHash algorithm is used to calculate the hash value difference, and the transaction log is encrypted and packaged. When writing, the file handle is locked by atomic operation and the incremental data is injected into the Unity resource pipeline through a low-priority asynchronous thread.
3. The adaptive texture atlas compression system based on Unity engine according to claim 1, characterized in that: The texture resource setting module dynamically adjusts the transparent pixel threshold, vertex number limit and edge detection direction through the Unity editor interface, saves the modified configuration data to the DYN file or DYN-META file and calls the automatic refresh mechanism of the Unity engine to update the configuration data in the memory; the texture resource setting module integrates a real-time preview function, generates an atlas texture by reading the temporary data of the editing buffer to cover the rendering output of the running buffer, triggers hash verification and transaction log submission after the user confirms the modification, and automatically rolls back to the previous stable state if the hash value is inconsistent with the current value of the running buffer. When rolling back, the corresponding configuration field is restored according to the version identifier of the transaction log.
4. The adaptive texture atlas compression system based on Unity engine according to claim 1, characterized in that: When the atlas construction module performs polygon optimization operations, it offsets vertices outward by a preset distance to prevent pixel loss and deletes redundant vertices through the Douglas-Peucker algorithm. After cropping the area beyond the original texture boundary, the vertices of adjacent polygons are merged to form a single outline. The calculation of the expansion offset satisfies a safety margin of offset × 1.2 + 2 pixels, where the offset reference value is dynamically adjusted according to the texture resolution.
5. The adaptive texture atlas compression system based on Unity engine according to claim 1, characterized in that: The binary mask generated by the polygon rasterization unit is used to mark the occupied area in the atlas canvas; The arrangement unit supports multi-version configuration snapshot comparison. The user saves multiple copies of the editing buffer and calculates the variance of the pixel occupancy rate in each unit by dividing the preset canvas in the arrangement unit into equal-sized grid units to generate a difference hash map. When the variance exceeds the hash check threshold of the running buffer, the grid unit is marked with red-yellow-green gradient coloring.
6. The adaptive texture atlas compression system based on Unity engine according to claim 1, characterized in that: After the layout unit outputs the UV coordinate mapping table, it calls Unity's Texture2D.PackTextures method for reverse verification, and automatically shrinks the layout gap when pixel overflow is detected. At the same time, through the integrated breakpoint resumption mechanism, when the Unity engine crashes unexpectedly, it automatically reads the unfinished transaction log after restart and skips the submitted configuration fields according to the transaction identifier. The file header of the transaction log contains a CRC check code to ensure data integrity. If the check fails, the automatic rollback mechanism is triggered.
7. The adaptive texture atlas compression system based on Unity engine according to claim 1, characterized in that: The atlas setting module realizes the real-time preview function by customizing the ShaderLab shader. The ShaderLab shader calculates the grid unit occupancy rate and renders the color difference in real time. When rendering, the binary data of the difference hash map generated by the polygon rasterization unit is streamed through Unity's ScriptableObject API, and the grid division accuracy is strictly consistent with the hash map; the temporary atlas texture of the real-time preview function is generated by intercepting the Unity editor OnPostRender callback event to directly cover the output of the running buffer.
8. The adaptive texture atlas compression system based on Unity engine according to claim 1, characterized in that: The arrangement unit dynamically adjusts the number of threads and step parameters when the CPU usage rate exceeds 70%, and reserves at least one CPU core dedicated to the low-priority tasks of the asynchronous thread during the adjustment; when it is detected that the arrangement gap is too large, the step size is reduced to improve the positioning accuracy, and if the number of consecutive arrangement failures reaches 3 times, the offset is increased to avoid local dense areas; the arrangement result is verified to have no pixel overlap through a refined collision detection algorithm and then output to the atlas texture file. The collision detection algorithm and the multi-threaded parallel computing process use a mutex lock to achieve timing synchronization and keep the step size ≥ (current offset × 1.2 + 2 pixels) when dynamically adjusting the step size.
9. The method for using the adaptive texture atlas compression system based on the Unity engine according to any one of claims 1 to 8, characterized in that: The following steps are involved: Convert PNG images to DYN files and generate configuration data including texture size, transparent pixel threshold, and polygon generation parameters. Dynamically create texture data and sprite data that records sub-texture position and size by rewriting the Unity engine's processing logic for DYN files. A double-buffered configuration management mechanism is adopted. The configuration data modified by the user is first written into the editing buffer, and the incremental changes are periodically merged into the running buffer through an asynchronous thread. During the merging, the hash value difference is calculated based on the improved CityHash algorithm, and only the changed configuration fields are synchronized. When the user actively submits the modification, the asynchronous thread is suspended to perform hash verification first. Perform edge detection on the texture resources in the DYN file, scan non-transparent pixels row by row from the bottom of the texture and generate closed polygon vertex data, then call the open source geometric calculation library Clipper to perform geometric operations on the vertex data, including extending the outline, simplifying vertices, and clipping out-of-bounds areas. When the texture resolution is lower than 512×512 pixels, increase the expansion offset and vertex merging threshold by half of the base value; The optimized polygons are rasterized into pixel data through the active edge table algorithm, and memory aligned and encapsulated according to Unity's TextureFormat.RGBA32 format; Traverse all possible offset positions and calculate the overlapping state of the rasterized mask in parallel through multi-threading, and use the current expansion offset as the step reference value to mutually exclusive arrange the pixel data to the preset canvas. When the number of consecutive arrangement failures reaches 3 times, increase the offset. After the arrangement is completed, call the Texture2D.PackTextures method to verify the UV coordinate mapping table and automatically shrink the arrangement gap where pixel overflow is detected; Dynamically adjust the number of threads and step size parameters, reserve at least one CPU core dedicated to the asynchronous thread task, and synchronize collision detection and multi-threaded computing processes through mutex locks; When the user triggers the real-time preview, the temporary data of the editing buffer is read to generate a difference hash map, the grid unit occupancy difference is rendered by customizing the ShaderLab shader streaming, and the OnPostRender callback event of the Unity editor is intercepted to directly overwrite the output of the running buffer; If a transaction log CRC check failure is detected or the difference hash graph coloring error rate exceeds 5%, it will automatically roll back to the last stable configuration state based on the version identifier.
Citation Information
Patent Citations
Visual texture mapping method and system based on three-dimensional engine
CN118334227A
Unity-based BIM model Web end lightweight display method
CN119557525A
Systems and Methods for Incremental Dynamic Loading of Game Assets
US20240335746A1
Cited By
Dynamic texture atlas recombination and compression method and system based on airspace sparsity
CN121810824A
Dynamic texture atlas reorganization compression method and system based on spatial sparsity
CN121810824B