// Fill out your copyright notice in the Description page of Project Settings.

#include "GAS/GACombo.h"
#include "Abilities/Tasks/AbilityTask_PlayMontageAndWait.h"
#include "Abilities/Tasks/AbilityTask_WaitGameplayEvent.h"
#include "Abilities/Tasks/AbilityTask_WaitInputPress.h"
#include "GAS/CAbilitySystemStatics.h"

UGACombo::UGACombo()
{
	// `AbilityTags` might be deprecated after UE 5.6,
	// use `GetAssetTags()` and `SetAssetTags()` to replace `AbilityTags`
	// AbilityTags.AddTag(UCAbilitySystemStatics::GetBasicAttackAbilityTag());
	const FGameplayTagContainer Tags = FGameplayTagContainer(UCAbilitySystemStatics::GetBasicAttackAbilityTag());
	SetAssetTags(Tags);
	BlockAbilitiesWithTag.AddTag(UCAbilitySystemStatics::GetBasicAttackAbilityTag());
}

void UGACombo::ActivateAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo,
                               const FGameplayAbilityActivationInfo ActivationInfo, const FGameplayEventData* TriggerEventData)
{
	// CommitAbility() 会检测当前是否满足技能释放条件，如冷却、蓝量等
	// 如果满足，则会消耗对应资源，并返回true；若不满足，则不消耗，返回false
	// if (!CommitAbility(Handle, ActorInfo, ActivationInfo))
	// {
	// 	EndAbility(Handle, ActorInfo, ActivationInfo, true, false);
	// 	return;
	// }

	// K2版本的蓝图函数不需要参数，直接内部检查，更简练
	if (!K2_CommitAbility())
	{
		K2_EndAbility();
		return;
	}

	if (HasAuthorityOrPredictionKey(ActorInfo, &ActivationInfo))
	{
		UAbilityTask_PlayMontageAndWait* PlayComboMontageTask = UAbilityTask_PlayMontageAndWait::CreatePlayMontageAndWaitProxy(this, NAME_None, ComboMontage);
		PlayComboMontageTask->OnBlendOut.AddDynamic(this, &UGACombo::K2_EndAbility);
		PlayComboMontageTask->OnCancelled.AddDynamic(this, &UGACombo::K2_EndAbility);
		PlayComboMontageTask->OnCompleted.AddDynamic(this, &UGACombo::K2_EndAbility);
		PlayComboMontageTask->OnInterrupted.AddDynamic(this, &UGACombo::K2_EndAbility);
		PlayComboMontageTask->ReadyForActivation();

		UAbilityTask_WaitGameplayEvent* WaitComboChangeEventTask = UAbilityTask_WaitGameplayEvent::WaitGameplayEvent(this, GetComboChangedEventTag(), nullptr, false, false);
		WaitComboChangeEventTask->EventReceived.AddDynamic(this, &UGACombo::HandleComboChangedEvent);
		WaitComboChangeEventTask->ReadyForActivation();

		SetupInputPress();
	}
}

FGameplayTag UGACombo::GetComboChangedEventTag()
{
	return FGameplayTag::RequestGameplayTag("Ability.Combo.Change");
}

FGameplayTag UGACombo::GetComboChangedEventEndTag()
{
	return FGameplayTag::RequestGameplayTag("Ability.Combo.Change.End");
}

void UGACombo::SetupInputPress()
{
	// Hard-coded to be triggered only once
	UAbilityTask_WaitInputPress* WaitInputPressTask = UAbilityTask_WaitInputPress::WaitInputPress(this);
	WaitInputPressTask->OnPress.AddDynamic(this, &UGACombo::HandleInputPress);
	WaitInputPressTask->ReadyForActivation();
}

// Delegate functions in `EventReceived.AddDynamic` require a whole `FGameplayEventData` struct passing in, while reference is not allowed.
// ReSharper disable once CppPassValueParameterByConstReference
void UGACombo::HandleComboChangedEvent(FGameplayEventData Data)
{
	if (const FGameplayTag& EventTag = Data.EventTag; EventTag == GetComboChangedEventEndTag())
	{
		NextComboName = NAME_None;
		// UE_LOG(LogTemp, Warning, TEXT("Next Combo is cleared."));
	}
	else
	{
		NextComboName = EventTag.GetTagLeafName();
		// UE_LOG(LogTemp, Warning, TEXT("Next Combo Name: %s"), *NextComboName.ToString());
	}
}

void UGACombo::HandleInputPress(float TimeWaited)
{
	SetupInputPress();

	if (NextComboName == NAME_None) return;
	if (UAnimInstance* OwnerAnimInstance = GetOwnerAnimInstance())
	{
		OwnerAnimInstance->Montage_SetNextSection(OwnerAnimInstance->Montage_GetCurrentSection(ComboMontage), NextComboName, ComboMontage);
	}
}


//
// Created by IT-JIM
// VIDEO2: Decode a video file with opencv and send to a gstreamer pipeline via appsrc

#include <iostream>
#include <string>
#include <thread>
#include <atomic>
#include <cmath>
#include <sstream>
#include <algorithm>
#include <chrono>
#include <cstring>
#include <fstream>
#include <string>

#include "encode_z16.h"
#include "encodeRGBtoI420.h"

#include <gst/gst.h>
#include <gst/app/gstappsrc.h>
#include <librealsense2/rs.hpp>
#include <opencv2/opencv.hpp>

//======================================================================================================================
/// A simple assertion function + macro
inline void myAssert(bool b, const std::string& s = "MYASSERT ERROR !") {
    if (!b)
        throw std::runtime_error(s);
}

#define MY_ASSERT(x) myAssert(x, "MYASSERT ERROR :" #x)

//======================================================================================================================
/// Check GStreamer error, exit on error
inline void checkErr(GError* err) {
    if (err) {
        std::cerr << "checkErr : " << err->message << std::endl;
        exit(0);
    }
}

//======================================================================================================================
/// Our global data, serious gstreamer apps should always have this !
struct GoblinData {
    /// pipeline
    GstElement* pipeline = nullptr;
    /// appsrc
    GstElement* srcVideo = nullptr;
    /// Video file name
    std::string fileName;
    /// Appsrc flag: when it's true, send the frames
    std::atomic_bool flagRunV{ false };

};

//======================================================================================================================
/// Process a single bus message, log messages, exit on error, return false on eof
static bool busProcessMsg(GstElement* pipeline, GstMessage* msg, const std::string& prefix) {
    using namespace std;

    GstMessageType mType = GST_MESSAGE_TYPE(msg);
    cout << "[" << prefix << "] : mType = " << mType << " ";
    switch (mType) {
    case (GST_MESSAGE_ERROR):
        // Parse error and exit program, hard exit
        GError* err;
        gchar* dbg;
        gst_message_parse_error(msg, &err, &dbg);
        cout << "ERR = " << err->message << " FROM " << GST_OBJECT_NAME(msg->src) << endl;
        cout << "DBG = " << dbg << endl;
        g_clear_error(&err);
        g_free(dbg);
        exit(1);
    case (GST_MESSAGE_EOS):
        // Soft exit on EOS
        cout << " EOS !" << endl;
        return false;
    case (GST_MESSAGE_STATE_CHANGED):
        // Parse state change, print extra info for pipeline only
        cout << "State changed !" << endl;
        if (GST_MESSAGE_SRC(msg) == GST_OBJECT(pipeline)) {
            GstState sOld, sNew, sPenging;
            gst_message_parse_state_changed(msg, &sOld, &sNew, &sPenging);
            cout << "Pipeline changed from " << gst_element_state_get_name(sOld) << " to " <<
                gst_element_state_get_name(sNew) << endl;
        }
        break;
    case (GST_MESSAGE_STEP_START):
        cout << "STEP START !" << endl;
        break;
    case (GST_MESSAGE_STREAM_STATUS):
        cout << "STREAM STATUS !" << endl;
        break;
    case (GST_MESSAGE_ELEMENT):
        cout << "MESSAGE ELEMENT !" << endl;
        break;

        // You can add more stuff here if you want

    default:
        cout << endl;
    }
    return true;
}

//======================================================================================================================
/// Run the message loop for one bus
void codeThreadBus(GstElement* pipeline, GoblinData& data, const std::string& prefix) {
    using namespace std;
    GstBus* bus = gst_element_get_bus(pipeline);

    int res;
    while (true) {
        GstMessage* msg = gst_bus_timed_pop(bus, GST_CLOCK_TIME_NONE);
        MY_ASSERT(msg);
        res = busProcessMsg(pipeline, msg, prefix);
        gst_message_unref(msg);
        if (!res)
            break;
    }
    gst_object_unref(bus);
    cout << "BUS THREAD FINISHED : " << prefix << endl;
}

//======================================================================================================================
/// Take video from IntelRealsense SDK and send data to appsrc
void codeThreadSrcV(GoblinData& data) {
    using namespace std;

    // Find width, height, FPS
    int imW = 1280;
    int imH = 720;
    double fps = 30;

    // initialise tabulated values for encode_z16
    initialize_z16_tables();
    initialize_delta_table();

    ostringstream oss; // attention si concatene pas oublier le fois 2
    oss << "video/x-raw,format=I420,width=" << imW << ",height=" << imH * 2 << ",framerate=" << int(lround(fps)) << "/1";
    cout << "CAPS=" << oss.str() << endl;
    GstCaps* capsVideo = gst_caps_from_string(oss.str().c_str());
    g_object_set(data.srcVideo, "caps", capsVideo, nullptr);
    gst_caps_unref(capsVideo);

    // Play the pipeline AFTER we have set up the final c


#include<bits/stdc++.h>
using namespace std;
const int N=1e3+22;
int a[N];//下标是面数 大小是个数
int main()
{
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    string s;cin>>s;
    int t=1;//默认为正
    int min_v=0,max_v=0;
    for(int i=0;i<s.size();i++)
    {
        if(s[i]=='+')t=1;
        else if(s[i]=='-')t=-1;
        else if(isdigit(s[i])||s[i]=='d')
        {
            int x=0,y=0;
            if(isdigit(s[i]))
            {
                for(;isdigit(s[i]);i++)
                {
                    x=x*10+s[i]-'0';
                }
            }
            //此时如果s[i]=='d' 处理y
            if(s[i]=='d')
            {
                i++;
                for(;isdigit(s[i]);i++)
                {
                    y=y*10+s[i]-'0';
                }
            }
            i--;//避免跳过字符（两个i++,另一个是最外层for循环）！！！ 好好理解一下
            if(x==0&&y!=0)x=1;
            if(y)
            {
                a[y]+=x;
                if(t>0)
                {
                    min_v+=x*1;
                    max_v+=x*y;
                }
                else
                {
                    min_v-=x*y;
                    max_v-=1*x;
                }
            }
            //普通数字
            else
            {
                min_v+=t*x;
                max_v+=t*x;
            }
        }
    }
    for(int i=1;i<=N;i++)if(a[i])
    {
        cout<<i<<" "<<a[i]<<endl;
    }
    cout<<min_v<<" "<<max_v<<endl;
    return 0;
}


// 🎯 Combined Program with queue + stack
#include <iostream>
#include <queue>
#include <stack>
#include <string>
using namespace std;

int main() {
    queue<string> ticketQueue;   // Ticket booking queue
    stack<string> undoStack;     // Undo actions
    stack<string> redoStack;     // Redo actions

    int mainChoice;

    do {
        cout << "\n====== MAIN MENU ======\n";
        cout << "1. Ticket Booking System (Queue)\n";
        cout << "2. Undo/Redo System (Stack)\n";
        cout << "0. Exit\n";
        cout << "Enter choice: ";
        cin >> mainChoice;

        if (mainChoice == 1) {
            // ---- Ticket Booking System ----
            int choice;
            do {
                cout << "\n--- Ticket Booking System ---\n";
                cout << "1. Add person to queue\n";
                cout << "2. Serve next person\n";
                cout << "3. Show first & last person in queue\n";
                cout << "4. Show all people in queue\n";
                cout << "0. Back to Main Menu\n";
                cout << "Enter choice: ";
                cin >> choice;

                if (choice == 1) {
                    string name;
                    cout << "Enter person's name: ";
                    cin >> name;
                    ticketQueue.push(name);
                    cout << name << " joined the queue.\n";
                }
                else if (choice == 2) {
                    if (!ticketQueue.empty()) {
                        cout << "Serving " << ticketQueue.front() << " (ticket given).\n";
                        ticketQueue.pop();
                    } else {
                        cout << "Queue is empty.\n";
                    }
                }
                else if (choice == 3) {
                    if (!ticketQueue.empty()) {
                        cout << "First in queue: " << ticketQueue.front() << endl;
                        cout << "Last in queue : " << ticketQueue.back() << endl;
                    } else {
                        cout << "Queue is empty.\n";
                    }
                }
                else if (choice == 4) {
                    if (!ticketQueue.empty()) {
                        cout << "People in queue: ";
                        queue<string> temp = ticketQueue; // copy for iteration
                        while (!temp.empty()) {
                            cout << temp.front() << " ";
                            temp.pop();
                        }
                        cout << endl;
                    } else {
                        cout << "Queue is empty.\n";
                    }
                }
            } while (choice != 0);
        }

        else if (mainChoice == 2) {
            // ---- Undo/Redo System ----
            int choice;
            do {
                cout << "\n--- Undo/Redo System ---\n";
                cout << "1. Do new action\n";
                cout << "2. Undo last action\n";
                cout << "3. Redo last undone action\n";
                cout << "4. Show current actions\n";
                cout << "0. Back to Main Menu\n";
                cout << "Enter choice: ";
                cin >> choice;

                if (choice == 1) {
                    string action;
                    cout << "Enter action (e.g., type_text, draw_line): ";
                    cin >> action;
                    undoStack.push(action);
                    // Clear redo stack
                    while (!redoStack.empty()) redoStack.pop();
                    cout << "Action performed: " << action << endl;
                }
                else if (choice == 2) {
                    if (!undoStack.empty()) {
                        cout << "Undo: " << undoStack.top() << endl;
                        redoStack.push(undoStack.top());
                        undoStack.pop();
                    } else {
                        cout << "Nothing to undo.\n";
                    }
                }
                else if (choice == 3) {
                    if (!redoStack.empty()) {
                        cout << "Redo: " << redoStack.top() << endl;
                        undoStack.push(redoStack.top());
                        redoStack.pop();
                    } else {
                        cout << "Nothing to redo.\n";
                    }
                }
                else if (choice == 4) {
                    if (undoStack.empty()) {
                        cout << "No actions performed yet.\n";
                    } else {
                        cout << "Current actions: ";
                        stack<string> temp = undoStack; // copy for iteration
                        vector<string> actions;
                        while (!temp.empty()) {
                            actions.push_back(temp.top());
                            temp.pop();


#include "calculate.h"
#include "oreno.h"
#include <string>
#include <cmath>
#include <iostream>
#define QString string
#define QChar char
using namespace std;
QString Calculate(QString RawInput)
{
    int functopnum = 0, firstopnum = 0, veryfirstopnum = 0, lastopnum = 0, opin = -1, startop = 0, endop = 0, next = 0, parannum = 0, innerparannum = 0, paranin = -1;
    QString AraInput = "";
    bool startBabo = false, abesod = true;
    for (int i = 0; i < RawInput.length(); i++)
    {
        if(RawInput[i] == '(' && innerparannum == 0){parannum++; innerparannum++;}
        else if(RawInput[i] == ')' && innerparannum > 0)
        {
            innerparannum--;
        }
        else if(RawInput[i] == '(' && innerparannum > 0){innerparannum++;}
    }
    if(innerparannum != 0){cerr << "Syntax Error\n\n";RawInput = "";}
    for (int i = parannum; i > 0; i--)
    {
        QString IRawInput = "";
        bool inParan = false, isSingle = true;
        int startparan = -1, endparan = -1;
        innerparannum = 0;
        for (int x = 0; x < RawInput.length(); x++)
        {
            if(RawInput[x] == '(' && innerparannum == 0){startBabo = true; innerparannum++; startparan = x;}
            else if(RawInput[x] == ')' && innerparannum > 0)
            {
                innerparannum--;
                if(RawInput[x] == ')' && innerparannum == 0)
                {
                    innerparannum--;
                    endparan = x;
                    startBabo = false;
                    break;
                }
            }
            else if(RawInput[x] == '(' && innerparannum > 0){innerparannum++;}
            if(startBabo && startparan != x){IRawInput += RawInput[x];}
        }
        innerparannum = 0;
        for (int x = 0; x < IRawInput.length(); x++)
        {
            if (IRawInput[x] == '+' || IRawInput[x] == '/' || IRawInput[x] == '*' || IRawInput[x] == '^' || (IRawInput[x] == '-' && x != 0))
            {
                isSingle = false;
            }
        }
        if (isSingle)
        {
            if (IRawInput.length() > 0 && IRawInput[0] == '-')
            {
                IRawInput[0] = '0';
            }
            if (AraInput.length() > 0 && AraInput[AraInput.length() - 1] == '!')
            {
                QString zap = "";
                for (int i = 0; i < IRawInput.length() - 1; i++)
                {
                    zap += IRawInput[i];
                }
                if (TryParse(zap))
                {
                    int ap = stoi(zap);
                    for (int x = ap - 1; x > 1; x--)
                    {
                        ap *= x;
                    }
                    IRawInput = to_string(ap);
                }
                else{cerr << "Syntax Error\n\n"; RawInput = ""; AraInput = "";}
            }
            for (int x = 0; x < RawInput.length(); x++)
            {
                if (x < startparan || x > endparan)
                {
                    AraInput += RawInput[x];
                }
                else if (x == startparan)
                {
                    AraInput += IRawInput;
                }
            }
            RawInput = AraInput;
            AraInput = "";
        }
        else
        {
            for(int x = 0; x < RawInput.length(); x++)
            {
                if(x < startparan || x > endparan)
                {
                    AraInput += RawInput[x];
                }
                else if(x == startparan)
                {
                    AraInput += Calculate(IRawInput);
                }
            }
            RawInput = AraInput;
            AraInput = "";
        }
    }
    for (int i = 0; i < RawInput.length(); i++)
    {
        if (RawInput[i] == '*' || RawInput[i] == '/')
        {
            opin = i;
            firstopnum++;
        }
        else if (RawInput[i] == '+' || (RawInput[i] == '-' && i != 0 && i != opin + 1))
        {
            opin = i;
            lastopnum++;
        }
        else if (RawInput[i] == '^' || RawInput[i] == 'v')
        {
            opin = i;
            veryfirstopnum++;
        }
        else if(RawInput[i] == '!')
        {
            functopnum++;
            opin = i;
        }
    }
    for(int i = functopnum; i > 0; i--)
    {
        bool facto = false;
        QString sum = "";
        for (int x = 0; x < RawInput.length(); x++)
        {
            if (RawInput[x] == '!')
            {
                opin = x;
                facto = true;
                break;
            }
        }
        if (facto)
        {
            endop = opin;
        }
        for (int x = opin - 1; x >= 0; x--)
        {
            if (RawInput[x] == '+' || RawInput[x] == '/' || RawInput[x] == '^' || RawInput[x] == '*' || RawInput[x] == '-' && x > 0)
            {


// Auto-generated from specs/raylib_api.yaml
#include "raylib.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#include "raymath.h"
#pragma GCC diagnostic pop
#include "bas/runtime.hpp"
#include "bas/value.hpp"
#include <vector>
#include <string>
#include <unordered_map>

using bas::Value;
using Fn = bas::NativeFn;

namespace bas {
namespace rlreg {
    // Resource management
    static int next_tex_id = 1;
    static std::unordered_map<int, ::Texture2D> textures;
    static int next_sound_id = 1;
    static std::unordered_map<int, ::Sound> sounds;
    static int next_model_id = 1;
    static std::unordered_map<int, ::Model> models;
    static int next_shader_id = 1;
    static std::unordered_map<int, ::Shader> shaders;
    static int next_font_id = 1;
    static std::unordered_map<int, ::Font> fonts;
    static int next_music_id = 1;
    static std::unordered_map<int, ::Music> music;
    static std::unordered_map<int, ::AudioStream> audio_streams;
    static int next_wave_id = 1;
    static std::unordered_map<int, ::Wave> waves;
    static int next_mesh_id = 1;
    static std::unordered_map<int, ::Mesh> meshes;
    static int next_material_id = 1;
    static std::unordered_map<int, ::Material> materials;
    static int next_image_id = 1;
    static std::unordered_map<int, ::Image> images;
    static int next_audiostream_id = 1;
    static std::unordered_map<int, ::AudioStream> audiostreams;
    static std::unordered_map<int, ::Music> musics;
    static int next_cubemap_id = 1;
    static std::unordered_map<int, ::Texture2D> cubemaps;
    static int next_rendertex_id = 1;
    static std::unordered_map<int, ::RenderTexture2D> rendertextures;
}

void register_raylib_bindings(FunctionRegistry& R) {
    R.add_with_policy("INITWINDOW", Fn{"INITWINDOW", 3, [] (const std::vector<Value>& args) -> Value {
        if (args.size() != 3) throw std::runtime_error("INITWINDOW: expected 3 args");
        InitWindow(args[0].as_int(), args[1].as_int(), args[2].as_string().c_str());
        return Value::nil();
    }}, true);    R.add_with_policy("CLOSEWINDOW", Fn{"CLOSEWINDOW", 0, [] (const std::vector<Value>& args) -> Value {
        if (args.size() != 0) throw std::runtime_error("CLOSEWINDOW: expected 0 args");
        CloseWindow();
        return Value::nil();
    }}, true);    R.add_with_policy("WINDOWSHOULDCLOSE", Fn{"WINDOWSHOULDCLOSE", 0, [] (const std::vector<Value>& args) -> Value {
        if (args.size() != 0) throw std::runtime_error("WINDOWSHOULDCLOSE: expected 0 args");
        return Value::from_bool(WindowShouldClose());
    }}, true);    R.add_with_policy("ISWINDOWREADY", Fn{"ISWINDOWREADY", 0, [] (const std::vector<Value>& args) -> Value {
        if (args.size() != 0) throw std::runtime_error("ISWINDOWREADY: expected 0 args");
        return Value::from_bool(IsWindowReady());
    }}, true);    R.add_with_policy("ISWINDOWFULLSCREEN", Fn{"ISWINDOWFULLSCREEN", 0, [] (const std::vector<Value>& args) -> Value {
        if (args.size() != 0) throw std::runtime_error("ISWINDOWFULLSCREEN: expected 0 args");
        return Value::from_bool(IsWindowFullscreen());
    }}, true);    R.add_with_policy("ISWINDOWHIDDEN", Fn{"ISWINDOWHIDDEN", 0, [] (const std::vector<Value>& args) -> Value {
        if (args.size() != 0) throw std::runtime_error("ISWINDOWHIDDEN: expected 0 args");
        return Value::from_bool(IsWindowHidden());
    }}, true);    R.add_with_policy("ISWINDOWMINIMIZED", Fn{"ISWINDOWMINIMIZED", 0, [] (const std::vector<Value>& args) -> Value {
        if (args.size() != 0) throw std::runtime_error("ISWINDOWMINIMIZED: expected 0 args");
        return Value::from_bool(IsWindowMinimized());
    }}, true);    R.add_with_policy("ISWINDOWMAXIMIZED", Fn{"ISWINDOWMAXIMIZED", 0, [] (const std::vector<Value>& args) -> Value {
        if (args.size() != 0) throw std::runtime_error("ISWINDOWMAXIMIZED: expected 0 args");
        return Value::from_bool(IsWindowMaximized());
    }}, true);    R.add_with_policy("ISWINDOWFOCUSED", Fn{"ISWINDOWFOCUSED", 0, [] (const std::vector<Value>& args) -> Value {
        if (args.size() != 0) throw std::runtime_error("ISWINDOWFOCUSED: expected 0 args");
        return Value::from_bool(IsWindowFocused());
    }}, true);    R.add_with_policy("ISWINDOWRESIZED", Fn{"ISWINDOWRESIZED", 0, [] (const std::vector<Value>& args) -> Value {
        if (args.size() != 0) throw std::runtime_error("ISWINDOWRESIZED: expected 0 args");
        return Value::from_bool(IsWindowResized());
    }}, true);    R.add_with_policy("ISWINDOWSTATE", Fn{"ISWINDOWSTATE", 1, [] (const std::vector<Value>& args) -> Value {
        if (args.size() != 1) throw std::runtime_error("ISWINDOWSTATE: expected 1 args");
        return Value::from_bool(IsWindowState(args[0].as_int()));
    }}, true);    R.add_with_policy("SETWINDOWTITLE", Fn{"SETWINDOWTITLE", 1, [] (const std::vector<Value>& args) -> Value {
        if (args.size() != 1) throw std::runtime_error("SETWINDOWTITLE:


#include <U8g2lib.h>
#include "eyes.h"

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64

// Main screen reference
extern U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2;

// Reference state
int ref_eye_height = 40;
int ref_eye_width = 40;
int ref_space_between_eye = 10;
int ref_corner_radius = 10;
// Current state of the eyes
int left_eye_height = ref_eye_height;
int left_eye_width = ref_eye_width;
int left_eye_x = 32;
int left_eye_y = 32;
int right_eye_x = 32+ref_eye_width+ref_space_between_eye;
int right_eye_y = 32;
int right_eye_height = ref_eye_height;
int right_eye_width = ref_eye_width;
int corner_radius = ref_corner_radius;

#define COLOR_WHITE 1
#define COLOR_BLACK 0

// -----------------------------
// Eye functions

void display_clearDisplay()
{
  u8g2.clearBuffer();

}
void display_fillRoundRect(int x,int y,int w, int h, int r, int color)
{
  u8g2.setDrawColor(color);

  // Behavior is not defined if r is smaller than the height or width
  if( w<2*(r+1) )
  {
    r = (w/2)-1;
  }
  if( h<2*(r+1) )
  {
    r = (h/2)-1;
  }
  // Check if height and width are valid when calling drawRBox
  u8g2.drawRBox(x,y,w<1?1:w,h<1?1:h,r);
}
void display_display()
{
  u8g2.sendBuffer();
}
void display_fillTriangle(int x0,int y0, int x1,int y1,int x2,int y2, int color)
{
  u8g2.setDrawColor(color);
  u8g2.drawTriangle(x0,y0,x1,y1,x2,y2);
}

void draw_eyes(bool update)
{
    display_clearDisplay();
    // Draw from center
    int x = int(left_eye_x-left_eye_width/2);
    int y = int(left_eye_y-left_eye_height/2);
    display_fillRoundRect(x,y,left_eye_width,left_eye_height,corner_radius,COLOR_WHITE);
    x = int(right_eye_x-right_eye_width/2);
    y = int(right_eye_y-right_eye_height/2);
    display_fillRoundRect(x,y,right_eye_width,right_eye_height,corner_radius,COLOR_WHITE);
    if(update)
    {
      display_display();
    }

}

void reset_eyes(bool update)
{
  // Move eyes to the center of the display, defined by SCREEN_WIDTH, SCREEN_HEIGHT
  left_eye_height = ref_eye_height;
  left_eye_width = ref_eye_width;
  right_eye_height = ref_eye_height;
  right_eye_width = ref_eye_width;

  left_eye_x = SCREEN_WIDTH/2-ref_eye_width/2-ref_space_between_eye/2;
  left_eye_y = SCREEN_HEIGHT/2;
  right_eye_x = SCREEN_WIDTH/2+ref_eye_width/2+ref_space_between_eye/2;
  right_eye_y = SCREEN_HEIGHT/2;

  corner_radius = ref_corner_radius;

  draw_eyes(update);
}

void blink(int speed)
{
  reset_eyes(false);

  draw_eyes();

  for(int i=0;i<3;i++)
  {
    left_eye_height = left_eye_height-speed;
    right_eye_height = right_eye_height-speed;

    left_eye_width = left_eye_width+3;
    right_eye_width = right_eye_width+3;
    draw_eyes();
    delay(1);
  }
  for(int i=0;i<3;i++)
  {
    left_eye_height = left_eye_height+speed;
    right_eye_height = right_eye_height+speed;
    left_eye_width = left_eye_width-3;
    right_eye_width = right_eye_width-3;
    draw_eyes();
    delay(1);
  }
}

void eye_sleep()
{
  reset_eyes(false);

  left_eye_height = 2;
  left_eye_width  = ref_eye_width;
  right_eye_height = 2;
  right_eye_width  = ref_eye_width;

  corner_radius = 0;
  draw_eyes(true);

  for (int y = 50; y > 10; y -= 2) {
    u8g2.clearBuffer();
    draw_eyes(true);

    u8g2.setFont(u8g2_font_helvB08_tf);
    u8g2.setCursor(40, y);
    u8g2.print("Zzz");

    u8g2.sendBuffer();
    delay(200);
  }
}

void wakeup()
{
  reset_eyes(false);

  eye_sleep();

  for(int h=2; h <= ref_eye_height; h+=2)
  {
    left_eye_height = h;
    right_eye_height = h;
    corner_radius = h;
    if( corner_radius > ref_corner_radius)
    {
      corner_radius = ref_corner_radius;
    }
    draw_eyes(true);
  }

}

void happy_eye()
{
  reset_eyes(false);
  // Draw inverted triangle over the lower part of the eye
  int offset = ref_eye_height/2;
  for(int i=0;i<10;i++)
  {
    display_fillTriangle(left_eye_x-left_eye_width/2-1, left_eye_y+offset, left_eye_x+left_eye_width/2+1, left_eye_y+5+offset, left_eye_x-left_eye_width/2-1,left_eye_y+left_eye_height+offset,COLOR_BLACK);
    display_fillTriangle(right_eye_x+right_eye_width/2+1, right_eye_y+offset, right_eye_x-left_eye_width/2-2, right_eye_y+5+offset, right_eye_x+right_eye_width/2+1,right_eye_y+right_eye_height+offset,COLOR_BLACK);
    offset -= 2;
    display_display();
    delay(1);
  }

  display_display();
  delay(1000);
}

void saccade(int direction_x, int direction_y)
{
  // Quick movement of the eye, no size change. Stays at position after movement.
  // Call again with opposite direction to move back.
  // direction == -1 :  move left
  // direction == 1 :  move right

  int direction_x_movement_amplitude = 8;
  int direction_y_movement_amplitude = 6;
  int blink_amplitude = 8;

  for(int i=0;i<1;i++)
  {
    left_eye_x+=direction_x_movement_amplitude*direction_x;
    right_eye_x+=direction_x_movement_amplitude*direction_x;
    left_eye_y+=direction_y_mov


#include <iostream>
using std::cin;
using std::cout;
using std::endl;

#define tab "\t"
#define delimiter "\n--------------------------------------------------\n"

class List
{
	class Element
	{
		int Data;
		Element* pNext;
		Element* pPrev;
	public:
		Element(int Data, Element* pNext = nullptr, Element* pPrev = nullptr)
			:Data(Data), pNext(pNext), pPrev(pPrev)
		{
			cout << "EConstructor:\t" << this << endl;
		}
		~Element()
		{
			cout << "EDestructor:\t" << this << endl;
		}
		friend class List;

	}*Head, *Tail; //Объекты классов и структур и указатели на эти объекты можно
	//объявлять непосредственно после описания классов и структур
	size_t size; //Размер списка. size_t - это typedef на 'unsigned int'
	class ConstBaseIterator
	{
	protected: //Чтобы наследники увидели этот Элемент
		//Этот класс обобщает свойства разных Итераторов
		Element* Temp;
	public:
		ConstBaseIterator(Element * Temp = nullptr): Temp(Temp){}
		~ConstBaseIterator(){}

		//				Comparison operators:
		bool operator==(const ConstBaseIterator& other)const
		{
			return this->Temp == other.Temp;
		}
		bool operator!=(const ConstBaseIterator& other)const
		{
			return this->Temp != other.Temp;
		}

		int operator*()const
			//В константном итераторе должен быть только
			//константный оператор разыменования, здесь ни в коем случае не должно
			//быть обычного оператора разыменования
		{
			return Temp->Data;
		}
	};
public:
	class ConstIterator:public ConstBaseIterator
	{
	public:
		ConstIterator(Element * Temp = nullptr):ConstBaseIterator(Temp) {}
		~ConstIterator() {}

		ConstIterator& operator++()
		{
			Temp = Temp->pNext;
			return *this;
		}
		ConstIterator operator++(int)
		{
			ConstIterator old = *this;
			Temp = Temp->pNext;
			return old;
		}
		ConstIterator& operator--()
		{
			Temp = Temp->pPrev;
			return *this;
		}
		ConstIterator operator--(int)
		{
			ConstIterator old = *this;
			Temp = Temp->pPrev;
			return old;
		}
	};
	class ConstReverseIterator:public ConstBaseIterator
	{
	public:
		ConstReverseIterator(Element* Temp = nullptr) :ConstBaseIterator(Temp) {}
		~ConstReverseIterator() {}

		//					Increment/Decrement:
		ConstReverseIterator& operator++()
		{
			Temp = Temp->pPrev;
			return *this;
		}
		ConstReverseIterator operator++(int)
		{
			ConstReverseIterator old = *this;
			Temp = Temp->pPrev;
			return old;
		}
		ConstReverseIterator& operator--()
		{
			Temp = Temp->pNext;
			return *this;
		}
		ConstReverseIterator operator--(int)
		{
			ConstReverseIterator old = *this;
			Temp = Temp->pNext;
			return old;
		}
	};
	class Iterator :public ConstIterator
	{
	public:
		Iterator(Element * Temp):ConstIterator(Temp){}
		~Iterator(){}
		int& operator*()
		{
			return Temp->Data;
		}
	};
	class ReverseIterator :public ConstReverseIterator
	{
	public:
		ReverseIterator(Element* Temp):ConstReverseIterator(Temp) {}
		~ReverseIterator() {}
		int& operator*()
		{
			return Temp->Data;
		}
	};
	ConstIterator begin()const
	{
		return Head;
	}
	ConstIterator end()const
	{
		return nullptr;
	}
	ConstReverseIterator rbegin()const
	{
		return Tail;
	}
	ConstReverseIterator rend()const
	{
		return nullptr;
	}
	Iterator begin()
	{
		return Head;
	}
	Iterator end()
	{
		return nullptr;
	}
	ReverseIterator rbegin()
	{
		return Tail;
	}
	ReverseIterator rend()
	{
		return nullptr;
	}

	List()
	{
		Head = Tail = nullptr;
		size = 0;
		cout << "LConstructor:\t" << this << endl;
	}
	List(const std::initializer_list<int>& il) :List()
	{
		for (int const* it = il.begin(); it != il.end(); ++it)
		{
			push_back(*it);
		}
		cout << "ILConstructor:/t" << this << endl;
	}
	List(const List& other) :List()
	{
		*this = other;
		cout << "LCopyConstructor:\t" << this << endl;
	}
	~List()
	{
		//while (Head)pop_front();
		while (Tail)pop_back();
		cout << "LDestructor:\t" << this << endl;
	}

	//				Operators:
	List& operator=(const List& other)
	{
		if (this == &other) return *this;
		while (Head)pop_front();
		for (Element* Temp = other.Head; Temp; Temp = Temp->pNext) push_back(Temp->Data);
		cout << "LCopyAssignment:\t" << this << endl;
		return *this;
	}

	//				Adding Elements:
	void push_front(int Data)
	{
		//1) Создаем элемент, в котором будет храниться добавляемое значение:
		Element* New = new Element(Data);

		if (Head == nullptr && Tail == nullptr)
		{
			Head = Tail = New;
		}
		else
		{
			//2) Пристыковываем новый элемент к списку:
			New->pNext = Head;

			//3) Пристыковываем начальный элемент списка к новому элементу:
			Head->pPrev = New;

			//4) Делаем новый элемент начальным элементом списка:
			Head = New;
		}

		size++;
	}

	void push_back(int Data)
	{
		//1) Создаем новый элемент:
		Element* New = new Element(Data);
		if (Head == nullptr && Tail == nullptr)
			Head = Tail = New;
		else
		{
			//2) Цепляем новый элемент за хвост списка
			New->pPrev = Tail;

			//3) Пристыковываем список к новому элементу:
			Tail->pNext = New;

			//4) Делаем новый элемент хвостом списка:
			Tail = New;
		}
		size++;
	}

	void i


#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>

#include "flutter_window.h"
#include "utils.h"

int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
                      _In_ wchar_t *command_line, _In_ int show_command) {
  // Attach to console when present (e.g., 'flutter run') or create a
  // new console when running with a debugger.
  if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
    CreateAndAttachConsole();
  }

  // Initialize COM, so that it is available for use in the library and/or
  // plugins.
  ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);

  flutter::DartProject project(L"data");

  std::vector<std::string> command_line_arguments =
      GetCommandLineArguments();

  project.set_dart_entrypoint_arguments(std::move(command_line_arguments));

  FlutterWindow window(project);
  Win32Window::Point origin(10, 10);
  Win32Window::Size size(1280, 720);
  if (!window.Create(L"weather", origin, size)) {
    return EXIT_FAILURE;
  }
  window.SetQuitOnClose(true);

  ::MSG msg;
  while (::GetMessage(&msg, nullptr, 0, 0)) {
    ::TranslateMessage(&msg);
    ::DispatchMessage(&msg);
  }

  ::CoUninitialize();
  return EXIT_SUCCESS;
}


#include <iostream>
using namespace std;

int main() {

    const int ROWS = 4;
    const int COLS = 5;

    int matrix[ROWS][COLS] = {
        {0, 0, 3, 0, 4},
        {0, 0, 5, 7, 0},
        {0, 0, 0, 0, 0},
        {0, 2, 6, 0, 0}
    };

    int nonZeroCount = 0;
    for (int r = 0; r < ROWS; r++)
        for (int c = 0; c < COLS; c++)
            if (matrix[r][c] != 0)
                nonZeroCount++;

    int sparseRep[3][nonZeroCount];

    int index = 0;  // Index for sparseRep columns
    for (int r = 0; r < ROWS; r++)
        for (int c = 0; c < COLS; c++)
            if (matrix[r][c] != 0) {
                sparseRep[0][index] = r;             // row index
                sparseRep[1][index] = c;             // column index
                sparseRep[2][index] = matrix[r][c]; // non-zero value
                index++;
            }

    cout << "Sparse Matrix Representation (row, col, value):\n";
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < nonZeroCount; j++) {
            cout << sparseRep[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}


#include "main.h"

#include <cstdint>
#include <ostream>

class Vector3 {
  public:
    double x, y, z;

    Vector3(double x = 0, double y = 0, double z = 0) : x(x), y(y), z(z) {}

    bool equals(const Vector3 &other, double epsilon) const {
        return std::abs(x - other.x) < epsilon &&
               std::abs(y - other.y) < epsilon &&
               std::abs(z - other.z) < epsilon;
    }

    bool operator==(const Vector3 &other) const {
        return this->equals(other, 1e-6);
    }

    friend std::ostream &operator<<(std::ostream &stream, const Vector3 &self) {
        return stream << "(" << self.x << ", " << self.y << ", " << self.z
                      << ")";
    }
};

class Quaternion {
  public:
    double x, y, z, w;

    Quaternion(double x = 0, double y = 0, double z = 0, double w = 1)
        : x(x), y(y), z(z), w(w) {}

    bool equals(const Quaternion &other, double epsilon) const {
        return std::abs(x - other.x) < epsilon &&
               std::abs(y - other.y) < epsilon &&
               std::abs(z - other.z) < epsilon &&
               std::abs(w - other.w) < epsilon;
    }

    bool operator==(const Quaternion &other) const {
        return this->equals(other, 1e-6);
    }

    friend std::ostream &operator<<(std::ostream &stream,
                                    const Quaternion &self) {
        return stream << self.w << " + " << self.x << "i + " << self.y << "j + "
                      << self.z << "k";
    }
};

class PhysicsWorld {
  private:
    btDefaultCollisionConfiguration m_collisionConfig;
    btCollisionDispatcher m_dispatcher;
    btDbvtBroadphase m_broadphase;
    btSequentialImpulseConstraintSolver m_solver;
    btDiscreteDynamicsWorld m_dynamicsWorld;

    struct GroundInfo {
        btRigidBody *body;
        btCollisionShape *shape;
        bool isActive;
    };

    std::unique_ptr<GroundInfo> m_ground;

    static const uint32_t STEPS_PER_SECOND = 1000;

  public:
    PhysicsWorld()
        : m_collisionConfig(), m_dispatcher(&this->m_collisionConfig),
          m_broadphase(), m_solver(),
          m_dynamicsWorld(&this->m_dispatcher, &this->m_broadphase,
                          &this->m_solver, &this->m_collisionConfig) {
        // this->collisionConfig = btDefaultCollisionConfiguration();
        // this->dispatcher = btCollisionDispatcher(&this->collisionConfig);
        // this->broadphase = btDbvtBroadphase();
        // this->solver = btSequentialImpulseConstraintSolver();
        // this->dynamicsWorld =
        //     btDiscreteDynamicsWorld(&this->dispatcher, &this->broadphase,
        //                             &this->solver, &this->collisionConfig);

        this->m_dynamicsWorld.setGravity(btVector3(0, -9.82, 0));
    }

    ~PhysicsWorld() { dispose(); }

    void dispose() {
        if (this->m_ground && this->m_ground->isActive) {
            this->m_dynamicsWorld.removeRigidBody(m_ground->body);
        }
        if (this->m_ground) {
            delete this->m_ground->body->getMotionState();
            delete this->m_ground->body;
            delete this->m_ground->shape;
            this->m_ground.reset();
        }
    }

    void createGroundPlane() {
        if (m_ground) {
            throw std::runtime_error("Ground is already initialized");
        }

        btVector3 normal(0, 1, 0);
        auto shape = new btStaticPlaneShape(normal, 0);
        shape->setMargin(0.01);

        btTransform transform;
        transform.setIdentity();
        auto motionState = new btDefaultMotionState(transform);

        btVector3 localInertia(0, 0, 0);
        shape->calculateLocalInertia(0, localInertia);

        btRigidBody::btRigidBodyConstructionInfo rbInfo(0, motionState, shape,
                                                        localInertia);
        auto body = new btRigidBody(rbInfo);
        body->setFriction(1.0);

        this->m_ground = std::make_unique<GroundInfo>();
        this->m_ground->body = body;
        this->m_ground->shape = shape;
        this->m_ground->isActive = false;
    }

    void activePhysicsAt(const Vector3 &position) {
        if (this->m_ground) {
            if (position.y < 4) {
                if (!this->m_ground->isActive) {
                    this->m_dynamicsWorld.addRigidBody(m_ground->body);
                    this->m_ground->isActive = true;
                }
            } else if (position.y > 5 && this->m_ground->isActive) {
                this->m_dynamicsWorld.removeRigidBody(m_ground->body);
                this->m_ground->isActive = false;
            }
        }
    }

    void step() {
        this->m_dynamicsWorld.stepSimulation(1.0 / STEPS_PER_SECOND, 0,
                                             1.0 / STEPS_PER_SECOND);
    }

    btDiscreteDynamicsWorld &getWorld() { return this->m_dynamicsWorld; }
    btCollisionDispatcher &getDispatcher() { return this->m_dispatcher; }
};

bool determinismCheck() {
    Vector3 expectedPosition(-0.6827400326728821, 0.112127415835


#include <cstdlib>
#include <iostream>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <unistd.h>
#include <sys/wait.h>
#include <vector>

// General format of each entry
struct Entry
{
  std::string service;
  std::string username;
  std::string password;
};

// ensure directories exist
bool ensureDirectoryExists(const std::string &path)
{
  if (std::filesystem::exists(path))
  {
    return true; // Already exists
  }

  std::cout << "The folder \"" << path << "\" does not exist. Create it? (y/n): ";
  char choice;
  std::cin >> choice;

  if (choice == 'y' || choice == 'Y')
  {
    try
    {
      std::filesystem::create_directory(path);
      std::cout << "Created: " << path << "\n";
      return true;
    }
    catch (const std::filesystem::filesystem_error &e)
    {
      std::cerr << "Error creating " << path << ": " << e.what() << "\n";
      return false;
    }
  }
  else
  {
    std::cout << "Skipping creation of: " << path << "\n";
    return false;
  }
}

// Check that the filesystem is currently mounted
bool isMounted(const std::string &mountPoint)
{
  std::ifstream mounts("/proc/mounts");
  std::string line;
  while (std::getline(mounts, line))
  {
    std::istringstream iss(line);
    std::string device, mount, type, opts;
    if (iss >> device >> mount >> type >> opts)
    {
      if (mount == mountPoint)
      {
        return true;
      }
    }
  }
  return false;
}

// Return true if mounted successfully, false otherwise
bool mountVault(const std::string &vaultCrypt, const std::string &vaultMount)
{
  if (isMounted(vaultMount))
  {
    return true;
  }

  pid_t pid = fork();
  if (pid == -1)
  {
    perror("fork");
    return false;
  }

  if (pid == 0) // Child process
  {
    // Build argument list (argv must be null-terminated)
    const char *args[] = {
        "gocryptfs",
        "-i", "10m",
        vaultCrypt.c_str(),
        vaultMount.c_str(),
        nullptr};

    // Replace process image
    execvp("gocryptfs", (char *const *)args);

    // If execvp returns, it failed
    perror("execvp");
    _exit(127);
  }
  else // Parent process
  {
    int status;
    if (waitpid(pid, &status, 0) == -1)
    {
      perror("waitpid");
      return false;
    }

    if (WIFEXITED(status) && WEXITSTATUS(status) == 0)
    {
      // Double-check the mount
      return isMounted(vaultMount);
    }
    else
    {
      std::cerr << "gocryptfs failed with status " << status << "\n";
      return false;
    }
  }
}

bool addEntry(const std::string &vaultMount)
{
  // Ask user for details
  Entry e;
  std::cout << "Service: ";
  std::getline(std::cin, e.service);
  std::cout << "Username: ";
  std::getline(std::cin, e.username);
  std::cout << "Password: ";
  std::getline(std::cin, e.password);

  // create a file in the vaultMount
  std::string filename = vaultMount + "/" + e.service;

  if (std::filesystem::exists(filename))
  {
    std::cerr << "Error: File \"" << filename << "\" already exists!\n";
    return false;
  }

  // Open the file inside the vault directory
  std::ofstream file(filename);

  if (!file)
  {
    std::cerr << "Error: Could not create file " << filename << "\n";
    return false;
  }
  // Write entry data
  file << e.service << "\n"
       << e.username << "\n"
       << e.password << "\n";

  file.close();

  std::cout << "\n---   File created: " << filename << "   ---\n";
  return true;
}

// get a vector of files contained in vault directory
std::vector<std::filesystem::directory_entry> getEntries(const std::string_view vaultMount)
{
  // create a vector to hold all files contained in the vault directory
  std::vector<std::filesystem::directory_entry> entries;

  // get files
  for (const auto &entry : std::filesystem::directory_iterator(vaultMount))
  {
    if (entry.is_regular_file())
    {
      entries.push_back(entry);
    }
  }

  return entries;
}

int chooseEntry(const std::vector<std::filesystem::directory_entry> &entries, const std::string &actionName)
{
  if (entries.empty())
  {
    std::cout << "No entries found in vault.\n";
    return -1;
  }

  // print numbered list
  std::cout << "\n=== Entries in vault ===\n";
  for (size_t i = 0; i < entries.size(); ++i)
  {
    std::cout << i + 1 << ") " << entries[i].path().filename().string() << "\n";
  }
  std::cout << "0) Exit\n";

  // get user choice
  int choice;
  std::cout << "Enter the number of the entry to " + actionName + ": ";
  std::cin >> choice;
  std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

  if (choice == 0)
  {
    return -1;
  }
  if (choice < 1 || choice > (int)entries.size())
  {
    std::cerr << "Invalid choice.\n";
    return -1;
  }

  return choice - 1;
}

// view files contained in vault directory
void viewEntries(const std::string_view vaultMount)
{
  // vector that contains all entries
  std::vector entries{getEntries(vaultMount)};
  int id = chooseEntry(entries, "view");
  if (id < 0)
  {
    std::cout << "Exiting.\n";
    return;
  }


#include<iostream>
#include<fstream>
using namespace std;

class temp{
    string userName,Email,password;
    string searchName,searchPass,searchEmail;
    fstream file;
    public:
    void login();
    void signUP();
    void forgot();
}obj;

int main(){
    char choice;
    cout<<"\n1- Login";
    cout<<"\n2- Sign-Up";
    cout<<"\n3- Forgot Password";
    cout<<"\n4- Exit";
    cout<<"\nEnter Your Choice :: ";
    cin>>choice;

    switch(choice){
        case '1':
            cin.ignore();
            obj.login();
        break;
        case '2':
            cin.ignore();
            obj.signUP();
        break;
        case '3':
            cin.ignore();
            obj.forgot();
        break;
        case '4':
            return 0;
        break;
        defualt:
            cout<<"Invalid Selection...!";
    }
}
void temp :: signUP(){
    cout<<"\nEnter Your User Name :: ";
    getline(cin,userName);
    cout<<"Enter Your Email Address :: ";
    getline(cin,Email);
    cout<<"Enter Your Password :: ";
    getline(cin,password);

    file.open("loginData.txt",ios :: out | ios :: app);
    file<<userName<<"*"<<Email<<"*"<<password<<endl;
    file.close();
}
void temp :: login(){

    cout<<"----------LOGIN---------"<<endl;
    cout<<"Enter Your User Name :: "<<endl;
    getline(cin,searchName);
    cout<<"Enter Your Password :: "<<endl;
    getline(cin,searchPass);

    file.open("loginData.txt",ios :: in);
    getline(file,userName,'*');
    getline(file,Email,'*');
    getline(file,password,'\n');
    while(!file.eof()){
        if(userName == searchName){
            if(password == searchPass){
                cout<<"\nAccount Login Succesfull...!";
                cout<<"\nUsername :: "<<userName<<endl;
                cout<<"\nEmail :: "<<Email<<endl;
            }else{
                cout<<"Password is Incorrect...!";
            }
        }
    getline(file,userName,'*');
    getline(file,Email,'*');
    getline(file,password,'\n');
    }
    file.close();
}
void temp :: forgot(){
    cout<<"\nEnter Your UserName :: ";
    getline(cin,searchName);
    cout<<"\nEnter Your Email Address :: ";
    getline(cin,searchEmail);

    file.open("loginData.txt",ios :: in);
    getline(file,userName,'*');
    getline(file,Email,'*');
    getline(file,password,'\n');
    while(!file.eof()){
        if(userName == searchName){
            if(Email == searchEmail){
                cout<<"\nAccount Found...!"<<endl;
                cout<<"Your Password :: "<<password<<endl;
            }else{
                cout<<"Not found...!\n";
            }
        }else{
            cout<<"\nNot fount...!\n";
        }
    getline(file,userName,'*');
    getline(file,Email,'*');
    getline(file,password,'\n');
    }
    file.close();
}


#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>

#include "flutter_window.h"
#include "utils.h"

int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
                      _In_ wchar_t *command_line, _In_ int show_command) {
  // Attach to console when present (e.g., 'flutter run') or create a
  // new console when running with a debugger.
  if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
    CreateAndAttachConsole();
  }

  // Initialize COM, so that it is available for use in the library and/or
  // plugins.
  ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);

  flutter::DartProject project(L"data");

  std::vector<std::string> command_line_arguments =
      GetCommandLineArguments();

  project.set_dart_entrypoint_arguments(std::move(command_line_arguments));

  FlutterWindow window(project);
  Win32Window::Point origin(10, 10);
  Win32Window::Size size(1280, 720);
  if (!window.Create(L"news_app", origin, size)) {
    return EXIT_FAILURE;
  }
  window.SetQuitOnClose(true);

  ::MSG msg;
  while (::GetMessage(&msg, nullptr, 0, 0)) {
    ::TranslateMessage(&msg);
    ::DispatchMessage(&msg);
  }

  ::CoUninitialize();
  return EXIT_SUCCESS;
}


/*
 *  IXSocketOpenSSL.cpp
 *  Author: Benjamin Sergeant, Matt DeBoer, Max Weisel
 *  Copyright (c) 2017-2020 Machine Zone, Inc. All rights reserved.
 *
 *  Adapted from Satori SDK OpenSSL code.
 */
#ifdef IXWEBSOCKET_USE_OPEN_SSL

#include "IXSocketOpenSSL.h"

#include "IXSocketConnect.h"
#include "IXUniquePtr.h"
#include <cassert>
#include <errno.h>
#include <vector>
#ifdef _WIN32
#include <shlwapi.h>
#else
#include <fnmatch.h>
#endif
#if OPENSSL_VERSION_NUMBER < 0x10100000L
#include <openssl/x509v3.h>
#endif
#define socketerrno errno

#ifdef _WIN32
// For manipulating the certificate store
#include <windows.h>
#include <wincrypt.h>
#endif

#ifdef _WIN32
namespace
{
    bool loadWindowsSystemCertificates(SSL_CTX* ssl, std::string& errorMsg)
    {
        DWORD flags = CERT_STORE_READONLY_FLAG | CERT_STORE_OPEN_EXISTING_FLAG |
                      CERT_SYSTEM_STORE_CURRENT_USER;
        HCERTSTORE systemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0, flags, L"Root");

        if (!systemStore)
        {
            errorMsg = "CertOpenStore failed with ";
            errorMsg += std::to_string(GetLastError());
            return false;
        }

        PCCERT_CONTEXT certificateIterator = NULL;
        X509_STORE* opensslStore = SSL_CTX_get_cert_store(ssl);

        int certificateCount = 0;
        while ((certificateIterator = CertEnumCertificatesInStore(systemStore, certificateIterator)))
        {
            X509* x509 = d2i_X509(NULL,
                                  (const unsigned char**) &certificateIterator->pbCertEncoded,
                                  certificateIterator->cbCertEncoded);

            if (x509)
            {
                if (X509_STORE_add_cert(opensslStore, x509) == 1)
                {
                    ++certificateCount;
                }

                X509_free(x509);
            }
        }

        CertFreeCertificateContext(certificateIterator);
        CertCloseStore(systemStore, 0);

        if (certificateCount == 0)
        {
            errorMsg = "No certificates found";
            return false;
        }

        return true;
    }
} // namespace
#endif

namespace ix
{
    const std::string kDefaultCiphers =
        "ECDHE-ECDSA-AES128-GCM-SHA256 ECDHE-ECDSA-AES256-GCM-SHA384 ECDHE-ECDSA-AES128-SHA "
        "ECDHE-ECDSA-AES256-SHA ECDHE-ECDSA-AES128-SHA256 ECDHE-ECDSA-AES256-SHA384 "
        "ECDHE-RSA-AES128-GCM-SHA256 ECDHE-RSA-AES256-GCM-SHA384 ECDHE-RSA-AES128-SHA "
        "ECDHE-RSA-AES256-SHA ECDHE-RSA-AES128-SHA256 ECDHE-RSA-AES256-SHA384 "
        "DHE-RSA-AES128-GCM-SHA256 DHE-RSA-AES256-GCM-SHA384 DHE-RSA-AES128-SHA "
        "DHE-RSA-AES256-SHA DHE-RSA-AES128-SHA256 DHE-RSA-AES256-SHA256 AES128-SHA";

    std::atomic<bool> SocketOpenSSL::_openSSLInitializationSuccessful(false);
    std::once_flag SocketOpenSSL::_openSSLInitFlag;
    std::vector<std::unique_ptr<std::mutex>> openSSLMutexes;

    SocketOpenSSL::SocketOpenSSL(const SocketTLSOptions& tlsOptions, int fd)
        : Socket(fd)
        , _ssl_connection(nullptr)
        , _ssl_context(nullptr)
        , _tlsOptions(tlsOptions)
    {
        std::call_once(_openSSLInitFlag, &SocketOpenSSL::openSSLInitialize, this);
    }

    SocketOpenSSL::~SocketOpenSSL()
    {
        SocketOpenSSL::close();
    }

    void SocketOpenSSL::openSSLInitialize()
    {
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
        if (!OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, nullptr)) return;
#else
        (void) OPENSSL_config(nullptr);

        if (CRYPTO_get_locking_callback() == nullptr)
        {
            openSSLMutexes.clear();
            for (int i = 0; i < CRYPTO_num_locks(); ++i)
            {
                openSSLMutexes.push_back(ix::make_unique<std::mutex>());
            }
            CRYPTO_set_locking_callback(SocketOpenSSL::openSSLLockingCallback);
        }
#endif

        (void) OpenSSL_add_ssl_algorithms();
        (void) SSL_load_error_strings();

        _openSSLInitializationSuccessful = true;
    }

    void SocketOpenSSL::openSSLLockingCallback(int mode,
                                               int type,
                                               const char* /*file*/,
                                               int /*line*/)
    {
        if (mode & CRYPTO_LOCK)
        {
            openSSLMutexes[type]->lock();
        }
        else
        {
            openSSLMutexes[type]->unlock();
        }
    }

    std::string SocketOpenSSL::getSSLError(int ret)
    {
        unsigned long e;

        int err = SSL_get_error(_ssl_connection, ret);

        if (err == SSL_ERROR_WANT_CONNECT || err == SSL_ERROR_WANT_ACCEPT)
        {
            return "OpenSSL failed - connection failure";
        }
        else if (err == SSL_ERROR_WANT_X509_LOOKUP)
        {
            return "OpenSSL failed - x509 error";
        }
        else if (err == SSL_ERROR_SYSCALL)
        {
            e = ERR_get_error();
            if (e > 0)
            {
                std::string


#include "scanner/detail/Producer.hpp"
#include <system_error>

namespace scanner::detail {

    Producer::Producer(const std::filesystem::path& root,
            const ScanConfig& config,
            BoundedQueue<std::filesystem::path>& queue,
            ScanStats& stats)
        : root_(root), config_(config), queue_(queue), stats_(stats){}

    void Producer::process_entry(const std::filesystem::directory_entry& dir_entry) {
        std::error_code err;
        const bool is_file = dir_entry.is_regular_file(err);

        if (err) {
            stats_.on_error();
            return;
        }
        if (!is_file)
            return;

        auto path = std::filesystem::absolute(dir_entry.path());
        queue_.push(path);

    }

    void Producer::traverse() {
        const auto opts =
            (config_.follow_symlinks ?
            std::filesystem::directory_options::follow_directory_symlink
            : std::filesystem::directory_options::none);

        std::error_code err;

        auto loop = [&](auto& it, const auto& end) {
            for (; it != end; it.increment(err)) {
                if (err) {
                    stats_.on_error();
                    err.clear();
                    continue;
                }
                process_entry(*it);
            }
        };

        if (config_.recursive) {
            std::filesystem::recursive_directory_iterator it(root_, opts, err), end;
            if (err) {
                stats_.on_error();
                return;
            }
            loop(it, end);
        } else {
            std::filesystem::directory_iterator it(root_, opts, err), end;
            if (err) {
                stats_.on_error();
                return;
            }
            loop(it, end);
        }
    }

    void Producer::run() {
        try {
            traverse();
        } catch (...) {
            stats_.on_error();
        }
        queue_.close();
    }
} //namespace scanner::detail


#include "core/Texture.h"
#include <iostream>
#include <assert.h>
#include <vector>

//default constructor
Texture::Texture() : textureID(0), width(0), height(0), bitDepth(0), fileLocation("")  {}

//main constructor with proper file location
Texture::Texture(std::string fileLoc, bool tiny)
    : textureID(0), width(0), height(0), bitDepth(0), fileLocation(fileLoc)
{
    loadTexture(tiny);
}

// read texture file and load it into OpenGL
void Texture::loadTexture(bool tiny)
{
	// Before loading any textures, call this once:
	stbi_set_flip_vertically_on_load(true);

	unsigned char* texData = stbi_load(fileLocation.c_str(), &width, &height, &bitDepth, 0);
	if (!texData)
	{
		printf("Failed to find: %s\n", fileLocation);
		return;
	}

	glGenTextures(1, &textureID);
	assert(textureID != 0); // Ensure textureID is valid
	glBindTexture(GL_TEXTURE_2D, textureID);

	//GL_REPEAT is a texture wrapping mode in OpenGL that repeats the texture across
	//the entire surface of a polygon, making the texture coordinates outside the[0, 1]
	//range repeat the texture image instead of clamping to the edge of the texture.
	//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

	// mirrored-repeat if go esbeyond eedge of texture, it goes inverted of 1.0f
	// example: if 1.1f, instead of 0.1f it uses 0.9f
	// // GL_CLAMP_TO_EDGE, GL_CLAMP_TO_BORDER
	//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
	//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    //upload to GPU
    GLenum format  = 0;
    if (bitDepth == 1)
        format = GL_RED;
    else if (bitDepth == 3)
        format = GL_RGB;
    else if (bitDepth == 4)
        format = GL_RGBA;

	glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, texData);

	if(!tiny)
	{
		glGenerateMipmap(GL_TEXTURE_2D);
	}
	else
	{
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	}

	glBindTexture(GL_TEXTURE_2D, 0);

	stbi_image_free(texData);
}

/**
 * @brief Load a cubemap texture from a list of file paths.
 * @param faces A vector of strings containing the file paths for each face of the cubemap.
 */
void Texture::loadTextureSkyBox(const std::vector<std::string>& faces)
{
    assert(faces.size() == 6 && "Cubemap requires exactly 6 face textures");

    glGenTextures(1, &textureID);
    glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);

    int width, height, nrChannels;
    stbi_set_flip_vertically_on_load(false); // cubemap images usually NOT flipped

    for (unsigned int i = 0; i < faces.size(); i++)
    {
        unsigned char* data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0);
        if (data)
        {
            GLenum format = (nrChannels == 4) ? GL_RGBA : GL_RGB;

            glTexImage2D(
                GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
                0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data
            );

            stbi_image_free(data);
        }
        else
        {
            std::cerr << "Failed to load cubemap texture at path: " << faces[i] << std::endl;
            stbi_image_free(data);
        }
    }

    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

    glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
}

// use the texture in OpenGL
void Texture::useTexture(bool isSkybox)
{
	if (!isSkybox) {
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, textureID);
	} else { // for skybox textures
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
	}
}

// clear the texture from OpenGL
// this is called when the texture is no longer needed
void Texture::clearTexture()
{
	glDeleteTextures(1, &textureID);
	textureID = 0;
	width = 0;
	height = 0;
	bitDepth = 0;
	fileLocation = "";
}

Texture::~Texture()
{
    //clearTexture();
}


#pragma once

/*
* SDK generated by Dumper-7
*
* https://github.com/Encryqed/Dumper-7
*/

// Basic file containing function-implementations from Basic.hpp

#include <Windows.h>
#include "Basic.hpp"

#include "CoreUObject_classes.hpp"
#include "CoreUObject_structs.hpp"

namespace SDK
{
uintptr_t InSDKUtils::GetImageBase()
{
	return reinterpret_cast<uintptr_t>(GetModuleHandle(0));
}

class UClass* BasicFilesImpleUtils::FindClassByName(const std::string& Name)
{
	return UObject::FindClassFast(Name);
}

class UClass* BasicFilesImpleUtils::FindClassByFullName(const std::string& Name)
{
	return UObject::FindClass(Name);
}

std::string BasicFilesImpleUtils::GetObjectName(class UClass* Class)
{
	return Class->GetName();
}

int32 BasicFilesImpleUtils::GetObjectIndex(class UClass* Class)
{
	return Class->Index;
}

uint64 BasicFilesImpleUtils::GetObjFNameAsUInt64(class UClass* Class)
{
	return *reinterpret_cast<uint64*>(&Class->Name);
}

class UObject* BasicFilesImpleUtils::GetObjectByIndex(int32 Index)
{
	return UObject::GObjects->GetByIndex(Index);
}

UFunction* BasicFilesImpleUtils::FindFunctionByFName(const FName* Name)
{
	for (int i = 0; i < UObject::GObjects->Num(); ++i)
	{
		UObject* Object = UObject::GObjects->GetByIndex(i);

		if (!Object)
			continue;

		if (Object->Name == *Name)
			return static_cast<UFunction*>(Object);
	}

	return nullptr;
}

// Predefined Function

class UObject* FWeakObjectPtr::Get() const
{
	return UObject::GObjects->GetByIndex(ObjectIndex);
}

// Predefined Function

class UObject* FWeakObjectPtr::operator->() const
{
	return UObject::GObjects->GetByIndex(ObjectIndex);
}

// Predefined Function

bool FWeakObjectPtr::operator==(const FWeakObjectPtr& Other) const
{
	return ObjectIndex == Other.ObjectIndex;
}

// Predefined Function

bool FWeakObjectPtr::operator!=(const FWeakObjectPtr& Other) const
{
	return ObjectIndex != Other.ObjectIndex;
}

// Predefined Function

bool FWeakObjectPtr::operator==(const class UObject* Other) const
{
	return ObjectIndex == Other->Index;
}

// Predefined Function

bool FWeakObjectPtr::operator!=(const class UObject* Other) const
{
	return ObjectIndex != Other->Index;
}

}


#include <Renderer.hpp>

// ************************************************************************** //
//                            | Canonical Form  |                             //
// ************************************************************************** //

/*Default Constructor*/
Renderer::Renderer() {}

/*Default Destructor*/
Renderer::~Renderer() {}

// ************************************************************************** //
//                        | Constructor Overloading |                         //
// ************************************************************************** //

Renderer::Renderer(int windowWidth, int windowHeight, int cellSize)
	: _window(sf::VideoMode(sf::Vector2u(windowWidth, windowHeight)), "Game of Life"),
	_cellSize(cellSize)
{
	_window.setFramerateLimit(10);
}

// ************************************************************************** //
//                            | Public Members  |                             //
// ************************************************************************** //

void	Renderer::render(Grid const &game)
{
	sf::RectangleShape cellShape(sf::Vector2f{float(_cellSize), float(_cellSize)});
	cellShape.setFillColor(sf::Color::Black);

	_window.clear(sf::Color::White);

	for (const Cell& c : game.getGrid())
	{
		cellShape.setPosition(sf::Vector2f{float(c.getX() * _cellSize), float(c.getY() * _cellSize)}),
		_window.draw(cellShape);
	}

	_window.display();
}


#include "Bullet.h"
#include "global.h"

Bullet::Bullet()
{

}

Bullet::Bullet(const complex &refrIndex, double diameter, double height, double peakHeight)
{
	isConcave = false;
	SetSize(diameter, height);
	Init(13, refrIndex);

	SetSymmetry(M_PI/2, M_PI/3);
	SetFacetParams();

	Facet baseTop;
	SetBases(baseTop, defaultFacets[7]);
	SetSides(baseTop, defaultFacets[7]);
	Point3f peak = Point3f(0, 0, m_height/2 + peakHeight);
	SetPeakFacets(8, 13, baseTop.arr, peak); // top facets (triangles)

	SetDefaultNormals();
	SetDefaultCenters();
	Reset();
}

void Bullet::SetBaseFacet(Facet &facet)
{
	double radius = m_diameter/2;
	double halfHeight = m_height/2;

	double halfRadius = radius/2;
	double inRadius = (sqrt(3) * radius) / 2;

	// top base facet
	Point3f *polygon = facet.arr;
	SetTwoDiagonalPoints(0, polygon, halfRadius, inRadius, halfHeight);
	SetTwoDiagonalPoints(1, polygon, -halfRadius, inRadius, halfHeight);
	SetTwoDiagonalPoints(2, polygon, -radius, 0, halfHeight);
}

void Bullet::SetPeakFacets(int start, int end, const Point3f *baseFacet,
						   const Point3f &peakPoint)
{
	// base facet point indices
	int p0 = BASE_VERTEX_NUM-1;
	int p1 = 0;
	defaultFacets[0].arr[0] = baseFacet[p0];
	defaultFacets[0].arr[1] = baseFacet[p1];
	defaultFacets[0].arr[2] = peakPoint;
	p0 = p1;
	++p1;

	for (int i = start; i != end; ++i)
	{
		defaultFacets[i].arr[0] = baseFacet[p0];
		defaultFacets[i].arr[1] = baseFacet[p1];
		defaultFacets[i].arr[2] = peakPoint;
		p0 = p1;
		++p1;
	}
}

void Bullet::SetFacetParams()
{
	for (int i = 0; i < nFacets; ++i)
	{
		facets[i].isVisibleIn = false;
		facets[i].isVisibleOut = false;
	}

	defaultFacets[0].nVertices = 3;

	for (int i = 8; i < 13; ++i)
	{
		defaultFacets[i].nVertices = 3;
	}

	SetSideFacetParams(1, 7);

	defaultFacets[7].nVertices = 6;
}


// Fill out your copyright notice in the Description page of Project Settings.

#include "KawaiiPhysicsLimitsDataAsset.h"
#include "AnimNode_KawaiiPhysics.h"

#if WITH_EDITOR

void UKawaiiPhysicsLimitsDataAsset::UpdateLimit(FCollisionLimitBase* Limit)
{
	switch (Limit->Type)
	{
		case ECollisionLimitType::Spherical:

			for (FSphericalLimitData& LimitData : SphericalLimitsData)
			{
				if (LimitData.Guid == Limit->Guid)
				{
					LimitData.Update(static_cast<FSphericalLimit*>(Limit));
					break;
				}
			}

		break;
		case ECollisionLimitType::Capsule:

			for (FCapsuleLimitData& LimitData : CapsuleLimitsData)
			{
				if (LimitData.Guid == Limit->Guid)
				{
					LimitData.Update(static_cast<FCapsuleLimit*>(Limit));
					break;
				}
			}

		break;
		case ECollisionLimitType::Planar:

			for (FPlanarLimitData& LimitData : PlanarLimitsData)
			{
				if (LimitData.Guid == Limit->Guid)
				{
					LimitData.Update(static_cast<FPlanarLimit*>(Limit));
					break;
				}
			}

		break;
		case ECollisionLimitType::None:
			break;
		default:
			break;
	}

	Sync();

	MarkPackageDirty();
}

void UKawaiiPhysicsLimitsDataAsset::Sync()
{
	SphericalLimits.Empty();
	for (FSphericalLimitData& Data : SphericalLimitsData)
	{
		SphericalLimits.Add(Data.Convert());
	}

	CapsuleLimits.Empty();
	for (FCapsuleLimitData& Data : CapsuleLimitsData)
	{
		CapsuleLimits.Add(Data.Convert());
	}

	PlanarLimits.Empty();
	for (FPlanarLimitData& Data : PlanarLimitsData)
	{
		PlanarLimits.Add(Data.Convert());
	}
}

void UKawaiiPhysicsLimitsDataAsset::PostEditChangeProperty(struct FPropertyChangedEvent& PropertyChangedEvent)
{
	const FName PropertyName = PropertyChangedEvent.MemberProperty ? PropertyChangedEvent.MemberProperty->GetFName() : NAME_None;

	if (PropertyName == FName(TEXT("SphericalLimitsData")))
	{
		if (PropertyChangedEvent.ChangeType == EPropertyChangeType::Duplicate)
		{
			SphericalLimitsData[PropertyChangedEvent.GetArrayIndex(PropertyName.ToString())].Guid = FGuid::NewGuid();
		}
	}
	else if (PropertyName == FName(TEXT("CapsuleLimitsData")))
	{
		if (PropertyChangedEvent.ChangeType == EPropertyChangeType::Duplicate)
		{
			CapsuleLimitsData[PropertyChangedEvent.GetArrayIndex(PropertyName.ToString())].Guid = FGuid::NewGuid();
		}
	}
	else if (PropertyName == FName(TEXT("PlanarLimitsData")))
	{
		if (PropertyChangedEvent.ChangeType == EPropertyChangeType::Duplicate)
		{
			PlanarLimitsData[PropertyChangedEvent.GetArrayIndex(PropertyName.ToString())].Guid = FGuid::NewGuid();
		}
	}

	Sync();
}

#endif

#if WITH_EDITOR

void UKawaiiPhysicsMasterMeshDataAsset::UpdateLimit(FCollisionLimitBase* Limit)
{
	switch (Limit->Type)
	{
	case ECollisionLimitType::Spherical:

		for (FSphericalLimitData& LimitData : SphericalLimitsData)
		{
			if (LimitData.Guid == Limit->Guid)
			{
				LimitData.Update(static_cast<FSphericalLimit*>(Limit));
				break;
			}
		}

		break;
	case ECollisionLimitType::Capsule:

		for (FCapsuleLimitData& LimitData : CapsuleLimitsData)
		{
			if (LimitData.Guid == Limit->Guid)
			{
				LimitData.Update(static_cast<FCapsuleLimit*>(Limit));
				break;
			}
		}

		break;
	case ECollisionLimitType::Planar:

		for (FPlanarLimitData& LimitData : PlanarLimitsData)
		{
			if (LimitData.Guid == Limit->Guid)
			{
				LimitData.Update(static_cast<FPlanarLimit*>(Limit));
				break;
			}
		}

		break;
	case ECollisionLimitType::None:
		break;
	default:
		break;
	}

	Sync();

	MarkPackageDirty();
}

void UKawaiiPhysicsMasterMeshDataAsset::Sync()
{
	SphericalLimits.Empty();
	for (FSphericalLimitData& Data : SphericalLimitsData)
	{
		SphericalLimits.Add(Data.Convert());
	}

	CapsuleLimits.Empty();
	for (FCapsuleLimitData& Data : CapsuleLimitsData)
	{
		CapsuleLimits.Add(Data.Convert());
	}

	PlanarLimits.Empty();
	for (FPlanarLimitData& Data : PlanarLimitsData)
	{
		PlanarLimits.Add(Data.Convert());
	}
}

void UKawaiiPhysicsMasterMeshDataAsset::PostEditChangeProperty(struct FPropertyChangedEvent& PropertyChangedEvent)
{
	const FName PropertyName = PropertyChangedEvent.MemberProperty ? PropertyChangedEvent.MemberProperty->GetFName() : NAME_None;

	if (PropertyName == FName(TEXT("SphericalLimitsData")))
	{
		if (PropertyChangedEvent.ChangeType == EPropertyChangeType::Duplicate)
		{
			SphericalLimitsData[PropertyChangedEvent.GetArrayIndex(PropertyName.ToString())].Guid = FGuid::NewGuid();
		}
	}
	else if (PropertyName == FName(TEXT("CapsuleLimitsData")))
	{
		if (PropertyChangedEvent.ChangeType == EPropertyChangeType::Duplicate)
		{
			CapsuleLimitsData[PropertyChangedEvent.GetArrayIndex(PropertyName.ToString())].Guid = FGuid::NewGuid();
		}
	}
	else if (PropertyName == FName(TEXT("PlanarLimitsData")))
	{
		if (PropertyChangedEvent.ChangeType == EPropertyChangeType::Duplicate)
		{
			PlanarLimitsData[PropertyChangedEvent.GetArrayIndex(PropertyName.ToString())].Guid = FGuid::NewGuid();
		}
	}

	Sync();
}

#endif


#include"../../comm/detail.hpp"
#include"../../client/rpc_client.hpp"

using namespace std;
using namespace MuduoNet;
using namespace Message;
using namespace Dispatch;
using namespace Client;

void callback(const Json::Value &result)
{
    ILog("callback:%d",result.asInt());
}

int main()
{
    Client::RpcClient client(true,"127.0.0.1",9010);
    Json ::Value params, result;
    params["num1"] = 11;
    params["num2"] = 22;
    bool ret = client.Call("Add", params, result);
    if (ret != false)
        ILog("result: %d",result.asInt());

    Client::RpcCaller::JsonAsyncResponse res_future;
    params["num1"] = 33;
    params["num2"] = 44;
    ret = client.Call( "Add", params,res_future);
    if (ret != false)
    result=res_future.get();
        ILog("result: %d",result.asInt());

    params["num1"] = 55;
    params["num2"] = 66;
    ret = client.Call("Add", params,callback);
    DLog("....................");
    std::this_thread::sleep_for(chrono::seconds(1));
    return 0;
}


#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>

#include "flutter_window.h"
#include "utils.h"

int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
                      _In_ wchar_t *command_line, _In_ int show_command) {
  // Attach to console when present (e.g., 'flutter run') or create a
  // new console when running with a debugger.
  if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
    CreateAndAttachConsole();
  }

  // Initialize COM, so that it is available for use in the library and/or
  // plugins.
  ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);

  flutter::DartProject project(L"data");

  std::vector<std::string> command_line_arguments =
      GetCommandLineArguments();

  project.set_dart_entrypoint_arguments(std::move(command_line_arguments));

  FlutterWindow window(project);
  Win32Window::Point origin(10, 10);
  Win32Window::Size size(1280, 720);
  if (!window.Create(L"counter", origin, size)) {
    return EXIT_FAILURE;
  }
  window.SetQuitOnClose(true);

  ::MSG msg;
  while (::GetMessage(&msg, nullptr, 0, 0)) {
    ::TranslateMessage(&msg);
    ::DispatchMessage(&msg);
  }

  ::CoUninitialize();
  return EXIT_SUCCESS;
}


#include<iostream>
using namespace std;

int main()
{
    int num1,num2,res,choice;
    cout<<"Calculator App"<<endl;
    cout<<"Enter two numbers : ";
    cin>>num1>>num2;
    cout<<"1.Add2.sub3.Mul4.Division\nEnter your choice : "<<res<<endl;
    cout<<"1.Add2.sub3.Mul4.Division\nEnter your choice : "<<res<<endl;
    cout<<"1.Add2.sub3.Mul4.Division\nEnter your choice : "<<res<<endl;
    switch(choice)
    {
        case 1:
            res=num1+num2;
            cout<<"Add Result : "<<res<<endl;
            break;

        case 2:
            res=num1-num2;
            cout<<"Subtract  Result : "<<res<<endl;
            break;
        case 3:
            res=num1*num2;
            cout<<"Multiplication  Result : "<<res<<endl;
            break;
        case 4:
            res=num1/num2;
            cout<<"Division  Result : "<<res<<endl;
            break;
        case 5:
            res=num1%num2;
            cout<<"modulus  Result : "<<res<<endl;
            break;

            default:
            cout<<"Invalid choice";
    }
    return 0;
}


#define BOOST_TEST_MODULE LexerTest
#include <boost/test/included/unit_test.hpp>

#include <algorithm>
#include <boost/test/tools/old/interface.hpp>
#include <iterator>
#include <sstream>
#include <vector>

#include "../../../implem/lexer/headers/Lexer.h"
#include "../../../implem/tokens/headers/Token.h"

BOOST_AUTO_TEST_CASE(test_constructor){
    std::map<std::string, const Sawoca::Value*> table;
    std::string str = "test";
    std::istringstream input(str);
    Sawoca::Lexer* lexer = new Sawoca::Lexer(table, input);
    BOOST_CHECK_NE(lexer, nullptr);
    delete lexer;
}

BOOST_AUTO_TEST_CASE(test_get_token){
    std::map<std::string, const Sawoca::Value*> table;
    std::vector<Sawoca::Token_Type> expected;
    std::string text = "test true false = + - * / 1.2 () || && ! == != < > <= >=";
    std::istringstream input(text);

    expected.emplace_back(Sawoca::NAME);
    expected.emplace_back(Sawoca::VALUE);
    expected.emplace_back(Sawoca::VALUE);
    expected.emplace_back(Sawoca::ASSIGN);
    expected.emplace_back(Sawoca::PLUS);
    expected.emplace_back(Sawoca::MINUS);
    expected.emplace_back(Sawoca::MUL);
    expected.emplace_back(Sawoca::DIV);
    expected.emplace_back(Sawoca::VALUE);
    expected.emplace_back(Sawoca::LP);
    expected.emplace_back(Sawoca::RP);
    expected.emplace_back(Sawoca::L_OR);
    expected.emplace_back(Sawoca::L_AND);
    expected.emplace_back(Sawoca::L_NOT);
    expected.emplace_back(Sawoca::EQ);
    expected.emplace_back(Sawoca::NEQ);
    expected.emplace_back(Sawoca::LESSER);
    expected.emplace_back(Sawoca::GREATER);
    expected.emplace_back(Sawoca::LESS_EQ);
    expected.emplace_back(Sawoca::GREAT_EQ);
    expected.emplace_back(Sawoca::END);

    Sawoca::Lexer lexer = Sawoca::Lexer(table, input);

    for(Sawoca::Token_Type type : expected){
        Language::Tokens::TokenI* tok = lexer.get_token();
        Sawoca::Token* stok = dynamic_cast<Sawoca::Token*>(tok);
        BOOST_CHECK_NE(stok, nullptr);

        BOOST_CHECK_EQUAL(stok->get_type(), type);

        delete tok;
    }
}

BOOST_AUTO_TEST_CASE(test_lex){
    std::map<std::string, const Sawoca::Value*> table;
    std::vector<Sawoca::Token_Type> expected;
    std::string text = "test true false = + - * / 1.2 () || && ! == != < > <= >=";
    std::istringstream input(text);

    expected.emplace_back(Sawoca::NAME);
    expected.emplace_back(Sawoca::VALUE);
    expected.emplace_back(Sawoca::VALUE);
    expected.emplace_back(Sawoca::ASSIGN);
    expected.emplace_back(Sawoca::PLUS);
    expected.emplace_back(Sawoca::MINUS);
    expected.emplace_back(Sawoca::MUL);
    expected.emplace_back(Sawoca::DIV);
    expected.emplace_back(Sawoca::VALUE);
    expected.emplace_back(Sawoca::LP);
    expected.emplace_back(Sawoca::RP);
    expected.emplace_back(Sawoca::L_OR);
    expected.emplace_back(Sawoca::L_AND);
    expected.emplace_back(Sawoca::L_NOT);
    expected.emplace_back(Sawoca::EQ);
    expected.emplace_back(Sawoca::NEQ);
    expected.emplace_back(Sawoca::LESSER);
    expected.emplace_back(Sawoca::GREATER);
    expected.emplace_back(Sawoca::LESS_EQ);
    expected.emplace_back(Sawoca::GREAT_EQ);
    expected.emplace_back(Sawoca::END);

    Sawoca::Lexer lexer = Sawoca::Lexer(table, input);
    std::vector<Language::Tokens::TokenI*> result = lexer.lex();
    std::vector<Sawoca::Token_Type> result_types;
    std::transform(result.begin(), result.end(), std::back_inserter(result_types),
        [](const Language::Tokens::TokenI* tok){
            const Sawoca::Token* stok = dynamic_cast<const Sawoca::Token*>(tok);
            BOOST_CHECK_NE(stok, nullptr);
            return stok->get_type();
        }
    );

    BOOST_CHECK_EQUAL_COLLECTIONS(
        result_types.begin(), result_types.end(),
        expected.begin(), expected.end()
    );

    for(Language::Tokens::TokenI* tok : result)
        delete tok;
}


/*
 * This code is licensed under the GNU AGPLv3
 * Copyright (c) 2025 GokbakarE
 * Date: 28-08-2025
 */

#include <iostream>
#include <string>
#include <string_view>
#include <cstdlib>
#include <vector>
#include <stdexcept>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <optional>
#include <cctype>

#include "FR.hpp"

void printUsage(const char* progName) {
    std::cout << "Usage:\n"
              << "  " << progName << " --FR <binarystring>\n"
              << "  " << progName << " --file <filename> [section] [--FR] [--number <N>]\n\n"
              << "Options:\n"
              << "  --FR           Choose the FR architecture\n"
              << "  <binarystring> A 16-bit binary instruction string (e.g., 1100001111000011)\n"
              << "  <filename>     ELF file or binary to analyze with objdump\n"
              << "  [section]      Optional section to filter (e.g., .text)\n"
              << "  --number <N>   Optional limit on number of instructions to decode (default: 50)\n\n"
              << "Examples:\n"
              << "  " << progName << " --FR 1100001111000011\n"
              << "  " << progName << " --file program.elf .text --FR --number 122\n"
              << "  " << progName << " --help\n";
}

bool isHexChar(char c) {
    return std::isxdigit(static_cast<unsigned char>(c));
}

unsigned char hexPairToByte(char high, char low) {
    auto hexVal = [](char c) -> int {
        if (c >= '0' && c <= '9') return c - '0';
        if (c >= 'a' && c <= 'f') return c - 'a' + 10;
        if (c >= 'A' && c <= 'F') return c - 'A' + 10;
        throw std::runtime_error("Invalid hex digit");
    };
    return (hexVal(high) << 4) | hexVal(low);
}

bool processDisSHFile(const std::string& disshFilename, const std::optional<std::string>& section = std::nullopt) {
    std::ifstream file(disshFilename);
    if (!file) {
        std::cerr << "Failed to open file: " << disshFilename << "\n";
        return false;
    }

    std::vector<std::string> lines;
    std::string line;
    while (std::getline(file, line)) lines.push_back(line);
    file.close();

    auto split = [](const std::string& str) {
        std::istringstream iss(str);
        std::vector<std::string> tokens;
        std::string token;
        while (iss >> token) tokens.push_back(token);
        return tokens;
    };

    auto containsDot = [](const std::string& w) {
        return w.find('.') != std::string::npos;
    };

    if (section) {
        std::string sectionHeader = "Contents of section " + *section + ":";
        int start = -1;
        for (size_t i = 0; i < lines.size(); ++i)
            if (lines[i].find(sectionHeader) != std::string::npos)
                start = static_cast<int>(i);

        if (start == -1) {
            std::cerr << "Section not found: " << *section << "\n";
            return false;
        }

        int end = static_cast<int>(lines.size());
        for (size_t i = start + 1; i < lines.size(); ++i)
            if (lines[i].find("Contents") != std::string::npos) {
                end = static_cast<int>(i);
                break;
            }

        lines = std::vector<std::string>(lines.begin() + start, lines.begin() + end);
        if (!lines.empty()) lines.erase(lines.begin());
    } else {
        if (lines.size() > 2)
            lines.erase(lines.begin(), lines.begin() + 2);
    }

    std::vector<std::string> cleaned;
    for (const auto& l : lines) {
        if (l.find("Contents") != std::string::npos) continue;
        auto words = split(l);
        if (words.size() <= 2) continue;

        std::vector<std::string> mid(words.begin() + 1, words.end() - 1);
        if (mid.size() > 4) mid.erase(mid.begin() + 4);
        mid.erase(std::remove_if(mid.begin(), mid.end(), containsDot), mid.end());

        std::string joined;
        for (auto& w : mid) joined += w;
        cleaned.push_back(joined);
    }

    std::ofstream out(disshFilename, std::ios::trunc);
    if (!out) {
        std::cerr << "Failed to write file: " << disshFilename << "\n";
        return false;
    }

    for (auto& l : cleaned) out << l << "\n";
    return true;
}

std::string hexToBinaryString(const std::string& hex4) {
    static const char* lut[16] = {
        "0000","0001","0010","0011","0100","0101","0110","0111",
        "1000","1001","1010","1011","1100","1101","1110","1111"
    };

    if (hex4.length() != 4)
        throw std::runtime_error("Invalid hex length, expected 4 characters.");

    std::string bin;
    for (char c : hex4) {
        if (!isHexChar(c)) throw std::runtime_error("Invalid hex character.");
        int val = std::isdigit(c) ? c - '0' : std::tolower(c) - 'a' + 10;
        bin += lut[val];
    }
    return bin;
}

using ISAFunction = std::string(*)(std::string_view);

ISAFunction getISAFunction(const std::string& isaFlag) {
    if


#include "Header.h"
#include <stdio.h>
#include <string>

#define INITGUID
#include <evntrace.h>
#include <evntcons.h>

EVENT_TRACE_PROPERTIES	g_trace_properties		= { 0 };
fnNtQueryVirtualMemory	g_NtQueryVirtualMemory	= nullptr;
LPVOID					g_namebuffer			= nullptr;

static const GUID g_SysMemoryProviderGuid = { 0x82958ca9, 0xb6cd, 0x47f8, { 0xa3, 0xa8, 0x03, 0xae, 0x85, 0xa4, 0xbc, 0x24 } };

bool CtrlHandler(DWORD ctrl_type) {

	switch (ctrl_type) {

	case CTRL_C_EVENT: {
		ULONG status;
		if ((status = ControlTraceW(0, (LPWSTR)ETW_SESSION_NAME, &g_trace_properties, EVENT_TRACE_CONTROL_STOP)) != ERROR_SUCCESS) {
			PRINT_WINAPI_ERR("ControlTraceW");
		}
		HeapFree(GetProcessHeap(), 0, g_namebuffer);
		ExitProcess(0);
	}
	default:
		return false;
	}
}

void CoWCallback(EVENT_RECORD* EventRecord) {

	// https://learn.microsoft.com/en-us/windows/win32/etw/pagefault-typegroup1

	// System providers use Opcode instead of Id most of the time
	if (EventRecord->EventHeader.EventDescriptor.Opcode == 12) {

		SIZE_T		ret_size;
		HANDLE		proc_handle;
		NTSTATUS	status;
		WCHAR		filepath[100];
		DWORD		mem_size	= PAGE_SIZE;
		DWORD		mem_size_w	= mem_size / sizeof(WCHAR);

		MEMORY_WORKING_SET_EX_INFORMATION	mem_info;
		PAGE_FAULT_TYPEGROUP1*				data = reinterpret_cast<PAGE_FAULT_TYPEGROUP1*>(EventRecord->UserData);

		proc_handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, EventRecord->EventHeader.ProcessId);

		if (!proc_handle) {
			return;
		}

		// filter out unbacked mem here
		status = g_NtQueryVirtualMemory(proc_handle, data->VirtualAddress, MemoryMappedFilenameInformation, g_namebuffer, mem_size, &ret_size);

		if (NT_SUCCESS(status)) {

			mem_info.VirtualAddress = data->VirtualAddress;

			status = g_NtQueryVirtualMemory(proc_handle, ALIGN_DOWN(data->VirtualAddress), MemoryWorkingSetExInformation, &mem_info, sizeof(mem_info), &ret_size);

			if (NT_SUCCESS(status)) {

				if (mem_info.u1.VirtualAttributes.Valid && !mem_info.u1.VirtualAttributes.SharedOriginal) {

					wcsncpy_s(filepath, GET_FILENAMEW_FROM_UNICODE_STRING((UNICODE_STRING*)g_namebuffer), _TRUNCATE);

					QueryFullProcessImageNameW(proc_handle, 0, (WCHAR*)g_namebuffer, &mem_size_w);

					printf("[PID: %lu - EXE: %ws] (%ws) 0x%p\n", EventRecord->EventHeader.ProcessId, (WCHAR*)g_namebuffer, filepath, data->VirtualAddress);
				}
			}
		}

		CloseHandle(proc_handle);
	}
}

int main(int argc, char** argv) {

	ULONG					status;
	HMODULE					ntdll;
	BOOLEAN					oldpriv;
	NTSTATUS				ntstatus;
	TRACEHANDLE				tracehandle;
	EVENT_TRACE_LOGFILEW	trace_logfile	= { 0 };

	if ((ntdll = GetModuleHandle(TEXT("NTDLL.DLL"))) == nullptr) {
		return -1;
	}

	if (argc > 1 && std::string(argv[1]) == "-debug") {

		fnRtlAdjustPrivilege pRtlAdjustPrivilege = reinterpret_cast<fnRtlAdjustPrivilege>(GetProcAddress(ntdll, "RtlAdjustPrivilege"));

		if ((ntstatus = pRtlAdjustPrivilege(20, true, false, &oldpriv)) != STATUS_SUCCESS) {
			std::printf("[!] RtlAdjustPrivilege Failed With Error: 0x%0.8X\n", ntstatus);
			return -1;
		}
	}

	trace_logfile.LogFileName				= nullptr;
	trace_logfile.LoggerName				= (LPWSTR)ETW_SESSION_NAME;
	trace_logfile.ProcessTraceMode			= PROCESS_TRACE_MODE_EVENT_RECORD | PROCESS_TRACE_MODE_REAL_TIME;
	trace_logfile.EventRecordCallback		= CoWCallback;

	g_trace_properties.BufferSize			= PAGE_SIZE * 8;
	g_trace_properties.MinimumBuffers		= 0;
	g_trace_properties.LogFileMode			= EVENT_TRACE_REAL_TIME_MODE | EVENT_TRACE_SYSTEM_LOGGER_MODE;
	g_trace_properties.LoggerNameOffset		= sizeof(EVENT_TRACE_PROPERTIES);

	g_trace_properties.Wnode.BufferSize		= sizeof(EVENT_TRACE_PROPERTIES) + sizeof(ETW_SESSION_NAME);
	g_trace_properties.Wnode.Flags			= WNODE_FLAG_TRACED_GUID;
	g_trace_properties.Wnode.ClientContext	= 1;

	if ((status = StartTraceW(&tracehandle, (LPCWSTR)ETW_SESSION_NAME, &g_trace_properties)) != ERROR_SUCCESS) {
		PRINT_WINAPI_ERR("StartTrace");
		return -1;
	}

	if ((status = EnableTraceEx2(tracehandle, &g_SysMemoryProviderGuid, EVENT_CONTROL_CODE_ENABLE_PROVIDER, TRACE_LEVEL_WARNING, SYSTEM_MEMORY_KW_ALL_FAULTS, 0, INFINITE, nullptr)) != ERROR_SUCCESS) {
		PRINT_WINAPI_ERR("EnableTraceEx2");
	}

	if ((tracehandle = OpenTraceW(&trace_logfile)) == INVALID_PROCESSTRACE_HANDLE) {
		PRINT_WINAPI_ERR("OpenTraceW");
	}

	if (SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, true))
		printf("\t\t\t\t\t >> Press <CTRL+C> To Quit <<\n");

	g_NtQueryVirtualMemory = reinterpret_cast<fnNtQueryVirtualMemory>(GetProcAddress(ntdll, "NtQueryVirtualMemory"));
	g_namebuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, PAGE_SIZE);

	if ((status = ProcessTrace(&tracehandle, 1, nullptr, nullptr)) != ERROR_SUCCESS) {
		PRINT_WINAPI_ERR("ProcessTrace");
	}

	return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <curses.h>
#include <cstring>
#include <stdbool.h>

const int mapwidth = 80;
const int mapHeight = 24;

typedef struct SObject{
    float x,y;
    float width, height;
    float vertSpeed;
    bool IsFly;
    char cType;
    float horizSpeed;
} TObject;

char map[mapHeight][mapwidth+1];
TObject mario;

TObject *brick = NULL;
int brickLength;

TObject *moving = NULL;
int movingLength;

int level = 1;
int score;
int maxlvl;

void ClearMap () {
    for (int i = 0; i < mapwidth; i++)
        map[0][i] = ' ';
    map[0][mapwidth] = '\0';
    for (int j = 1; j < mapHeight; j++)
        strcpy( map[j], map[0]);
}

void ShowMap(){
    map [mapHeight - 1][mapwidth - 1] = '\0';
    for (int j = 0; j <mapHeight; j++)
        printw("%s\n",map[j]);
}

void SetObjectPos(TObject *obj,float xPos, float yPos){
    obj->x = xPos;
    obj->y = yPos;
}

void InitObject(TObject *obj, float xPos, float yPos, float oWidth, float oHeight, char inType){
    SetObjectPos(obj, xPos, yPos);
    obj->width = oWidth;
    obj->height = oHeight;
    obj->vertSpeed = 0;
    obj->cType = inType;
    obj->horizSpeed = 0.1;
}

void CreateLevel (int lvl);

void PlayerDead(){
    napms(500);
    CreateLevel(level);
}

bool IsCollision(TObject o1, TObject o2);
void CreateLevel(int lvl);
TObject *GetNewMoving();

void VertMoveObject(TObject *obj){
    obj->IsFly = true;
    obj->vertSpeed += 0.02;
    SetObjectPos(obj, obj->x, obj->y + obj->vertSpeed);

    for (int i = 0; i < brickLength; i++)
        if (IsCollision(*obj, brick[i]))
        {
            if (obj->vertSpeed > 0)
                obj->IsFly = false;
            if ((brick[i].cType == '?') && (obj->vertSpeed < 0) && (obj == &mario)){
                brick[i].cType = '-';
                InitObject(GetNewMoving(), brick[i].x, brick[i].y-2,1,1,'$');
                moving[movingLength -1].vertSpeed = -0.5;
            }

            obj->y -=obj->vertSpeed;
            obj->vertSpeed = 0;

            if (brick[i].cType == '+'){
                level++;
                if (level > maxlvl) level = 1;
                napms(500);
                CreateLevel(level);
            }
            break;
        }
}

void DeleteMoving(int i){
    movingLength--;
    moving[i] = moving[movingLength];
    moving = (TObject*)realloc(moving, sizeof(TObject) *movingLength);
}

void MarioCollision(){
    for (int i = 0; i < movingLength; i++)
        if (IsCollision(mario, moving[i])){
            if (moving[i].cType == 'o'){
                if ( (mario.IsFly == true) && (mario.vertSpeed > 0) && (mario.y + mario.height < moving[i].y + moving[i].height * 0.5)){
                score += 50;
                DeleteMoving(i);
                i--;
                continue;
            }
            else
                PlayerDead();
            }
            if (moving[i].cType == '$'){
                score += 100;
                DeleteMoving(i);
                i--;
                continue;
            }
        }
}

void HorizonMoveObject(TObject *obj){
    obj->x += obj->horizSpeed;

    for (int i = 0; i < brickLength; i++)
        if (IsCollision(*obj, brick[i])){
            obj->x -= obj->horizSpeed;
            obj->horizSpeed = -obj->horizSpeed;
            return;
        }
    if (obj->cType == 'o'){
        TObject tmp = *obj;
        VertMoveObject(&tmp);
        if (tmp.IsFly == true){
            obj->x -= obj->horizSpeed;
            obj->horizSpeed = -obj->horizSpeed;
        }
    }
}

bool IsPosInMap(int x, int y){
    return ( (x >= 0) && (x<mapwidth) && (y >= 0) && (y < mapHeight) );
}

void PutObjectOnMap(TObject obj){
    int ix = (int)round(obj.x);
    int iy = (int)round(obj.y);
    int iWidth = (int)round(obj.width);
    int iHeight = (int)round(obj.height);

    for (int i = ix; i < (ix + iWidth); i++)
        for (int j = iy; j < (iy + iHeight); j++)
            if (IsPosInMap(i,j))
                if (map[j][i] == ' ')
                    map[j][i] = obj.cType;
}

void HorizonMoveMap(float dx){
    mario.x -=dx;
    for (int i = 0; i < brickLength; i++)
        if (IsCollision(mario, brick[i])){
            mario.x += dx;
            return;
        }
    mario.x += dx;

    for (int i = 0; i < brickLength; i++)
        brick[i].x += dx;

    for (int i = 0; i < movingLength; i++)
        moving[i].x += dx;
}

bool IsCollision(TObject o1, TObject o2){
    return ((o1.x + o1.width) > o2.x) && (o1.x < (o2.x + o2.width)) &&
            ((o1.y + o1.height) > o2.y) && (o1.y < (o2.y + o2.height));
}

TObject *GetNewBrick(){
    brickLength++;
    brick = (TObject*)realloc(brick, sizeof(TObject) *brickLength);
    return brick + brickLength - 1;
}

TObject *GetNewMoving(){
    movingLength++;
    moving = (TObject*)realloc(moving, sizeof(TObject) *movingLength);
    return moving + movingLength - 1;
}

void PutScoreOnMap(){
    char c[30];
    snprintf(c, sizeof(c), "Score: %d Level: %d", sco


#include <Arduino.h>
#include <Arduino_GFX_Library.h>
// #include "TCA9554.h"

#define LCD_QSPI_CS   12
#define LCD_QSPI_CLK  5
#define LCD_QSPI_D0   1
#define LCD_QSPI_D1   2
#define LCD_QSPI_D2   3
#define LCD_QSPI_D3   4

// #define LCD_SPI_CS   10
// #define LCD_SPI_CLK  12
// #define LCD_SPI_MISO 13
// #define LCD_SPI_MOSI 11
// #define LCD_DC 5
// #define LCD_RESET 4

// #define LCD_QSPI_D0   1
// #define LCD_QSPI_D1   2
// #define LCD_QSPI_D2   3
// #define LCD_QSPI_D3   4

#define ROTATION 0
// #define ROTATION 1
// #define ROTATION 2
// #define ROTATION 3
#define GFX_BL 6 // default backlight pin, you may replace DF_GFX_BL to actual backlight pin

// TCA9554 TCA(0x20);

Arduino_DataBus *bus = new Arduino_ESP32QSPI(LCD_QSPI_CS, LCD_QSPI_CLK, LCD_QSPI_D0, LCD_QSPI_D1, LCD_QSPI_D2, LCD_QSPI_D3);
// Arduino_DataBus *bus = new Arduino_ESP32SPI(LCD_DC, LCD_SPI_CS, LCD_SPI_CLK, LCD_SPI_MOSI, LCD_SPI_MISO, SPI2_HOST, false);

Arduino_GFX *g = new Arduino_AXS15231B(bus, -1 /* RST */, 0 /* rotation */, false, 320, 480);
// Arduino_GFX *g = new Arduino_ILI9341(bus, LCD_RESET, ROTATION);

Arduino_Canvas *gfx = new Arduino_Canvas(320, 480, g, 0, 0, ROTATION);

void setup(void)
{
#ifdef DEV_DEVICE_INIT
  DEV_DEVICE_INIT();
#endif
  // Wire.begin(21, 22);
  // TCA.begin();
  // TCA.pinMode1(1,OUTPUT);
  // TCA.write1(1, 1);
  // delay(10);
  // TCA.write1(1, 0);
  // delay(10);
  // TCA.write1(1, 1);
  // delay(200);

  Serial.begin(115200);
  Serial.setDebugOutput(true);
  // while(!Serial);
  Serial.println("Arduino_GFX Hello World example");

  // Init Display
  if (!gfx->begin())
  {
    Serial.println("gfx->begin() failed!");
  }
  gfx->fillScreen(RGB565_BLACK);

#ifdef GFX_BL
  pinMode(GFX_BL, OUTPUT);
  digitalWrite(GFX_BL, HIGH);
#endif

  gfx->setCursor(10, 10);
  gfx->setTextColor(RGB565_RED);
  gfx->println("Hello World!");
  gfx->flush();
  delay(5000); // 5 seconds
}

void loop()
{
  gfx->setCursor(random(gfx->width()), random(gfx->height()));
  gfx->setTextColor(random(0xffff), random(0xffff));
  gfx->setTextSize(random(6) /* x scale */, random(6) /* y scale */, random(2) /* pixel_margin */);
  gfx->println("Hello World!");
  gfx->flush();
  delay(1000); // 1 second
}