Kigs Framework Introduction (5/8) - CoreItem

 
Rate me!
0.00 (No votes)
 
21 Feb 2020MIT
A multi purpose, cross-platform, free and Open Source C++ framework. This article will focus on CoreItem.
In previous articles from this series, we have discovered the CoreModifiable class and its features (attributes, methods...). Let's see another totally different class family and the new possibilities it offers: CoreItem. CoreItem can be used in the Kigs framework to manipulate JSON style objects, but also to animate values or to evaluate expressions.

Kigs Logo

Table of Contents

Introduction

CoreItem is a family of class with several different usages:

  • JSON type objects manipulation
  • Expression evaluation / basic scripting language
  • CoreModifiable values animation

Let's have a look at those Kigs framework features.

Basic CoreItem Usage

CoreItem are classes used to manage JSON type of object hierarchy.

Main CoreItem types are CoreValueCoreMap and CoreVector.
The easier way to manipulate CoreItem is to use CoreItemSP, a smartpointer on CoreItem:

// Create a CoreValue<int> with value 52
CoreItemSP item = CoreItemSP(52);

Here is the list of constructors for CoreValue:

  • CoreItemSP(const bool& value): create a CoreValue<bool>
  • CoreItemSP(const float& value): create a CoreValue<float>
  • CoreItemSP(const int& value): create a CoreValue<int>
  • CoreItemSP(const unsigned int& value): create a CoreValue<unsigned int>
  • CoreItemSP(const kstl::string& value) or CoreItemSP(const char* value): create a CoreValue<kstl::string>
  • CoreItemSP(const usString& other): create a CoreValue<usString>

Here is the list of constructors for CoreVector:

  • CoreItemSP(const Point2D& value): create a CoreVector with two CoreValue<float> values
  • CoreItemSP(const Point3D& value): create a CoreVector with three CoreValue<float> values

Other static helper functions are:

  • getCoreMap(): return an empty CoreMap
  • getCoreVector(): return an empty CoreVector
  • template<typename smartPointOn, typename ... Args> static CoreItemSP getCoreItemOfType(Args&& ... args): return the asked type of CoreItem.

CoreItem hierarchy can also be created from a JSON file or string:

// A CoreItem hierarchy can be created from json file (or json string)
JSonFileParser L_JsonParser;
CoreItemSP item = L_JsonParser.Get_JsonDictionaryFromString(R"====(
  {
   "obj1" : { "obj3": [0.4, 0.9, 0.0, "str"] },
   "val1" : 15
  }
)====");

And then the item can be read using array-like access:

// check if val2 exist
if (item["val2"].isNil())
{
    std::cout << "val 2 not found " << std::endl;
}
else
{
    std::cout << "val 2 : " << (int)item["val2"] << std::endl;
}

std::cout << "val 1 : " << (int)item["val1"] << std::endl;
std::cout << " first obj3 array val : " << (float)item["obj1"]["obj3"][0] << std::endl;

CoreItem can be inserted in a CoreMap or CoreVector using the set method:

// create a CoreValue<float>
CoreItemSP toInsert(61.5f);
// add it to CoreMap item with key "val2"
item->set("val2", toInsert);
// set with "" do a push_back on CoreVector
item["obj1"]["obj3"]->set("",CoreItemSP("stringValue"));

maCoreItem are CoreModifiable attributes that can be added to CoreModifiable and then exported or imported:

CMSP donothing = KigsCore::GetInstanceOf("useless", "DoNothing");
donothing->AddDynamicAttribute(COREITEM, "item");
donothing->setValue("item", item.get());
Export("testCoreItemExport.xml", donothing.get());

The generated XML file contains a DATA section containing the exported JSON:

<?xml version="1.0" encoding="utf-8"?>
<Inst N="useless" T="DoNothingObject">
   <Attr T="coreitem" N="item" Dyn="yes">
<![CDATA[{"obj1":{"obj3":[0.400000,0.900000,0.000000,
          "str","lastElem",[5.000000,4.000000,3.000000]]},
"val1":15,
"val2":52}]]>
   </Attr>
</Inst>

Expression Evaluation

Another kind of CoreItem are CoreItemOperator.
They can be used to evaluate a mathematical expression with access to CoreModifiable attributes or methods.

Using CoreItem in C++ Code

The expression is given as a string starting with "eval" keyword, the dimension of the expression: "1D" or nothing for float, "2D" for 2D vectors, "3D" for 3D vectors, "4D" for 4D vectors and the expression to be evaluated between parenthesis.

CoreItemSP    tsteval("eval(12.0*sin(4.0))");
// evaluate the expression and print it
std::cout << "Expression : 12.0*sin(4.0) = " << (float)tsteval << std::endl;

Of course, more complex expressions are possible :

tsteval = std::string("eval(if(([/Sample5->randomNumber(0.0,2.0)]>1.0),
#/Sample5->EvalResult.x#=(#/Sample5->EvalResult.x#+1);1,
#/Sample5->EvalResult.y#=(#/Sample5->EvalResult.y#+1);2))");

The expression is re-evaluated each time we cast the CoreItem to floatPoint2DPoint3D or Vector4D.

Mathematical Operators

  • '*' = multiplication
  • '+' = addition
  • '-' = subtraction or negation
  • '/' = division
  • '(' and ')' = parenthesis are also available to group mathematical operations

Logical Operators

  • '==' = test equality
  • '!=' = test difference
  • '>' = test superiority
  • '<' = test inferiority
  • '>=' = test superiority or equality
  • '<=' = test inferiority or equality
  • '&&' = logical AND
  • '||' = logical OR

Mathematical Functions

Working on float values.

  • 'sin' = gives sinus of the given parameter
  • 'cos' = gives cosinus of the given parameter
  • 'tan' = gives tangent of the given parameter
  • 'abs' = gives absolute value of the given parameter
  • 'min' = gives minimum value of the given parameters
  • 'max' = gives maximum value of the given parameters

Test and Affectation

  • 'if' = function if takes 3 parameters, first is the test, second is the returned result if the test is true (then), third is the returned result if the test is false (else).
  • '=' affect the right part value to the left part attributes

Attributes

  • '#path_to_owner->attribute_name#' = CoreModifiable attributes are given by their path

When using maCoreItem, the path can be relative to owner CoreModifiable. To get only one value of a 2D or 3D or 4D vector, a '.x', '.y','.z' or 'w' can be added to the attribute name.

Methods

  • '[path_to_owner->method_name(arg1,arg2...)]' = CoreModifiable methods are given by their path. Like for attributes, when using maCoreItem, the path can be relative to owner CoreModifiable.

Vectors

  • '{' and '}' = are delimiters for vector members. Then each member is separated from the next one by ','.

Instructions Separator

  • ';' = several expressions can be evaluated, separated by ';'. The last one is the one returned.

For CoreModifiable Attributes Initialisation (XML)

The same mechanism can be used in XML file to initialize attributes values.
There is no need to precise "1D", "2D", "3D" or "4D" as the dimension is given directly by the attribute type.
The expression is evaluated only once to initialize the attribute.

Warning: If the evaluation uses other attributes (in other instances or not), they must have been loaded and initialized before the current one. In a given XML, attributes are initialized in the order they are read in the XML.
<Inst N="simpleclass" T="SimpleClass">
   <Attr N="IntValue" V="eval(32*4)"/>
</Inst>

Animation

Sample5 animated logo snapshot

Sample5 animated logo snapshot.

A third way to use CoreItem is to create animation with CoreAction. Animations are available thanks to the CoreAnimation module.

Here is an example of animation in the "Screen_Main.xml" file of Sample5:

<Inst Name="animateLogo" Type="CoreSequenceLauncher">
    <Attr Type="coreitem" Name="Sequence"><![CDATA[
{"animateLogo":[
    {"Linear2D":[4,[0.5,0.5],[1.0,0.5],"Dock"]},
    {"Linear2D":[4,[1.0,0.5],[0.5,0.0],"Dock"]},
    {"Combo": [
        {"Hermite2D":[4,[0.5,0.0],[0.5,1.0],[-1.0,0.0],[1.0,0.0],"Dock"]},
        {"Linear1D":[4,0.0,3.14,"RotationAngle"]}]},
    {"SetValue1D":[1,1,"/Sample5->NeedExit"]}
]}
]]>
    </Attr>
    <Attr Type="bool" Name="StartOnFirstUpdate" Value="true" />
</Inst> 

In the previous XML extract, a CoreSequenceLauncher instance is created as a son of a UIImage of the Kigs framework logo. All numeric, 2D, 3D or 4D vectors CoreModifiable attributes can be animated using CoreAction.
CoreSequence is then created like this:

{"Sequence Name":[
CoreAction1,
CoreAction2,
...
]}

Each action is described as a JSON object:

{"ActionType":[ActionParam1 , ActionParam2, ...]}

In a CoreSequence, each action is executed before the next one.

Interpolation CoreAction

Linear Interpolation

Linear1DLinear2DLinear3DLinear4D are available.

2D, 3D or 4D values are given between '[' and ']' and separated by ','.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

Here is an example of Linear2D interpolation :

{"Linear2D":[duration,[start_value.x,start_value.y],[end_value.x,end_value.y],
"attribute_path->attribute_name",isRelative]}

duration is a float given in seconds, then the start and end values are given, then the CoreModifiable attribute to animate, and the optional relative attribute with following possible values:

  • 0 => absolute start and end values
  • 1 => start and end relative (mean given values are added to the current value)
  • 2 => start relative, end absolute
  • 3 => start absolute, end relative

Hermite Interpolation

Hermite interpolation is an interpolation with given starting and ending tangent.

Here is an example of Hermite1D interpolation (2D, 3D and 4D are also available):

{ "Hermite1D": [duration,start_value, end_value,start_tangent, 
   end_tangent,"attribute_path->attribute_name",isRelative] }

Setting a Value

SetValue action waits "duration", then sets the given value to the attribute.
SetValue1DSetValue2DSetValue3DSetValue4D are available.

Here is an example of SetValue3D:

{ "SetValue3D" : [duration, [value.x,value.y,value.z] , "attribute_path->attribute_name"] }

KeyFrame Actions

At the moment, no interpolation is done, KeyFrame actions are the same as series of SetValue actions.
KeyFrame1DKeyFrame2DKeyFrame3DKeyFrame4D are available.

Here is an example of KeyFrame2D:

{"KeyFrame2D" : ["attribute_path->attribute_name", key1_time , [key1_value.x,key1_value.y]
                                                 , key2_time , [key2_value.x,key2_value.y]
                                                 , ...
                                                 , keyN_time, [keyN_value.x,keyN_value.y] ] }

Loop Actions

For Loop

Execute the same action N times. If N is -1, do an infinite loop.

{ "ForLoop" : [N ,{ CoreAction } ] }

DoWhile Loop

Execute the same action while a given attribute is true (not 0).

{ "DoWhile" : ["attribute_path->attribute_name", { CoreAction } ] }

Compose Actions

Combo

Combo action executes all its son actions at the same time.

{ "Combo" : [{action1},
            ,{action2},
            , ...
            ,{actionN} ] }

Series

Serie action plays son actions as a sequence: each one after the other.

{ "Serie" :[ {action1},
            ,{action2},
            , ...
            ,{actionN} ] }

Functions

Animate CoreModifiable attribute using CoreItem expression evaluation.

Function1DFunction2DFunction3DFunction4D are available.

There are two possible ways to pass an expression to Function action:

  • float (1D) expression is given for each dimension needed.
  • A unique expression with the same dimension of the defined action is given.

The actionTime() method can be used in the expression to get current action time. If "null" is given for one of the expression, then the parameter is unchanged.

Example of Function2D:

{ "Function2D": [duration,["expression1","expression2"],"attribute_path->attribute_name"] }

or:

{ "Function2D": [duration,"expression2D","attribute_path->attribute_name"] }

Example of actionTime usage:

{ "Function2D": [2.0,["0.5+0.5*sin(actionTime())","null"],"AnchorPoint"] }

Other Actions

Wait

Do nothing during the given value in second.

{ "Wait" : [ duration ] }

Notification

Post a message after waiting duration.
An optional string can be given as notification parameter (usString* is passed as private param).

{ "Notification" :  [ duration , "notification_name", "optional_param" ] }

See Signal / Slot / Notification future article for details.

Signal

Make owner CoreModifiable instance send a signal after waiting duration.
An optional string can be given as usString signal parameter.

{ "Signal" :  [ duration , "signal", "optional_param" ] }

See Signal / Slot / Notification future article for details.

RemoveFromParent

Remove the object owning this sequence from its parent of the given type after waiting duration.

{ "RemoveFromParent" :  [ duration , "parent_type" ] }

Find all the sample code from this wiki section in Sample5 project (browse the code).

Already Published in this Series

  1. Kigs Framework Introduction (1/8) - Overview
  2. Kigs Framework Introduction (2/8) - CoreModifiable
  3. Kigs Framework Introduction (3/8) - Attributes
  4. Kigs Framework Introduction (4/8) - Methods
  5. Kigs Framework Introduction (5/8) - CoreItem

History

  • 20th February, 2020: Initial version

[출처] https://www.codeproject.com/Articles/5257419/Kigs-framework-introduction-5-8-CoreItem

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
154 Windows 10에 한국어 입출력이 가능한 리눅스 데스크톱 설치하기 file 졸리운_곰 2020.06.29 289
153 [C/C++] (고전 기호 처리 인공지능) 전문가 시스템 file 졸리운_곰 2020.06.13 330
152 리눅스 파일 찾기 (파일 및 디렉토리 검색) file 졸리운_곰 2020.05.12 277
151 linux desktop 화면 해상도 변경 file 졸리운_곰 2020.04.09 270
150 Kigs Framework Introduction (7/8) - Lua Binding 졸리운_곰 2020.03.23 337
149 crontab 저장 파일 위치 졸리운_곰 2020.03.02 321
148 crontab 백업 방법 스크립트 졸리운_곰 2020.03.02 285
147 리눅스 우분투 crontab (크론탭) 설정 졸리운_곰 2020.03.02 281
146 Kigs Framework Introduction (6/8) - Signal, Slot, Notification file 졸리운_곰 2020.02.28 321
» Kigs Framework Introduction (5/8) - CoreItem file 졸리운_곰 2020.02.28 322
144 Kigs Framework Introduction (4/8) - Methods file 졸리운_곰 2020.02.28 278
143 Kigs Framework Introduction (3/8) - Attributes file 졸리운_곰 2020.02.28 219
142 Kigs Framework Introduction (2/8) - CoreModifiable file 졸리운_곰 2020.02.28 258
141 Kigs Framework Introduction (1/8) file 졸리운_곰 2020.02.27 265
140 wxwidgets 과 codeblock 설치(리눅스) 졸리운_곰 2019.12.25 228
139 [windows] MinGW, wxWidget, Code:Blocks를 이용한 C/C++ IDE 환경 구축 file 졸리운_곰 2019.12.25 480
138 ubuntu 18.04.2 LTS 개발환경 세팅 졸리운_곰 2019.12.25 223
137 꼭 필요한 리눅스 명령어, file 졸리운_곰 2019.10.15 411
136 [Ubuntu 18.04] 원격 데스크톱 file 졸리운_곰 2019.02.23 331
135 Tasksel – Easily and Quickly Install Group Softwares in Debian and Ubuntu file 졸리운_곰 2018.10.14 296
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED