summaryrefslogtreecommitdiff
path: root/src/candy_gear.cpp
blob: 484ce6a12f75e258672224ebce69b57d415cb90d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
 * Copyright 2022 Frederico de Oliveira Linhares
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "candy_gear.h"

#include <mruby/array.h>
#include <mruby/hash.h>
#include <mruby/string.h>

#include <yaml-cpp/yaml.h>

static mrb_value
parse_node(mrb_state *mrb, const YAML::Node &node)
{
  mrb_value value;
  std::string scalar;

  switch(node.Type())
  {
  case YAML::NodeType::Null:
    return mrb_nil_value();

  case YAML::NodeType::Scalar:
    scalar = node.as<std::string>();
    return mrb_str_new(mrb, scalar.data(), scalar.size());

  case YAML::NodeType::Sequence:
    value = mrb_ary_new_capa(mrb, node.size());
    for (YAML::const_iterator it = node.begin(); it != node.end(); it++)
      mrb_ary_push(mrb, value, parse_node(mrb, *it));
    return value;

  case YAML::NodeType::Map:
    value = mrb_hash_new_capa(mrb, node.size());
    for(YAML::const_iterator it = node.begin(); it != node.end(); it++)
      mrb_hash_set(
	mrb, value, parse_node(mrb, it->first), parse_node(mrb, it->second));
    return value;

  case YAML::NodeType::Undefined:
  default:
    return mrb_nil_value();
  }
}

static mrb_value
cg_mCandyGear_load_yaml(mrb_state *mrb, mrb_value self)
{
  const char *file_path;

  mrb_get_args(mrb, "z", &file_path);

  YAML::Node root = YAML::LoadFile(file_path);

  return parse_node(mrb, root);
}

static mrb_value
cg_mCandyGear_quit(mrb_state *mrb, mrb_value self)
{
  cg_core.quit_game = SDL_TRUE;

  return self;
}

void
cg_candy_gear_init(mrb_state *mrb)
{
  struct RClass *cg_m;

  cg_m = mrb_module_get(mrb, "CandyGear");
  mrb_define_class_method(
    mrb, cg_m, "load_yaml", cg_mCandyGear_load_yaml, MRB_ARGS_REQ(1));
  mrb_define_class_method(
    mrb, cg_m, "quit", cg_mCandyGear_quit, MRB_ARGS_NONE());
}