My Game --文件读取数据

时间:2022-06-11 13:05:31

My Game --线段数据 中说到背景的绘制由贝赛尔曲线生成线段,用 DrawNode 画多边形,同时一张背景有两座山,一座山有两条以上贝赛尔曲线保存,用了嵌套的数据类:Bezier,LineLayer,BgLayerData 这个做也是为了方便从文件读取数据

把背景的数据放在文件里方便修改,也可以做个工具快速绘制背景,下面是这个背景的数据保存的XML文件:

 <RootLayer>
<Layers>
<layer>
<Beziers>
<Bezier bx="0.375" by="0.000" ex="1.000" ey="0.500" c1x="0.750" c1y="1.000" c2x="0.850" c2y="0.875"/>
<Bezier bx="0.375" by="0.500" ex="1.000" ey="0.650" c1x="1.000" c1y="0.400" c2x="0.750" c2y="0.750"/>
<Bezier bx="0.375" by="0.125" ex="1.000" ey="0.375" c1x="0.800" c1y="0.130" c2x="0.700" c2y="0.375"/>
</Beziers>
<Colors>
<color r="0.200" g="0.439" b="0.200" a="1"/>
<color r="0.196" g="0.529" b="0.251" a="1"/>
<color r="0.133" g="0.675" b="0.220" a="1"/>
</Colors>
</layer>
<layer>
<Beziers>
<Bezier bx="0.000" by="0.125" ex="0.750" ey="0.000" c1x="0.250" c1y="0.750" c2x="0.375" c2y="0.750"/>
<Bezier bx="0.000" by="0.250" ex="0.750" ey="0.500" c1x="0.375" c1y="0.250" c2x="0.375" c2y="0.500"/>
</Beziers>
<Colors>
<color r="0.255" g="0.647" b="0.310" a="1"/>
<color r="0.000" g="0.600" b="0.267" a="1"/>
</Colors>
</layer>
</Layers>
</RootLayer>

每个 Layer 下两组元素:贝赛尔曲线和对应的对应的颜色

Resources 下的 ResourcesManage 类读取文件内容,并生存相应的数据结构存储起来,方便使用

读取数据的代码:

BgLayerData * ResourcesManage::getBgLayerDataFromFile( std::string && fileName )
{
tinyxml2::XMLDocument doc;
doc.LoadFile( fileName.c_str( ) );
auto elemRoot = doc.RootElement( );
auto layers = elemRoot->FirstChildElement( "Layers" );
auto elemLayer = layers->FirstChildElement( );
while( elemLayer != 0 )
{
//auto elem = elemLayer->FirstChildElement( );
auto bezier = elemLayer->FirstChildElement( "Beziers" );
auto bz = bezier->FirstChildElement( );
auto color = elemLayer->FirstChildElement( "Colors" );
auto co = color->FirstChildElement( );
auto layer = new LineLayer( );
while( bz != 0 && co != 0 )
{
float bx = atof( bz->Attribute( "bx" ) );
float by = atof( bz->Attribute( "by" ) );
float ex = atof( bz->Attribute( "ex" ) );
float ey = atof( bz->Attribute( "ey" ) );
float c1x = atof( bz->Attribute( "c1x" ) );
float c1y = atof( bz->Attribute( "c1y" ) );
float c2x = atof( bz->Attribute( "c2x" ) );
float c2y = atof( bz->Attribute( "c2y" ) );
float r = atof( co->Attribute( "r" ) );
float g = atof( co->Attribute( "g" ) );
float b = atof( co->Attribute( "b" ) );
float a = atof( co->Attribute( "a" ) ); layer->AddBezier( bx, by, ex, ey, c1x, c1y, c2x, c2y, r, g, b, a );
bz = bz->NextSiblingElement( );
co = co->NextSiblingElement( );
}
if( !layer->isEmpty( ) )
{
_bgLayerData->AddLineLayer( layer );
}
elemLayer = elemLayer->NextSiblingElement( );
}
return _bgLayerData;
}

使用 tinyxml2 的 XMLDocument 读取文件,然后从读取的内容当中提取数据。首先找到根节点,再找到第一个“Layers”节点(也就这么一个,因为只有一个背景),“Layers”节点对应 BgLayerData 类;接下来找到第一个子节点“Layer”,“Layer”对应 LineLayer类,开始循环,从“Layer”中循环获取“Bezier”和“color”创建并添加到 LineLayer 中;循环递增条件是当前节点赋值为下一个节点,当节点为时循环结束。通过两重循环把数据提取出来,下一步就可以使用了。

ResourcesManage 类原本设想会有许多任务,但目前只用到上面这个函数,其他的就先放那里,给将来做个参考。