bdd787fdd4e3b44eb2181997f79f54488e36d75a
[demo] / src / terrain.cc
1 #include <gmath/gmath.h>
2
3 #include "camera.h"
4 #include "gfxapi.h"
5 #include "image.h"
6 #include "mesh.h"
7 #include "meshgen.h"
8 #include "object.h"
9 #include "scene.h"
10 #include "terrain.h"
11
12 static float calc_height(float u, float v, void *ptr);
13
14 Terrain::Terrain()
15 {
16         vis_scene = 0;
17 }
18
19 Terrain::~Terrain()
20 {
21 }
22
23 bool Terrain::init()
24 {
25         vis_scene = new Scene;
26
27         return true;
28 }
29
30 void Terrain::destroy()
31 {
32         delete vis_scene;
33 }
34
35 bool Terrain::generate(const TerrainParams &params)
36 {
37         tiles.clear();
38
39         float txsz = params.xsz / params.xtiles;
40         float tysz = params.ysz / params.ytiles;
41
42         for(int i=0; i<params.ytiles; i++) {
43                 for(int j=0; j<params.xtiles; j++) {
44                         TerrainTile tile;
45                         tile.mesh = gfx_create_mesh();
46
47                         gen_heightfield(tile.mesh, txsz, tysz, params.max_height,
48                                         params.tile_usub, params.tile_vsub, calc_height,
49                                         (void*)&params);
50
51                         tile.mesh->update_vertex_data();
52                         tiles.push_back(tile);
53
54 /*
55         the terrain scene stores objects only
56         no need to fill the mat, mesh std::vectors
57 */
58                         Object *o = new Object;
59                         o->mesh = tile.mesh;
60                         o->material = &material;
61                         o->transform = Mat4::identity;
62
63                         vis_scene->objects.push_back(o);
64                 }
65         }
66         return true;
67 }
68
69 Scene *Terrain::get_visible(const Camera *camera) const
70 {
71         return vis_scene;
72 }
73
74 static float calc_height(float u, float v, void *ptr)
75 {
76         if(!ptr) {
77                 fprintf(stderr, "Terrain parameters not found.\n");
78                 return 0;
79         }
80
81         TerrainParams *tp = (TerrainParams*)ptr;
82         float sn = gph::fbm(u * tp->noise_freq, v * tp->noise_freq, tp->num_octaves);
83         /* todo use the image later */
84         return sn;
85 }