// Copyright 2025-2026 肖其顿 (XIAO QI DUN) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package ofdgo import ( "container/list" "image" "reflect" ) // renderCache 按估算字节数限制派生渲染数据,淘汰不修改源资源 type renderCache[K comparable, V any] struct { limit, used int entries map[K]*list.Element order list.List } // renderCacheEntry 保存缓存值及内存成本 type renderCacheEntry[K comparable, V any] struct { key K value V cost int } // get 读取缓存并更新使用顺序 // 入参: key 缓存键 // 返回: V 缓存值, bool 是否命中 func (c *renderCache[K, V]) get(key K) (V, bool) { if item := c.entries[key]; item != nil { c.order.MoveToFront(item) return item.Value.(renderCacheEntry[K, V]).value, true } var zero V return zero, false } // put 缓存预算内的派生数据,超大单项不进入缓存 // 入参: key 缓存键, value 缓存值, cost 字节成本 func (c *renderCache[K, V]) put(key K, value V, cost int) { if item := c.entries[key]; item != nil { c.used -= item.Value.(renderCacheEntry[K, V]).cost c.order.Remove(item) delete(c.entries, key) } if cost <= 0 || cost > c.limit { return } if c.entries == nil { c.entries = make(map[K]*list.Element) } for c.used+cost > c.limit { item := c.order.Back() entry := item.Value.(renderCacheEntry[K, V]) c.used -= entry.cost delete(c.entries, entry.key) c.order.Remove(item) } c.entries[key] = c.order.PushFront(renderCacheEntry[K, V]{key, value, cost}) c.used += cost } // rasterCommandCost 按保留容量估算中立指令成本,不含临时后端路径及借用图片 // 入参: command 绘制指令 // 返回: int 字节成本 func rasterCommandCost(command RasterCommand) int { cost := 512 + (cap(command.Path)+cap(command.Clip))*56 if command.Stroke != nil { cost += 128 + cap(command.Stroke.Dashes)*8 } if command.Paint.Gradient != nil { cost += 256 + cap(command.Paint.Gradient.Stops)*64 if mesh := command.Paint.Gradient.Mesh; mesh != nil { cost += 32 + cap(mesh.Triangles)*240 } } return cost } // rasterCommandsCost 估算整组指令保留的内存,同一图片实例只计一次 // 入参: commands 绘制指令, limit 缓存预算 // 返回: int 估算字节数,超预算时返回预算加一 func rasterCommandsCost(commands []RasterCommand, limit int) int { limit = max(0, limit) cost := 0 var images map[image.Image]bool for _, command := range commands { part := rasterCommandCost(command) if part < 0 || part > limit-cost { return limit + 1 } cost += part if command.Image == nil { continue } if reflect.ValueOf(command.Image).Kind() == reflect.Pointer { if images[command.Image] { continue } if images == nil { images = make(map[image.Image]bool) } images[command.Image] = true } part = imageResourceCost(command.Image, limit-cost) if part > limit-cost { return limit + 1 } cost += part } return cost }