1194 lines
30 KiB
C++
1194 lines
30 KiB
C++
#include "dl_factory.h"
|
||
|
||
#ifndef DL_DISABLE_RENDER
|
||
#include "dl_factory_imp.h"
|
||
#include "io/dl_file.h"
|
||
#include "system/dl_time.h"
|
||
#include "vk/dl_vk.h"
|
||
#include "dl_free_type.h"
|
||
#include "io/dl_json.h"
|
||
#include "system/dl_audio.h"
|
||
#include "render/dl_render_def.h"
|
||
|
||
namespace dl
|
||
{
|
||
|
||
Factory* g_factory;
|
||
|
||
void Factory::LoadModel(std::string_view path_name, std::string_view name)
|
||
{
|
||
//-------------------------资源名字防止重复-----------------------
|
||
std::string path_name_real;
|
||
std::string res_name;
|
||
if (!String::GetPathAndRes(_strPathModel, path_name, path_name_real, res_name, name))
|
||
return;
|
||
|
||
auto iter = _imp->_mapName2Model.find(res_name);
|
||
if (iter != _imp->_mapName2Model.end())
|
||
{
|
||
log_err("资源名字已经存在:{},id:{}", res_name, iter->second);
|
||
return;
|
||
}
|
||
//-------------------------判断从文件还是从缓存读取-----------------------
|
||
bool b_read_cache;// 是否从缓存读取
|
||
bool b_exist = File::IsExist(path_name_real);// 文件是否存在
|
||
ModelCache::Node* cache_node = _imp->_modelCache.Get(path_name_real);// 缓存是否存在
|
||
if(!b_exist && !cache_node)
|
||
{//不存在
|
||
log_err("加载模型失败(文件不存在,并且没有缓存文件):{}", path_name_real);
|
||
return;
|
||
}
|
||
if (!b_exist && cache_node)
|
||
{//不存在,缓冲文件存在
|
||
b_read_cache = true;
|
||
}
|
||
else if (b_exist && cache_node)
|
||
{//都存在,则比较 校验值
|
||
uint32_t crc32 = File::GetCrc32(path_name_real);
|
||
if (crc32 == cache_node->_crc32)
|
||
b_read_cache = true;
|
||
else
|
||
{
|
||
cache_node->_crc32 = crc32;//更新
|
||
b_read_cache = false;
|
||
}
|
||
}
|
||
else
|
||
{//只文件存在
|
||
b_read_cache = false;
|
||
cache_node = _imp->_modelCache.Add(path_name_real);
|
||
if (!cache_node)
|
||
{
|
||
log_err("添加缓存文件失败:{}", path_name_real);
|
||
return;
|
||
}
|
||
cache_node->_crc32 = File::GetCrc32(path_name_real);
|
||
}
|
||
|
||
FloatTime t0 = g_time->GetCurrent();
|
||
std::vector<Model*> mul_model;
|
||
if (b_read_cache)
|
||
{
|
||
//加载所有子模型
|
||
for (std::string& str : cache_node->_allSub)
|
||
{
|
||
//加载model_object
|
||
ModelObject* model_object = new ModelObject;
|
||
model_object->Load(str);
|
||
//model_object -> model
|
||
Model* model = g_vk->CreateModel(model_object);
|
||
delete model_object;
|
||
//记录model
|
||
mul_model.push_back(model);
|
||
}
|
||
if (mul_model.empty())
|
||
{
|
||
log_err("模型加载失败(从缓存,没有sub):{}", res_name);
|
||
return;
|
||
}
|
||
size_t id = g_vk->GetMulModelSize();
|
||
_imp->_mapName2Model[res_name] = id;
|
||
g_vk->AddMulModel(mul_model);
|
||
}
|
||
else
|
||
{//从文件加载
|
||
std::vector<ModelObject*> mul_model_object = ModelObject::Create(path_name_real, res_name);
|
||
if (mul_model_object.empty())
|
||
return;
|
||
|
||
//转换所有子模型
|
||
for (ModelObject* model_object : mul_model_object)
|
||
{
|
||
//model_object -> model
|
||
Model* model = g_vk->CreateModel(model_object);
|
||
//记录model
|
||
mul_model.push_back(model);
|
||
}
|
||
if (mul_model.empty())
|
||
{
|
||
log_err("模型加载失败(从文件,没有sub):{}", path_name_real);
|
||
return;
|
||
}
|
||
size_t id = g_vk->GetMulModelSize();
|
||
_imp->_mapName2Model[res_name] = id;
|
||
g_vk->AddMulModel(mul_model);
|
||
|
||
//更新子模型
|
||
size_t i = 0;
|
||
for (ModelObject* model_object : mul_model_object)
|
||
{//资源名+id
|
||
//文件名
|
||
std::string file_name = fmt::format("{}#{}", res_name, i);
|
||
//model文件
|
||
const std::string PATH_CACHE = GetPathBinary3D();
|
||
std::string path_child = PATH_CACHE + file_name + ".model";
|
||
if (model_object->IsHaveTexture())
|
||
{//存在贴图则转存
|
||
//tex文件路径
|
||
std::string path_tex = PATH_CACHE + "texture/" + file_name + "/";
|
||
File::CreateFolder(path_tex);
|
||
//复制贴图文件,并转换路径
|
||
model_object->ConvertTexturePath(path_tex);
|
||
}
|
||
model_object->SaveToFile(path_child);
|
||
cache_node->_allSub.push_back(path_child);
|
||
delete model_object;
|
||
++i;
|
||
}
|
||
}
|
||
FloatTime t1 = g_time->GetCurrent();
|
||
log_msg("成功加载一个模型文件:{},子模型数量:{},从缓存:{},耗时:{}",
|
||
res_name, mul_model.size(), b_read_cache, t1 - t0);
|
||
}
|
||
|
||
gcActor Factory::CreateActor(std::string_view name)
|
||
{
|
||
gcActor act = get_gc<Actor>();
|
||
act->_idModel = _imp->_get_model_id(name);
|
||
act->_trans = Transform::Create();
|
||
act->_color = nullptr;
|
||
act->_modelAnimationInstance = _imp->_create_model_bone_animation(name);
|
||
act->_rigidBody = nullptr;
|
||
|
||
return act;
|
||
}
|
||
|
||
|
||
Camera* Factory::GetCamera()
|
||
{
|
||
return g_vk->GetCamera();
|
||
}
|
||
|
||
|
||
gcSprite Factory::CreateSpriteDefault(const Color& col /*= ColorDef::WHITE*/)
|
||
{
|
||
auto spr = get_gc<Sprite>();
|
||
|
||
bool b_solid = col[3] == 0.0f || col[3] == 1.0f;
|
||
//等于0时,用户很有可能随后修改透明度
|
||
spr->_id = b_solid ? _imp->_idSolid : _imp->_idSolidTrans;
|
||
spr->_quad = QUAD_DEFAULT_SPRITE;
|
||
spr->_z = Z_DEFAULT;
|
||
|
||
FactoryImp::SpriteInfo* spr_info = _imp->_get_sprite_info(spr->_id);
|
||
assert(spr_info);
|
||
|
||
for (int i = 0; i != 4; ++i)
|
||
{
|
||
spr->_col[i] = col;
|
||
spr->_uv[i] = spr_info->_uv[i];
|
||
}
|
||
#ifndef NDEBUG
|
||
spr->_name = ":";
|
||
#endif
|
||
return spr;
|
||
}
|
||
|
||
|
||
gcSprite Factory::CreateSprite(const SpriteID& spr_id)
|
||
{
|
||
FactoryImp::SpriteInfo* spr_info = _imp->_get_sprite_info(spr_id);
|
||
if (!spr_info)
|
||
{
|
||
log_err("获取SpriteInfo失败:{}", to_string(spr_id));
|
||
return g_factory->CreateSpriteDefault();
|
||
}
|
||
|
||
auto spr = get_gc<Sprite>();
|
||
|
||
spr->SetColor(spr_info->_color);
|
||
spr->_id = spr_id;
|
||
|
||
// 如果旋转过
|
||
Size size = Align::GetSize(spr_info->_rect);
|
||
if (spr_info->_bRightAngle)
|
||
std::swap(size[0], size[1]);
|
||
|
||
spr->_quad = createQuad(size, false)
|
||
- toPosition(spr_info->_anchor);//偏移锚点
|
||
spr->_z = Z_DEFAULT;
|
||
for (int i = 0; i != 4; ++i)
|
||
spr->_uv[i] = spr_info->_uv[i];
|
||
|
||
#ifndef NDEBUG
|
||
spr->_name = GetSpriteName(spr_id);
|
||
#endif
|
||
return spr;
|
||
}
|
||
|
||
|
||
gcSprite Factory::CreateSprite(std::string_view name, std::size_t index /*= 0*/)
|
||
{
|
||
auto iter = _imp->_mapName2SpriteID.find(std::string{ name });
|
||
if (iter == _imp->_mapName2SpriteID.end())
|
||
{
|
||
log_err("SpriteSheet不存在:{}", name);
|
||
return g_factory->CreateSpriteDefault();
|
||
}
|
||
|
||
std::vector<SpriteID>& all_id = iter->second;
|
||
|
||
if (index >= all_id.size())
|
||
{
|
||
log_err("下标越界:{},{}/{},", name, index, all_id.size());
|
||
return g_factory->CreateSpriteDefault();
|
||
}
|
||
|
||
SpriteID& spr_id = all_id[index];
|
||
return CreateSprite(spr_id);
|
||
}
|
||
|
||
bool Factory::RegisterSprite(std::string_view name, Image* img, const Point& anchor)
|
||
{
|
||
if (!img)
|
||
{
|
||
log_err("传入图像为空:{}", name);
|
||
return false;
|
||
}
|
||
//--------------------记录Rect到Factory的_vecRectInfo----------------
|
||
auto iter = _imp->_mapName2SpriteID.find(std::string{ name });
|
||
if (iter != _imp->_mapName2SpriteID.end())
|
||
{
|
||
log_err("精灵名字已存在:{}", name);
|
||
return false;
|
||
}
|
||
|
||
//
|
||
size_t id_tex;
|
||
size_t id_rect;
|
||
|
||
// 旋转精灵使w更大
|
||
bool right_angle = false;
|
||
{
|
||
Image img_r;
|
||
if (img->GetHeight() > img->GetWidth())
|
||
{
|
||
img_r = Image::RotateRightAngle1(*img);
|
||
img = &img_r;
|
||
right_angle = true;
|
||
}
|
||
if (!_imp->_reg_image(img, SIZE_SPRITE_BORDER, id_tex, id_rect))
|
||
{
|
||
log_err0("注册图像失败!");
|
||
return false;
|
||
}
|
||
}
|
||
|
||
|
||
// 创建 sprite_id
|
||
std::vector<SpriteID>& vec_spr_id = _imp->_mapName2SpriteID[std::string{ name }];
|
||
SpriteID& spr_id = Select::CreateIfEmpty(vec_spr_id, 0);
|
||
spr_id._tex = id_tex;
|
||
spr_id._rect = id_rect;
|
||
|
||
//{纹理id,区域id} -> { SpriteInfo }
|
||
FactoryImp::SpriteInfo& info = Select::CreateIfEmpty(
|
||
_imp->_allSpriteInfo, id_tex, id_rect);
|
||
|
||
RectU rect = _imp->_get_rect(id_tex, id_rect);
|
||
info._rect = createRectU({}, Align::GetSize(rect));
|
||
_imp->_rect_to_uv(rect, info._uv, right_angle);
|
||
info._anchor = anchor;
|
||
info._color = ColorDef::WHITE;
|
||
info._bRightAngle = right_angle;
|
||
|
||
return true;
|
||
}
|
||
|
||
bool Factory::HasSprite(std::string_view name)
|
||
{
|
||
auto iter = _imp->_mapName2SpriteID.find(std::string{ name });
|
||
return iter != _imp->_mapName2SpriteID.end();
|
||
}
|
||
|
||
std::vector<gcSprite> Factory::CreateSpriteMulti(std::string_view name, size_t num /*= 0*/, size_t index /*= 0*/)
|
||
{
|
||
auto iter = _imp->_mapName2SpriteID.find(std::string{ name });
|
||
if (iter == _imp->_mapName2SpriteID.end())
|
||
{
|
||
log_err("SpriteSheet不存在:{}", name);
|
||
return {};
|
||
}
|
||
|
||
std::vector<SpriteID>& all_id = iter->second;
|
||
if (num == 0)
|
||
num = all_id.size();
|
||
|
||
std::vector<gcSprite> ret;
|
||
ret.resize(num);
|
||
for (size_t i = 0; i < num; ++i)
|
||
{
|
||
ret[i] = CreateSprite(all_id[i]);
|
||
}
|
||
return ret;
|
||
}
|
||
|
||
|
||
|
||
gcSprite Factory::CloneSprite(gcSprite& spr)
|
||
{
|
||
auto ret = get_gc<Sprite>(*(spr.operator->()));
|
||
//如果是拥有Coor,则需要深拷贝
|
||
if (ret->_bOwnCoor)
|
||
ret->_coor = spr->_coor->Clone();
|
||
|
||
return ret;
|
||
}
|
||
|
||
Size Factory::GetSpriteTexSize(const SpriteID &spr_id)
|
||
{
|
||
FactoryImp::SpriteInfo* spr_info = _imp->_get_sprite_info(spr_id);
|
||
if (!spr_info)
|
||
{
|
||
log_err0("返回精灵信息失败!");
|
||
return toSizeNeg2Zero(SIZE_DEFAULT_SPRITE);
|
||
}
|
||
return Align::GetSize(spr_info->_rect);
|
||
}
|
||
|
||
|
||
std::string Factory::GetSpriteName(const SpriteID& spr_id)
|
||
{
|
||
for (auto& iter : _imp->_mapName2SpriteID)
|
||
{
|
||
for (SpriteID& iter1 : iter.second)
|
||
{
|
||
if (iter1._tex == spr_id._tex
|
||
&& iter1._rect == spr_id._rect)
|
||
{
|
||
return iter.first;
|
||
}
|
||
}
|
||
}
|
||
return "error";
|
||
}
|
||
|
||
size_t Factory::LoadFont(std::string_view path_name)
|
||
{
|
||
return g_freetype->LoadFace(path_name);
|
||
}
|
||
|
||
size_t Factory::GetFontSize()
|
||
{
|
||
return g_freetype->GetFontSize();
|
||
}
|
||
|
||
|
||
gcText Factory::CreateText(size_t font_id /*= 0*/,
|
||
unsigned font_size, const Color& col,
|
||
unsigned font_outline, const Color& col_outline,
|
||
unsigned font_shadow, const Color& col_shadow)
|
||
{
|
||
auto txt = get_gc<Text>();
|
||
|
||
if (font_id >= g_freetype->GetFontSize())
|
||
{
|
||
log_err0("字体id越界,将使用0号!");
|
||
assert(font_id);
|
||
font_id = 0;
|
||
}
|
||
|
||
txt->_fontId = font_id;
|
||
txt->_fontSize[TextParam::NORMAL] = font_size;
|
||
txt->_fontSize[TextParam::OUTLINE] = font_outline;
|
||
txt->_fontSize[TextParam::SHADOW] = font_shadow;
|
||
txt->_fontSizeReal = txt->_fontSize;
|
||
txt->_col[TextParam::NORMAL] = col;
|
||
txt->_col[TextParam::OUTLINE] = col_outline;
|
||
txt->_col[TextParam::SHADOW] = col_shadow;
|
||
txt->_coor = Coor::Create();
|
||
|
||
return txt;
|
||
}
|
||
|
||
|
||
CharImage* Factory::GetChar(const CharInfo& info)
|
||
{
|
||
// 缓存工作由CreateSpriteChar完成
|
||
return g_freetype->GetChar(info);
|
||
}
|
||
|
||
float Factory::CreateSpriteChar(const CharInfo& info, gcSprite& spr, gcSprite& spr_outline)
|
||
{
|
||
auto fn_failed = [&]()
|
||
{
|
||
spr = CreateSpriteDefault();
|
||
spr->SetQuad(createQuad(info._size, false));
|
||
|
||
spr_outline = CreateSpriteDefault();
|
||
spr_outline->SetQuad(createQuad(info._size, false));
|
||
};
|
||
|
||
if (info._font >= g_freetype->GetFontSize())
|
||
{
|
||
log_err("字体id不存在:{}", info._font);
|
||
fn_failed();
|
||
return 0;
|
||
}
|
||
|
||
if (info._size == 0)
|
||
{
|
||
log_err0("字体大小不能为0!");
|
||
fn_failed();
|
||
return 0;
|
||
}
|
||
|
||
// 排除控制字符
|
||
if ((info._ch >= 0 && info._ch <= 31)
|
||
|| info._ch == 127)
|
||
{
|
||
fn_failed();
|
||
return 0;
|
||
}
|
||
|
||
FactoryImp::CharSprite& char_spr = _imp->_hashCharImage[info];
|
||
FactoryImp::CharSprite::Data& d0 = char_spr._data[0];
|
||
FactoryImp::CharSprite::Data& d1 = char_spr._data[1];
|
||
RectU rect0;
|
||
RectU rect1;
|
||
// 注册图像(普通和描边一起注册)
|
||
if (d0._idTex == 0)
|
||
{
|
||
CharImage* char_img = g_freetype->GetChar(info);
|
||
if (char_img == nullptr)
|
||
{
|
||
log_err0("GetChar失败!");
|
||
fn_failed();
|
||
return 0;
|
||
}
|
||
|
||
char_spr._advance = char_img->_advance;
|
||
char_spr._anchor = { -char_img->_bearingX, char_img->_bearingY };
|
||
|
||
//0
|
||
if (!_imp->_reg_image(char_img->_image, 1, d0._idTex, d0._idRect))
|
||
{
|
||
delete char_img;
|
||
log_err0("注册图像失败!");
|
||
fn_failed();
|
||
return 0;
|
||
}
|
||
rect0 = _imp->_get_rect(d0._idTex, d0._idRect);
|
||
_imp->_rect_to_uv(rect0, d0._uv);
|
||
|
||
//1
|
||
if (info._outline > 0)
|
||
{
|
||
if (!_imp->_reg_image(char_img->_imageOutline, 1, d1._idTex, d1._idRect))
|
||
{
|
||
delete char_img;
|
||
log_err0("注册图像(描边)失败!");
|
||
fn_failed();
|
||
return 0;
|
||
}
|
||
rect1 = _imp->_get_rect(d1._idTex, d1._idRect);
|
||
_imp->_rect_to_uv(rect1, d1._uv);
|
||
}
|
||
|
||
delete char_img;
|
||
}
|
||
else
|
||
{
|
||
rect0 = _imp->_get_rect(d0._idTex, d0._idRect);
|
||
if (info._outline > 0)
|
||
{
|
||
rect1 = _imp->_get_rect(d1._idTex, d1._idRect);
|
||
}
|
||
}
|
||
|
||
//0
|
||
spr = MemoryPool::GetGC<Sprite>();
|
||
|
||
spr->SetColor(ColorDef::WHITE);
|
||
spr->_id = { d0._idTex, d0._idRect};
|
||
spr->_quad = createQuad(Align::GetSize(rect0), false)
|
||
- char_spr._anchor;//偏移锚点
|
||
spr->_z = Z_DEFAULT;
|
||
for (int i = 0; i != 4; ++i)
|
||
spr->_uv[i] = d0._uv[i];
|
||
|
||
//1
|
||
if (info._outline > 0)
|
||
{
|
||
spr_outline = MemoryPool::GetGC<Sprite>();
|
||
|
||
spr_outline->SetColor(ColorDef::WHITE);
|
||
spr_outline->_id = { d1._idTex, d1._idRect };
|
||
spr_outline->_quad = createQuad(Align::GetSize(rect1), false)
|
||
- char_spr._anchor;//偏移锚点
|
||
spr_outline->_z = Z_DEFAULT;
|
||
for (int i = 0; i != 4; ++i)
|
||
spr_outline->_uv[i] = d1._uv[i];
|
||
}
|
||
|
||
return char_spr._advance;
|
||
}
|
||
|
||
dl::Coor* Factory::GetRootCoor(size_t i)
|
||
{
|
||
return g_vk->GetRootCoor(i);
|
||
}
|
||
|
||
void Factory::AddColor(std::string_view name, const Color& col)
|
||
{
|
||
_hashTagColor[std::string{ name }] = col;
|
||
}
|
||
|
||
|
||
Color Factory::GetColor(std::string_view name)
|
||
{
|
||
if (name.size() == 10
|
||
&& name[0] == '0'
|
||
&& name[1] == 'x')
|
||
{//尝试十六进制
|
||
return createColor(name);
|
||
}
|
||
|
||
auto iter = _hashTagColor.find(std::string{ name });
|
||
if (iter == _hashTagColor.end())
|
||
{
|
||
log_err("Tag颜色查找失败:{}", name);
|
||
return ColorDef::WHITE;
|
||
}
|
||
else
|
||
return iter->second;
|
||
}
|
||
|
||
std::optional<Color> Factory::GetColorCheck(std::string_view name)
|
||
{
|
||
auto iter = _hashTagColor.find(std::string{ name });
|
||
if (iter == _hashTagColor.end())
|
||
{
|
||
return std::nullopt;
|
||
}
|
||
else
|
||
return iter->second;
|
||
}
|
||
|
||
|
||
void Factory::ExportTexture2D()
|
||
{
|
||
for(size_t i = 0; i < g_vk->GetCanvasSize(); ++i)
|
||
{
|
||
VK::Canvas* canvas = g_vk->GetCanvas(i);
|
||
std::string str = fmt::format("{}{}.png", _strPathTemp, i);
|
||
g_vk->ExportTexture(canvas->_texture, str);
|
||
}
|
||
}
|
||
|
||
|
||
void Factory::_render_sprite(Sprite* spr)
|
||
{
|
||
const SpriteID& id = g_factory->GetImp()->_idTrans;
|
||
VK::Canvas* canvas = g_vk->GetCanvas(spr->_id._tex);
|
||
assert(canvas);
|
||
|
||
if (spr->_id._rect == -1
|
||
|| !spr->IsColorOne()
|
||
|| (spr->_id._tex >= id._tex))
|
||
{ //可能是半透明
|
||
canvas->_allSpriteTrans.push_back(spr);
|
||
}
|
||
else
|
||
canvas->_allSprite.push_back(spr);
|
||
}
|
||
|
||
struct ColorTag
|
||
{
|
||
char _name[32];
|
||
uint32_t _color;
|
||
};
|
||
|
||
void Factory::LoadColorCsv(std::string_view name)
|
||
{
|
||
assert(0);
|
||
/*std::vector<ColorTag> all;
|
||
CsvFile::Deserialize(name, all);
|
||
|
||
for (auto& iter : all)
|
||
{
|
||
AddColor(iter._name, ABGR::CreateColor(iter._color));
|
||
}*/
|
||
}
|
||
|
||
|
||
void Factory::DeleteBinary(bool b_all, bool b_2d, bool b_3d)
|
||
{
|
||
if (!_bSetPath)
|
||
{
|
||
log_err0("尚未指定输出目录!");
|
||
return;
|
||
}
|
||
if (b_all)
|
||
File::DeleteContent(GetPathBinary());
|
||
else
|
||
{
|
||
if (b_2d)
|
||
File::DeleteContent(GetPathBinary2D());
|
||
if (b_3d)
|
||
File::DeleteContent(GetPathBinary3D());
|
||
}
|
||
}
|
||
|
||
constexpr std::string_view NAME_CACHE_MODEL = "model.cache";
|
||
|
||
void Factory::_init_path()
|
||
{
|
||
if (!_bSetPath)
|
||
{
|
||
SetPath(
|
||
File::PathCurrent(),
|
||
File::PathCurrent(),
|
||
File::PathStorage(),
|
||
File::PathTemp());
|
||
}
|
||
// File::CreateFolder(File::PathCurrent());
|
||
// File::CreateFolder(File::PathStorage());
|
||
// File::CreateFolder(File::PathTemp());
|
||
// File::CreateFolder(File::PathPrivate());
|
||
File::CreateFolder(_strPathImage);
|
||
File::CreateFolder(_strPathModel);
|
||
File::CreateFolder(_strPathVoice);
|
||
File::CreateFolder(_strPathBinary);
|
||
File::CreateFolder(_strPathTemp);
|
||
File::CreateFolder(GetPathBinary2D());
|
||
File::CreateFolder(GetPathBinary3D());
|
||
|
||
// 因为每个模型单独存放,不会合并,所以算法不一样
|
||
// 针对每一个模型文件,缓存 效验值、中间文件路径
|
||
// 如果效验值不同,则生成中间文件,并更新效验值
|
||
_imp->_modelCache.Load(GetPathBinary3D() + NAME_CACHE_MODEL);
|
||
|
||
// 合并大图纹理,生成Canvas
|
||
_load_sprite();
|
||
}
|
||
|
||
void Factory::_init_defualt_res()
|
||
{
|
||
//先使用一下,保证gcSprite后于gcText析构
|
||
gcSprite spr = CreateSpriteDefault();
|
||
spr->SetColor(ColorDef::RED);
|
||
|
||
|
||
//默认颜色
|
||
AddColor("red", ColorDef::RED);
|
||
AddColor("green", ColorDef::GREEN);
|
||
AddColor("blue", ColorDef::BLUE);
|
||
AddColor("white", ColorDef::WHITE);
|
||
AddColor("black", ColorDef::BLACK);
|
||
AddColor("yellow", ColorDef::YELLOW);
|
||
AddColor("purple", ColorDef::PURPLE);
|
||
AddColor("cyan", ColorDef::CYAN);
|
||
|
||
//默认字体
|
||
LoadFont("dl/default_font");
|
||
|
||
//-------------默认模型-------------------
|
||
if (false)
|
||
{
|
||
//加载model_object
|
||
ModelObject* model_object = new ModelObject;
|
||
model_object->Load("dl/default_model");
|
||
//model_object -> model
|
||
Model* model = g_vk->CreateModel(model_object);
|
||
delete model_object;
|
||
assert(model);
|
||
|
||
size_t id = g_vk->GetMulModelSize();
|
||
_imp->_mapName2Model[":"] = id;
|
||
std::vector<Model*> vec_model{ model };
|
||
g_vk->AddMulModel(vec_model);
|
||
}
|
||
}
|
||
|
||
|
||
void FactoryImp::_rect_to_uv(const RectU& rect, UV* uv, bool right_angle)
|
||
{
|
||
using namespace Align;
|
||
Position4 ltrb;
|
||
for (int i = 0; i != 4; ++i)
|
||
ltrb[i] = rect[i] / (Float)SIZE_TEXTURE_2D;
|
||
|
||
if (!right_angle)
|
||
{
|
||
uv[(size_t)Corner::LT] = GetLT(ltrb);
|
||
uv[(size_t)Corner::RT] = GetRT(ltrb);
|
||
uv[(size_t)Corner::RB] = GetRB(ltrb);
|
||
uv[(size_t)Corner::LB] = GetLB(ltrb);
|
||
}
|
||
else
|
||
{
|
||
uv[(size_t)Corner::LT] = GetRT(ltrb);
|
||
uv[(size_t)Corner::RT] = GetRB(ltrb);
|
||
uv[(size_t)Corner::RB] = GetLB(ltrb);
|
||
uv[(size_t)Corner::LB] = GetLT(ltrb);
|
||
}
|
||
|
||
/*for (int i = 0; i != 4; ++i)
|
||
uv[i][1] = 1.0f - uv[i][1];*/
|
||
}
|
||
|
||
constexpr uint32_t VERSION = 1;
|
||
void FactoryImp::_save_sprite_info(std::string_view path_name)
|
||
{
|
||
StreamOutput s;
|
||
|
||
s.Write(&VERSION);
|
||
|
||
s.Write(&_idTrans);
|
||
s.Write(&_idSolid);
|
||
s.Write(&_idSolidTrans);
|
||
|
||
s.Write(&_allSpriteInfo);
|
||
s.Write(&_mapName2SpriteID);
|
||
|
||
s.Save(path_name);
|
||
}
|
||
|
||
|
||
bool FactoryImp::_load_sprite_info(std::string_view path_name)
|
||
{
|
||
StreamInput s;
|
||
if (!s.LoadFromFile(path_name))
|
||
return false;
|
||
|
||
uint32_t version;
|
||
s.Read(&version);
|
||
if (version != VERSION)
|
||
return false;
|
||
|
||
s.Read(&_idTrans);
|
||
s.Read(&_idSolid);
|
||
s.Read(&_idSolidTrans);
|
||
|
||
s.Read(&_allSpriteInfo);
|
||
s.Read(&_mapName2SpriteID);
|
||
|
||
return true;
|
||
}
|
||
|
||
ModelAnimationInstance* FactoryImp::_create_model_bone_animation(std::string_view name)
|
||
{
|
||
auto iter = _mapName2Model.find(std::string{ name });
|
||
if (iter == _mapName2Model.end())
|
||
{
|
||
log_err("未知模型名称: {}", name);
|
||
return nullptr;
|
||
}
|
||
//现在只有一个model
|
||
std::vector<Model*>& mul_model = g_vk->GetMulModel(iter->second);
|
||
//assert(mul_model.size() == 1);
|
||
Model* model = mul_model[0];
|
||
if (!model->_modelData)
|
||
return nullptr;
|
||
ModelData* bone_data = model->_modelData;
|
||
//存在骨骼动画,则生成实例
|
||
if (bone_data->_allAnimation.empty())
|
||
{
|
||
log_warn("模型没有任何动画,但存在骨骼绑定:{}", name);
|
||
return nullptr;
|
||
}
|
||
ModelAnimationInstance* ret = new ModelAnimationInstance;
|
||
ret->_skinndeData = bone_data;
|
||
//ret->_finalTrans.resize(bone_data->_allBoneOffset.size(), Mat::CreateIdentity());
|
||
//ret->_skinndeData->_root2Model);
|
||
//ret->_clipName = bone_data->_allAnimation.begin()->first;
|
||
ret->_id = g_vk->GetUboBoneFree();
|
||
if (ret->_id == -1)
|
||
{
|
||
return nullptr;
|
||
}
|
||
g_vk->SetUboBoneUse(ret->_id);
|
||
return ret;
|
||
}
|
||
|
||
|
||
|
||
constexpr PointU SPRITE_EXTEND_XY = { SIZE_SPRITE_BORDER, SIZE_SPRITE_BORDER };
|
||
constexpr Size SPRITE_EXTEND_SIZE = { SIZE_SPRITE_BORDER * 2, SIZE_SPRITE_BORDER * 2 };
|
||
|
||
bool FactoryImp::_reg_image(Image* image_src, unsigned border, size_t& id_tex, size_t& id_rect)
|
||
{
|
||
RectU rect;
|
||
// 扩展图像
|
||
Size size = image_src->GetSize() + toLonger(border * 2);
|
||
Image* image = createImage(size, ColorDef::NONE);
|
||
Img::AddImageRect(image, image_src, createRectU(image_src->GetSize()), toLonger(border));
|
||
Img::BuildBorder(image, border);
|
||
bool b_add = false;
|
||
for (size_t i = 0; i < _allTexPack.size(); ++i)
|
||
{
|
||
if (_allTexPack[i].Add(size, rect))
|
||
{
|
||
b_add = true;
|
||
id_tex = _numTexStatic + i;
|
||
id_rect = _allTexRect[i].size();
|
||
|
||
_allTexRect[i].push_back(Align::Shrink(std::as_const(rect), border));
|
||
break;
|
||
}
|
||
}
|
||
|
||
if (!b_add)
|
||
{//分配一个新的
|
||
TexPack tex_pack;
|
||
tex_pack.Reset({ SIZE_TEXTURE_2D, SIZE_TEXTURE_2D });
|
||
if (!tex_pack.Add(size, rect))
|
||
{
|
||
log_err0("注册图像失败!可能是图像太大。需要小于SIZE_TEXTURE_2D。");
|
||
return false;
|
||
}
|
||
id_tex = _numTexStatic + _allTexPack.size();
|
||
id_rect = 0;
|
||
_allTexPack.push_back(tex_pack);
|
||
_allTexRect.push_back({ Align::Shrink(std::as_const(rect), border) });
|
||
|
||
std::array<Image*, NUM_MIPMAP_2D> vec_image;
|
||
unsigned size_big = SIZE_TEXTURE_2D;
|
||
for (size_t i = 0; i < vec_image.size(); ++i)
|
||
{
|
||
vec_image[i] = createImage(toLonger(size_big), ColorDef::NONE);
|
||
size_big >>= 1;
|
||
assert(size_big);
|
||
}
|
||
g_vk->CreateCanvas(id_tex, vec_image);
|
||
for (size_t i = 0; i < vec_image.size(); ++i)
|
||
{
|
||
delete vec_image[i];
|
||
}
|
||
}
|
||
|
||
Texture tex = g_vk->GetCanvas(id_tex)->_texture;
|
||
|
||
g_vk->UpdateTexture2D(tex, Align::GetLT(rect),
|
||
image, createRectU(image->GetSize()));
|
||
|
||
delete image;
|
||
return true;
|
||
}
|
||
|
||
|
||
void Factory::_save_cache()
|
||
{
|
||
if(!_imp->_modelCache.Empty())
|
||
_imp->_modelCache.Save(GetPathBinary3D() + NAME_CACHE_MODEL);
|
||
}
|
||
|
||
void Factory::_load_sprite()
|
||
{
|
||
assert(_bSetPath);
|
||
// cache目录创建
|
||
const std::string PATH_CACHE = GetPathBinary2D();
|
||
File::CreateFolder(PATH_CACHE);
|
||
|
||
|
||
// 如果文件没有修改(或发布模式),则尝试从out目录加载纹理
|
||
if (_bUseBinary
|
||
|| !File::CheckPathFileModified(_strPathImage, PATH_CACHE + "file.cache", true))
|
||
{
|
||
if (_imp->_load_sprite_info(PATH_CACHE + "sprite.cache"))
|
||
{//加载成功,才不进行后面的注册操作
|
||
size_t tex_size = _imp->_allSpriteInfo.size();
|
||
|
||
for (size_t i = 0; i != tex_size; ++i)
|
||
{
|
||
bool fail = false;
|
||
std::array<Image*, NUM_MIPMAP_2D> vec_image;
|
||
for (size_t j = 0; j < vec_image.size(); ++j)
|
||
{
|
||
std::string tex_path = fmt::format("{}{}_{}.png", PATH_CACHE, i, j);
|
||
vec_image[j] = createImage(tex_path);
|
||
if (vec_image[j] == nullptr)
|
||
{
|
||
log_err("纹理加载失败:{}", tex_path);
|
||
fail = true;
|
||
break;
|
||
}
|
||
}
|
||
if (!fail)
|
||
{
|
||
//创建纹理资源(创建Canvas,并创建纹理)
|
||
g_vk->CreateCanvas(i, vec_image);
|
||
}
|
||
for (size_t j = 0; j < vec_image.size(); ++j)
|
||
{
|
||
delete vec_image[j];
|
||
}
|
||
}
|
||
log_msg("从缓存目录读取2d资源完成:{}", PATH_CACHE);
|
||
_imp->_numTexStatic = tex_size;//记录2d静态纹理数量
|
||
return;
|
||
}
|
||
if (_bUseBinary)
|
||
{
|
||
log_err("从缓存目录读取2d资源失败:{}", PATH_CACHE);
|
||
return;
|
||
}
|
||
}
|
||
|
||
// 遍历所有图像
|
||
std::vector<std::string> mul_file;
|
||
File::GetPathFileAll(_strPathImage, mul_file, ".(png|jpg|jpeg|bmp)$");
|
||
|
||
std::list<FactoryImp::SheetNode> list_sheet_node_normal;
|
||
std::list<FactoryImp::SheetNode> list_sheet_node_trans;
|
||
|
||
for (std::string& path_name : mul_file)
|
||
{
|
||
log_("开始加载文件:{}", path_name);
|
||
//0.image
|
||
Image* image = createImage(path_name);
|
||
if (!image)
|
||
continue;
|
||
//1.meta
|
||
std::string meta_name = path_name;
|
||
String::ReplaceExtension(meta_name, "json");
|
||
|
||
struct ParamSheet
|
||
{
|
||
struct Node
|
||
{
|
||
std::string _anchor;
|
||
std::string _color;
|
||
};
|
||
|
||
Size _split;
|
||
std::string _anchor;//公共锚点
|
||
std::unordered_map<std::size_t, Node> _allSprite;//精灵单独配置
|
||
ParamSheet() :
|
||
_split{ 1, 1 },
|
||
_anchor{}
|
||
{}
|
||
};
|
||
ParamSheet _paramSheet;
|
||
|
||
std::ifstream ifs = File::Get(meta_name);
|
||
if (ifs.is_open())
|
||
{
|
||
json j = json::parse(ifs);
|
||
Json::DisableLog l;
|
||
Json::Get(j, "split", _paramSheet._split);//分割
|
||
Json::Get(j, "anchor", _paramSheet._anchor);//锚点
|
||
//子元素信息
|
||
for (unsigned y = 0; y < _paramSheet._split[1]; ++y)
|
||
for (unsigned x = 0; x < _paramSheet._split[0]; ++x)
|
||
{
|
||
size_t index = (size_t)(y * _paramSheet._split[0] + x);
|
||
ParamSheet::Node node;
|
||
json j_spr;
|
||
Json::Get(j, "sprite_" + to_string(index), j_spr);//独立信息
|
||
if (j_spr.empty())
|
||
continue;
|
||
Json::Get(j_spr, "anchor", _paramSheet._allSprite[index]._anchor);//锚点
|
||
Json::Get(j_spr, "color", _paramSheet._allSprite[index]._color);//颜色
|
||
}
|
||
}
|
||
Size wh = image->GetSize() / _paramSheet._split;//单图大小
|
||
Point anchor_pub = Align::Anchor2Point(wh, _paramSheet._anchor);//公用锚点
|
||
|
||
// 2.record
|
||
unsigned index = 0;
|
||
for (unsigned y = 0; y < _paramSheet._split[1]; ++y)
|
||
{
|
||
for (unsigned x = 0; x < _paramSheet._split[0]; ++x)
|
||
{
|
||
FactoryImp::SheetNode img_rect;
|
||
img_rect._pathName = path_name;
|
||
img_rect._rect = createRectU(PointU{ x * wh[0], y * wh[1] }, wh);
|
||
img_rect._index = index;
|
||
|
||
//如果自己有专门配置的锚点,则优先使用
|
||
auto iter = _paramSheet._allSprite.find(index);
|
||
if (iter == _paramSheet._allSprite.end())
|
||
{
|
||
img_rect._anchor = anchor_pub;
|
||
}
|
||
else
|
||
{
|
||
ParamSheet::Node& node = iter->second;
|
||
img_rect._anchor = Align::Anchor2Point(wh, node._anchor);
|
||
}
|
||
|
||
PointU lt = Align::GetLT(img_rect._rect);
|
||
//去透明空白部分
|
||
Img::CalcLeastRect(image, img_rect._rect);
|
||
//更新锚点
|
||
img_rect._anchor -= toPoint(Align::GetLT(img_rect._rect) - lt);
|
||
//是否含有半透明颜色
|
||
bool is_have_translucent = Img::IsHaveTranslucent(image, img_rect._rect);
|
||
if (is_have_translucent)
|
||
list_sheet_node_trans.push_back(img_rect);
|
||
else
|
||
list_sheet_node_normal.push_back(img_rect);
|
||
|
||
//即使空白,还是要自增下标
|
||
++index;
|
||
}
|
||
}
|
||
delete image;
|
||
}
|
||
//特殊精灵
|
||
list_sheet_node_normal.push_back({ ":", 0, createRectU(SIZE_SPRITE_DEFAULT), {} });
|
||
list_sheet_node_trans.push_back({ ":", 0, createRectU(SIZE_SPRITE_DEFAULT), {} });
|
||
|
||
//3.合并图集
|
||
TexturePack::Static pack;
|
||
pack.SetSize(SIZE_TEXTURE_2D_SIZE);
|
||
size_t pack_id = 0;//当前操作图集id
|
||
|
||
//tex id -> nrit
|
||
std::vector<std::list<FactoryImp::SheetNodeTarget>> all_snt;
|
||
|
||
//获得大小(扩展像素)
|
||
auto fn_get_size = [](const FactoryImp::SheetNode& nri) {
|
||
return Align::GetSize(nri._rect) + SPRITE_EXTEND_SIZE;
|
||
};
|
||
//成功加入操作
|
||
auto fn_call_back = [&](const FactoryImp::SheetNode& nri, const PointU& lt) {
|
||
// rect未变,lt为扩展后位置
|
||
all_snt[pack_id].push_back({nri, lt});
|
||
};
|
||
//直到全部添加
|
||
while (!list_sheet_node_normal.empty())
|
||
{
|
||
all_snt.push_back({});
|
||
pack.Calc(list_sheet_node_normal, fn_get_size, fn_call_back);
|
||
++pack_id;
|
||
}
|
||
//记录id
|
||
_imp->_idTrans._tex = pack_id;
|
||
_imp->_idTrans._rect = 0;//all_snt.back().size()
|
||
//直到全部添加
|
||
while (!list_sheet_node_trans.empty())
|
||
{
|
||
all_snt.push_back({});
|
||
pack.Calc(list_sheet_node_trans, fn_get_size, fn_call_back);
|
||
++pack_id;
|
||
}
|
||
//4.创建纹理
|
||
size_t id_tex = 0;
|
||
size_t index_special = 0;//特殊精灵标记
|
||
for (auto& iter : all_snt)
|
||
{
|
||
// 整个大图 包含mipmap
|
||
std::array<Image*, NUM_MIPMAP_2D> vec_image_big;
|
||
unsigned size_big = SIZE_TEXTURE_2D;
|
||
for (size_t i = 0; i < vec_image_big.size(); ++i)
|
||
{
|
||
vec_image_big[i] = createImage(toLonger(size_big), ColorDef::NONE);
|
||
size_big >>= 1;
|
||
assert(size_big);
|
||
}
|
||
size_t id_rect = 0;
|
||
for (FactoryImp::SheetNodeTarget& snt : iter)
|
||
{
|
||
Image* image = nullptr;
|
||
bool b_reg_special = false;//是否以特殊精灵创建
|
||
if (snt._sheetNode._pathName == ":")
|
||
{//纯色精灵
|
||
image = createImage(SIZE_SPRITE_DEFAULT + SPRITE_EXTEND_SIZE,
|
||
ColorDef::WHITE);
|
||
b_reg_special = true;
|
||
if (index_special == 0)
|
||
{//第一个为不透明纯色
|
||
_imp->_idSolid = { id_tex, id_rect };
|
||
}
|
||
else if (index_special == 1)
|
||
{//第二个为透明纯色
|
||
_imp->_idSolidTrans = { id_tex, id_rect };
|
||
}
|
||
++index_special;
|
||
}
|
||
else
|
||
{
|
||
Image* image_src = createImage(snt._sheetNode._pathName);
|
||
Size size = Align::GetSize(snt._sheetNode._rect) + SPRITE_EXTEND_SIZE;
|
||
image = createImage(size, ColorDef::NONE);
|
||
Img::AddImageRect(image, image_src, snt._sheetNode._rect, SPRITE_EXTEND_XY);
|
||
Img::BuildBorder(image, SIZE_SPRITE_BORDER);
|
||
delete image_src;
|
||
}
|
||
assert(image);// image现在为处理后的小图
|
||
// 加入到大图
|
||
constexpr unsigned EDGE = 1;
|
||
for (size_t i = 0; i < vec_image_big.size(); ++i)
|
||
{
|
||
if (i == 0)
|
||
Img::AddImageRect(vec_image_big[i], image, createRectU(image->GetSize()), snt._lt);
|
||
else
|
||
{
|
||
Float scale = 1.0f / Math::Pow(2u, (unsigned)i);
|
||
Size size = image->GetSize() / Math::Pow(2u, (unsigned)i);
|
||
Every::ClampFloor(size, 1u);
|
||
RectU rect = toSize(toPosition(createRectU(image->GetSize())) * scale);
|
||
PointU lt = toSize(toPosition(snt._lt) * scale);
|
||
|
||
Image* img_scale = Img::ResizeImage(image, size);
|
||
assert(img_scale);
|
||
Img::AddImageRect(vec_image_big[i], img_scale, rect, lt);
|
||
delete img_scale;
|
||
}
|
||
}
|
||
//--------------------记录Rect到Factory的_vecRectInfo----------------
|
||
//名字转换
|
||
std::string name;
|
||
if (!b_reg_special)
|
||
{//不是默认纯色精灵才变
|
||
name = String::GetResName(_strPathImage, snt._sheetNode._pathName);
|
||
}
|
||
else
|
||
name = snt._sheetNode._pathName;
|
||
|
||
//取得图像named的 所有SpriteID
|
||
//同一图像的子图像会注册到同一SpriteID列表,但是由于注册顺序的不同,需要按拆分时的编号写入
|
||
std::vector<SpriteID>& vec_spr_id = _imp->_mapName2SpriteID[std::string{ name }];
|
||
SpriteID& spr_id = Select::CreateIfEmpty(vec_spr_id, size_t(snt._sheetNode._index));
|
||
spr_id._tex = id_tex;
|
||
spr_id._rect = id_rect;
|
||
|
||
//{纹理id,区域id} -> { SpriteInfo }
|
||
FactoryImp::SpriteInfo& info = Select::CreateIfEmpty(
|
||
_imp->_allSpriteInfo, id_tex, id_rect);
|
||
|
||
snt._lt += SPRITE_EXTEND_XY;// 还原到图像扩展之前位置
|
||
info._rect = createRectU(snt._lt, Align::GetSize(snt._sheetNode._rect));
|
||
_imp->_rect_to_uv(info._rect, info._uv);
|
||
info._anchor = snt._sheetNode._anchor;
|
||
info._color = ColorDef::WHITE;
|
||
|
||
delete image;
|
||
++id_rect;
|
||
}
|
||
for (size_t i = 0; i < vec_image_big.size(); ++i)
|
||
{
|
||
saveImage(vec_image_big[i], fmt::format("{}{}_{}.png", PATH_CACHE, id_tex, i));
|
||
}
|
||
|
||
//创建vk资源
|
||
g_vk->CreateCanvas(id_tex, vec_image_big);
|
||
for (size_t i = 0; i < vec_image_big.size(); ++i)
|
||
{
|
||
delete vec_image_big[i];
|
||
}
|
||
++id_tex;
|
||
}
|
||
_imp->_save_sprite_info(PATH_CACHE + "sprite.cache");
|
||
log_msg("读取2d资源从:{},并生成到:{}", _strPathImage, PATH_CACHE);
|
||
_imp->_numTexStatic = id_tex;//记录2d静态纹理数量
|
||
}
|
||
Factory::Factory() :
|
||
_bSetPath{ false },
|
||
_bUseBinary{ false },
|
||
_idTemp{0}
|
||
{
|
||
_imp = new FactoryImp;
|
||
}
|
||
|
||
Factory::~Factory()
|
||
{
|
||
_save_cache();
|
||
delete _imp;
|
||
}
|
||
|
||
}
|
||
#endif |