Skip to content
Myr

stb_voxel_render.h

This file

Path

stb_voxel_render.h

3,807 lines · 157.4 KiB · C

Last changed by

Fix trailing whitespaceSean Barrettbefore adoption2bb4a0a

History of this file

Take it

1// stb_voxel_render.h - v0.89 - Sean Barrett, 2015 - public domain2//3// This library helps render large-scale "voxel" worlds for games,4// in this case, one with blocks that can have textures and that5// can also be a few shapes other than cubes.6//7//    Video introduction:8//       http://www.youtube.com/watch?v=2vnTtiLrV1w9//10//    Minecraft-viewer sample app (not very simple though):11//       http://github.com/nothings/stb/tree/master/tests/caveview12//13// It works by creating triangle meshes. The library includes14//15//    - converter from dense 3D arrays of block info to vertex mesh16//    - vertex & fragment shaders for the vertex mesh17//    - assistance in setting up shader state18//19// For portability, none of the library code actually accesses20// the 3D graphics API. (At the moment, it's not actually portable21// since the shaders are GLSL only, but patches are welcome.)22//23// You have to do all the caching and tracking of vertex buffers24// yourself. However, you could also try making a game with25// a small enough world that it's fully loaded rather than26// streaming. Currently the preferred vertex format is 20 bytes27// per quad. There are designs to allow much more compact formats28// with a slight reduction in shader features, but no roadmap29// for actually implementing them.30//31//32// USAGE33//34//   #define the symbol STB_VOXEL_RENDER_IMPLEMENTATION in *one*35//   C/C++ file before the #include of this file; the implementation36//   will be generated in that file.37//38//   If you define the symbols STB_VOXEL_RENDER_STATIC, then the39//   implementation will be private to that file.40//41//42// FEATURES43//44//   - you can choose textured blocks with the features below,45//     or colored voxels with 2^24 colors and no textures.46//47//   - voxels are mostly just cubes, but there's support for48//     half-height cubes and diagonal slopes, half-height49//     diagonals, and even odder shapes especially for doing50//     more-continuous "ground".51//52//   - texture coordinates are projections along one of the major53//     axes, with the per-texture scaling.54//55//   - a number of aspects of the shader and the vertex format56//     are configurable; the library generally takes care of57//     coordinating the vertex format with the mesh for you.58//59//60// FEATURES (SHADER PERSPECTIVE)61//62//   - vertices aligned on integer lattice, z on multiples of 0.563//   - per-vertex "lighting" or "ambient occlusion" value (6 bits)64//   - per-vertex texture crossfade (3 bits)65//66//   - per-face texture #1 id (8-bit index into array texture)67//   - per-face texture #2 id (8-bit index into second array texture)68//   - per-face color (6-bit palette index, 2 bits of per-texture boolean enable)69//   - per-face 5-bit normal for lighting calculations & texture coord computation70//   - per-face 2-bit texture matrix rotation to rotate faces71//72//   - indexed-by-texture-id scale factor (separate for texture #1 and texture #2)73//   - indexed-by-texture-#2-id blend mode (alpha composite or modulate/multiply);74//     the first is good for decals, the second for detail textures, "light maps",75//     etc; both modes are controlled by texture #2's alpha, scaled by the76//     per-vertex texture crossfade and the per-face color (if enabled on texture #2);77//     modulate/multiply multiplies by an extra factor of 2.0 so that if you78//     make detail maps whose average brightness is 0.5 everything works nicely.79//80//   - ambient lighting: half-lambert directional plus constant, all scaled by vertex ao81//   - face can be fullbright (emissive), controlled by per-face color82//   - installable lighting, with default single-point-light83//   - installable fog, with default hacked smoothstep84//85//  Note that all the variations of lighting selection and texture86//  blending are run-time conditions in the shader, so they can be87//  intermixed in a single mesh.88//89//90// INTEGRATION ARC91//92//   The way to get this library to work from scratch is to do the following:93//94//      Step 1. define STBVOX_CONFIG_MODE to 095//96//        This mode uses only vertex attributes and uniforms, and is easiest97//        to get working. It requires 32 bytes per quad and limits the98//        size of some tables to avoid hitting uniform limits.99//100//      Step 2. define STBVOX_CONFIG_MODE to 1101//102//        This requires using a texture buffer to store the quad data,103//        reducing the size to 20 bytes per quad.104//105//      Step 3: define STBVOX_CONFIG_PREFER_TEXBUFFER106//107//        This causes some uniforms to be stored as texture buffers108//        instead. This increases the size of some of those tables,109//        and avoids a potential slow path (gathering non-uniform110//        data from uniforms) on some hardware.111//112//   In the future I might add additional modes that have significantly113//   smaller meshes but reduce features, down as small as 6 bytes per quad.114//   See elsewhere in this file for a table of candidate modes. Switching115//   to a mode will require changing some of your mesh creation code, but116//   everything else should be seamless. (And I'd like to change the API117//   so that mesh creation is data-driven the way the uniforms are, and118//   then you wouldn't even have to change anything but the mode number.)119//120//121// IMPROVEMENTS FOR SHIP-WORTHY PROGRAMS USING THIS LIBRARY122//123//   I currently tolerate a certain level of "bugginess" in this library.124//125//   I'm referring to things which look a little wrong (as long as they126//   don't cause holes or cracks in the output meshes), or things which127//   do not produce as optimal a mesh as possible. Notable examples:128//129//        -  incorrect lighting on slopes130//        -  inefficient meshes for vheight blocks131//132//   I am willing to do the work to improve these things if someone is133//   going to ship a substantial program that would be improved by them.134//   (It need not be commercial, nor need it be a game.) I just didn't135//   want to do the work up front if it might never be leveraged. So just136//   submit a bug report as usual (github is preferred), but add a note137//   that this is for a thing that is really going to ship. (That means138//   you need to be far enough into the project that it's clear you're139//   committed to it; not during early exploratory development.)140//141//142// VOXEL MESH API143//144//   Context145//146//     To understand the API, make sure you first understand the feature set147//     listed above.148//149//     Because the vertices are compact, they have very limited spatial150//     precision. Thus a single mesh can only contain the data for a limited151//     area. To make very large voxel maps, you'll need to build multiple152//     vertex buffers. (But you want this anyway for frustum culling.)153//154//     Each generated mesh has three components:155//             - vertex data (vertex buffer)156//             - face data (optional, stored in texture buffer)157//             - mesh transform (uniforms)158//159//     Once you've generated the mesh with this library, it's up to you160//     to upload it to the GPU, to keep track of the state, and to render161//     it.162//163//   Concept164//165//     The basic design is that you pass in one or more 3D arrays; each array166//     is (typically) one-byte-per-voxel and contains information about one167//     or more properties of some particular voxel property.168//169//     Because there is so much per-vertex and per-face data possible170//     in the output, and each voxel can have 6 faces and 8 vertices, it171//     would require an very large data structure to describe all172//     of the possibilities, and this would cause the mesh-creation173//     process to be slow. Instead, the API provides multiple ways174//     to express each property, some more compact, others less so;175//     each such way has some limitations on what it can express.176//177//     Note that there are so many paths and combinations, not all of them178//     have been tested. Just report bugs and I'll fix 'em.179//180//   Details181//182//     See the API documentation in the header-file section.183//184//185// CONTRIBUTORS186//187//   Features             Porting            Bugfixes & Warnings188//  Sean Barrett                          github:r-leyh   Jesus Fernandez189//                                        Miguel Lechon   github:Arbeiterunfallversicherungsgesetz190//                                        Thomas Frase    James Hofmann191//                                        Stephen Olsen   github:guitarfreak192//193// VERSION HISTORY194//195//   0.89   (2020-02-02)  bugfix in sample code196//   0.88   (2019-03-04)  fix warnings197//   0.87   (2019-02-25)  fix warning198//   0.86   (2019-02-07)  fix typos in comments199//   0.85   (2017-03-03)  add block_selector (by guitarfreak)200//   0.84   (2016-04-02)  fix GLSL syntax error on glModelView path201//   0.83   (2015-09-13)  remove non-constant struct initializers to support more compilers202//   0.82   (2015-08-01)  added input.packed_compact to store rot, vheight & texlerp efficiently203//                        fix broken tex_overlay2204//   0.81   (2015-05-28)  fix broken STBVOX_CONFIG_OPTIMIZED_VHEIGHT205//   0.80   (2015-04-11)  fix broken STBVOX_CONFIG_ROTATION_IN_LIGHTING refactoring206//                        change STBVOX_MAKE_LIGHTING to STBVOX_MAKE_LIGHTING_EXT so207//                                    that header defs don't need to see config vars208//                        add STBVOX_CONFIG_VHEIGHT_IN_LIGHTING and other vheight fixes209//                        added documentation for vheight ("weird slopes")210//   0.79   (2015-04-01)  fix the missing types from 0.78; fix string constants being const211//   0.78   (2015-04-02)  bad "#else", compile as C++212//   0.77   (2015-04-01)  documentation tweaks, rename config var to STB_VOXEL_RENDER_STATIC213//   0.76   (2015-04-01)  typos, signed/unsigned shader issue, more documentation214//   0.75   (2015-04-01)  initial release215//216//217// HISTORICAL FOUNDATION218//219//   stb_voxel_render   20-byte quads   2015/01220//   zmc engine         32-byte quads   2013/12221//   zmc engine         96-byte quads   2011/10222//223//224// LICENSE225//226//   See end of file for license information.227228#ifndef INCLUDE_STB_VOXEL_RENDER_H229#define INCLUDE_STB_VOXEL_RENDER_H230231#include <stdlib.h>232233typedef struct stbvox_mesh_maker stbvox_mesh_maker;234typedef struct stbvox_input_description stbvox_input_description;235236#ifdef STB_VOXEL_RENDER_STATIC237#define STBVXDEC static238#else239#define STBVXDEC extern240#endif241242#ifdef __cplusplus243extern "C" {244#endif245246//////////////////////////////////////////////////////////////////////////////247//248// CONFIGURATION MACROS249//250//  #define STBVOX_CONFIG_MODE <integer>           // REQUIRED251//     Configures the overall behavior of stb_voxel_render. This252//     can affect the shaders, the uniform info, and other things.253//     (If you need more than one mode in the same app, you can254//     use STB_VOXEL_RENDER_STATIC to create multiple versions255//     in separate files, and then wrap them.)256//257//         Mode value       Meaning258//             0               Textured blocks, 32-byte quads259//             1               Textured blocks, 20-byte quads260//            20               Untextured blocks, 32-byte quads261//            21               Untextured blocks, 20-byte quads262//263//264//  #define STBVOX_CONFIG_PRECISION_Z  <integer>   // OPTIONAL265//     Defines the number of bits of fractional position for Z.266//     Only 0 or 1 are valid. 1 is the default. If 0, then a267//     single mesh has twice the legal Z range; e.g. in268//     modes 0,1,20,21, Z in the mesh can extend to 511 instead269//     of 255. However, half-height blocks cannot be used.270//271// All of the following are just #ifdef tested so need no values, and are optional.272//273//    STBVOX_CONFIG_BLOCKTYPE_SHORT274//        use unsigned 16-bit values for 'blocktype' in the input instead of 8-bit values275//276//    STBVOX_CONFIG_OPENGL_MODELVIEW277//        use the gl_ModelView matrix rather than the explicit uniform278//279//    STBVOX_CONFIG_HLSL280//        NOT IMPLEMENTED! Define HLSL shaders instead of GLSL shaders281//282//    STBVOX_CONFIG_PREFER_TEXBUFFER283//        Stores many of the uniform arrays in texture buffers instead,284//        so they can be larger and may be more efficient on some hardware.285//286//    STBVOX_CONFIG_LIGHTING_SIMPLE287//        Creates a simple lighting engine with a single point light source288//        in addition to the default half-lambert ambient light.289//290//    STBVOX_CONFIG_LIGHTING291//        Declares a lighting function hook; you must append a lighting function292//        to the shader before compiling it:293//            vec3 compute_lighting(vec3 pos, vec3 norm, vec3 albedo, vec3 ambient);294//        'ambient' is the half-lambert ambient light with vertex ambient-occlusion applied295//296//    STBVOX_CONFIG_FOG_SMOOTHSTEP297//        Defines a simple unrealistic fog system designed to maximize298//        unobscured view distance while not looking too weird when things299//        emerge from the fog. Configured using an extra array element300//        in the STBVOX_UNIFORM_ambient uniform.301//302//    STBVOX_CONFIG_FOG303//        Defines a fog function hook; you must append a fog function to304//        the shader before compiling it:305//            vec3 compute_fog(vec3 color, vec3 relative_pos, float fragment_alpha);306//        "color" is the incoming pre-fogged color, fragment_alpha is the alpha value,307//        and relative_pos is the vector from the point to the camera in worldspace308//309//    STBVOX_CONFIG_DISABLE_TEX2310//        This disables all processing of texture 2 in the shader in case311//        you don't use it. Eventually this could be replaced with a mode312//        that omits the unused data entirely.313//314//    STBVOX_CONFIG_TEX1_EDGE_CLAMP315//    STBVOX_CONFIG_TEX2_EDGE_CLAMP316//        If you want to edge clamp the textures, instead of letting them wrap,317//        set this flag. By default stb_voxel_render relies on texture wrapping318//        to simplify texture coordinate generation. This flag forces it to do319//        it correctly, although there can still be minor artifacts.320//321//    STBVOX_CONFIG_ROTATION_IN_LIGHTING322//        Changes the meaning of the 'lighting' mesher input variable to also323//        store the rotation; see later discussion.324//325//    STBVOX_CONFIG_VHEIGHT_IN_LIGHTING326//        Changes the meaning of the 'lighting' mesher input variable to also327//        store the vheight; see later discussion. Cannot use both this and328//        the previous variable.329//330//    STBVOX_CONFIG_PREMULTIPLIED_ALPHA331//        Adjusts the shader calculations on the assumption that tex1.rgba,332//        tex2.rgba, and color.rgba all use premultiplied values, and that333//        the output of the fragment shader should be premultiplied.334//335//    STBVOX_CONFIG_UNPREMULTIPLY336//        Only meaningful if STBVOX_CONFIG_PREMULTIPLIED_ALPHA is defined.337//        Changes the behavior described above so that the inputs are338//        still premultiplied alpha, but the output of the fragment339//        shader is not premultiplied alpha. This is needed when allowing340//        non-unit alpha values but not doing alpha-blending (for example341//        when alpha testing).342//343344//////////////////////////////////////////////////////////////////////////////345//346// MESHING347//348// A mesh represents a (typically) small chunk of a larger world.349// Meshes encode coordinates using small integers, so those350// coordinates must be relative to some base location.351// All of the coordinates in the functions below use352// these relative coordinates unless explicitly stated353// otherwise.354//355// Input to the meshing step is documented further down356357STBVXDEC void stbvox_init_mesh_maker(stbvox_mesh_maker *mm);358// Call this function to initialize a mesh-maker context structure359// used to build meshes. You should have one context per thread360// that's building meshes.361362STBVXDEC void stbvox_set_buffer(stbvox_mesh_maker *mm, int mesh, int slot, void *buffer, size_t len);363// Call this to set the buffer into which stbvox will write the mesh364// it creates. It can build more than one mesh in parallel (distinguished365// by the 'mesh' parameter), and each mesh can be made up of more than366// one buffer (distinguished by the 'slot' parameter).367//368// Multiple meshes are under your control; use the 'selector' input369// variable to choose which mesh each voxel's vertices are written to.370// For example, you can use this to generate separate meshes for opaque371// and transparent data.372//373// You can query the number of slots by calling stbvox_get_buffer_count374// described below. The meaning of the buffer for each slot depends375// on STBVOX_CONFIG_MODE.376//377//   In mode 0 & mode 20, there is only one slot. The mesh data for that378//   slot is two interleaved vertex attributes: attr_vertex, a single379//   32-bit uint, and attr_face, a single 32-bit uint.380//381//   In mode 1 & mode 21, there are two slots. The first buffer should382//   be four times as large as the second buffer. The first buffer383//   contains a single vertex attribute: 'attr_vertex', a single 32-bit uint.384//   The second buffer contains texture buffer data (an array of 32-bit uints)385//   that will be accessed through the sampler identified by STBVOX_UNIFORM_face_data.386387STBVXDEC int stbvox_get_buffer_count(stbvox_mesh_maker *mm);388// Returns the number of buffers needed per mesh as described above.389390STBVXDEC int stbvox_get_buffer_size_per_quad(stbvox_mesh_maker *mm, int slot);391// Returns how much of a given buffer will get used per quad. This392// allows you to choose correct relative sizes for each buffer, although393// the values are fixed based on the configuration you've selected at394// compile time, and the details are described in stbvox_set_buffer.395396STBVXDEC void stbvox_set_default_mesh(stbvox_mesh_maker *mm, int mesh);397// Selects which mesh the mesher will output to (see previous function)398// if the input doesn't specify a per-voxel selector. (I doubt this is399// useful, but it's here just in case.)400401STBVXDEC stbvox_input_description *stbvox_get_input_description(stbvox_mesh_maker *mm);402// This function call returns a pointer to the stbvox_input_description part403// of stbvox_mesh_maker (which you should otherwise treat as opaque). You404// zero this structure, then fill out the relevant pointers to the data405// describing your voxel object/world.406//407// See further documentation at the description of stbvox_input_description below.408409STBVXDEC void stbvox_set_input_stride(stbvox_mesh_maker *mm, int x_stride_in_elements, int y_stride_in_elements);410// This sets the stride between successive elements of the 3D arrays411// in the stbvox_input_description. Z values are always stored consecutively.412// (The preferred coordinate system for stbvox is X right, Y forwards, Z up.)413414STBVXDEC void stbvox_set_input_range(stbvox_mesh_maker *mm, int x0, int y0, int z0, int x1, int y1, int z1);415// This sets the range of values in the 3D array for the voxels that416// the mesh generator will convert. The lower values are inclusive,417// the higher values are exclusive, so (0,0,0) to (16,16,16) generates418// mesh data associated with voxels up to (15,15,15) but no higher.419//420// The mesh generate generates faces at the boundary between open space421// and solid space but associates them with the solid space, so if (15,0,0)422// is open and (16,0,0) is solid, then the mesh will contain the boundary423// between them if x0 <= 16 and x1 > 16.424//425// Note that the mesh generator will access array elements 1 beyond the426// limits set in these parameters. For example, if you set the limits427// to be (0,0,0) and (16,16,16), then the generator will access all of428// the voxels between (-1,-1,-1) and (16,16,16), including (16,16,16).429// You may have to do pointer arithmetic to make it work.430//431// For example, caveview processes mesh chunks that are 32x32x16, but it432// does this using input buffers that are 34x34x18.433//434// The lower limits are x0 >= 0, y0 >= 0, and z0 >= 0.435//436// The upper limits are mode dependent, but all the current methods are437// limited to x1 < 127, y1 < 127, z1 < 255. Note that these are not438// powers of two; if you want to use power-of-two chunks (to make439// it efficient to decide which chunk a coordinate falls in), you're440// limited to at most x1=64, y1=64, z1=128. For classic Minecraft-style441// worlds with limited vertical extent, I recommend using a single442// chunk for the entire height, which limits the height to 255 blocks443// (one less than Minecraft), and only chunk the map in X & Y.444445STBVXDEC int stbvox_make_mesh(stbvox_mesh_maker *mm);446// Call this function to create mesh data for the currently configured447// set of input data. This appends to the currently configured mesh output448// buffer. Returns 1 on success. If there is not enough room in the buffer,449// it outputs as much as it can, and returns 0; you need to switch output450// buffers (either by calling stbvox_set_buffer to set new buffers, or451// by copying the data out and calling stbvox_reset_buffers), and then452// call this function again without changing any of the input parameters.453//454// Note that this function appends; you can call it multiple times to455// build a single mesh. For example, caveview uses chunks that are456// 32x32x255, but builds the mesh for it by processing 32x32x16 at atime457// (this is faster as it is reuses the same 34x34x18 input buffers rather458// than needing 34x34x257 input buffers).459460// Once you're done creating a mesh into a given buffer,461// consider the following functions:462463STBVXDEC int stbvox_get_quad_count(stbvox_mesh_maker *mm, int mesh);464// Returns the number of quads in the mesh currently generated by mm.465// This is the sum of all consecutive stbvox_make_mesh runs appending466// to the same buffer. 'mesh' distinguishes between the multiple user467// meshes available via 'selector' or stbvox_set_default_mesh.468//469// Typically you use this function when you're done building the mesh470// and want to record how to draw it.471//472// Note that there are no index buffers; the data stored in the buffers473// should be drawn as quads (e.g. with GL_QUAD); if your API does not474// support quads, you can create a single index buffer large enough to475// draw your largest vertex buffer, and reuse it for every rendering.476// (Note that if you use 32-bit indices, you'll use 24 bytes of bandwidth477// per quad, more than the 20 bytes for the vertex/face mesh data.)478479STBVXDEC void stbvox_set_mesh_coordinates(stbvox_mesh_maker *mm, int x, int y, int z);480// Sets the global coordinates for this chunk, such that (0,0,0) relative481// coordinates will be at (x,y,z) in global coordinates.482483STBVXDEC void stbvox_get_bounds(stbvox_mesh_maker *mm, float bounds[2][3]);484// Returns the bounds for the mesh in global coordinates. Use this485// for e.g. frustum culling the mesh. @BUG: this just uses the486// values from stbvox_set_input_range(), so if you build by487// appending multiple values, this will be wrong, and you need to488// set stbvox_set_input_range() to the full size. Someday this489// will switch to tracking the actual bounds of the *mesh*, though.490491STBVXDEC void stbvox_get_transform(stbvox_mesh_maker *mm, float transform[3][3]);492// Returns the 'transform' data for the shader uniforms. It is your493// job to set this to the shader before drawing the mesh. It is the494// only uniform that needs to change per-mesh. Note that it is not495// a 3x3 matrix, but rather a scale to decode fixed point numbers as496// floats, a translate from relative to global space, and a special497// translation for texture coordinate generation that avoids498// floating-point precision issues. @TODO: currently we add the499// global translation to the vertex, than multiply by modelview,500// but this means if camera location and vertex are far from the501// origin, we lose precision. Need to make a special modelview with502// the translation (or some of it) factored out to avoid this.503504STBVXDEC void stbvox_reset_buffers(stbvox_mesh_maker *mm);505// Call this function if you're done with the current output buffer506// but want to reuse it (e.g. you're done appending with507// stbvox_make_mesh and you've copied the data out to your graphics API508// so can reuse the buffer).509510//////////////////////////////////////////////////////////////////////////////511//512// RENDERING513//514515STBVXDEC char *stbvox_get_vertex_shader(void);516// Returns the (currently GLSL-only) vertex shader.517518STBVXDEC char *stbvox_get_fragment_shader(void);519// Returns the (currently GLSL-only) fragment shader.520// You can override the lighting and fogging calculations521// by appending data to the end of these; see the #define522// documentation for more information.523524STBVXDEC char *stbvox_get_fragment_shader_alpha_only(void);525// Returns a slightly cheaper fragment shader that computes526// alpha but not color. This is useful for e.g. a depth-only527// pass when using alpha test.528529typedef struct stbvox_uniform_info stbvox_uniform_info;530531STBVXDEC int stbvox_get_uniform_info(stbvox_uniform_info *info, int uniform);532// Gets the information about a uniform necessary for you to533// set up each uniform with a minimal amount of explicit code.534// See the sample code after the structure definition for stbvox_uniform_info,535// further down in this header section.536//537// "uniform" is from the list immediately following. For many538// of these, default values are provided which you can set.539// Most values are shared for most draw calls; e.g. for stateful540// APIs you can set most of the state only once. Only541// STBVOX_UNIFORM_transform needs to change per draw call.542//543// STBVOX_UNIFORM_texscale544//    64- or 128-long vec4 array. (128 only if STBVOX_CONFIG_PREFER_TEXBUFFER)545//    x: scale factor to apply to texture #1. must be a power of two. 1.0 means 'face-sized'546//    y: scale factor to apply to texture #2. must be a power of two. 1.0 means 'face-sized'547//    z: blend mode indexed by texture #2. 0.0 is alpha compositing; 1.0 is multiplication.548//    w: unused currently. @TODO use to support texture animation?549//550//    Texscale is indexed by the bottom 6 or 7 bits of the texture id; thus for551//    example the texture at index 0 in the array and the texture in index 128 of552//    the array must be scaled the same. This means that if you only have 64 or 128553//    unique textures, they all get distinct values anyway; otherwise you have554//    to group them in pairs or sets of four.555//556// STBVOX_UNIFORM_ambient557//    4-long vec4 array:558//      ambient[0].xyz   - negative of direction of a directional light for half-lambert559//      ambient[1].rgb   - color of light scaled by NdotL (can be negative)560//      ambient[2].rgb   - constant light added to above calculation;561//                         effectively light ranges from ambient[2]-ambient[1] to ambient[2]+ambient[1]562//      ambient[3].rgb   - fog color for STBVOX_CONFIG_FOG_SMOOTHSTEP563//      ambient[3].a     - reciprocal of squared distance of farthest fog point (viewing distance)564565566                               //  +----- has a default value567                               //  |  +-- you should always use the default value568enum                           //  V  V569{                              //  ------------------------------------------------570   STBVOX_UNIFORM_face_data,   //  n      the sampler with the face texture buffer571   STBVOX_UNIFORM_transform,   //  n      the transform data from stbvox_get_transform572   STBVOX_UNIFORM_tex_array,   //  n      an array of two texture samplers containing the two texture arrays573   STBVOX_UNIFORM_texscale,    //  Y      a table of texture properties, see above574   STBVOX_UNIFORM_color_table, //  Y      64 vec4 RGBA values; a default palette is provided; if A > 1.0, fullbright575   STBVOX_UNIFORM_normals,     //  Y  Y   table of normals, internal-only576   STBVOX_UNIFORM_texgen,      //  Y  Y   table of texgen vectors, internal-only577   STBVOX_UNIFORM_ambient,     //  n      lighting & fog info, see above578   STBVOX_UNIFORM_camera_pos,  //  Y      camera position in global voxel space (for lighting & fog)579580   STBVOX_UNIFORM_count,581};582583enum584{585   STBVOX_UNIFORM_TYPE_none,586   STBVOX_UNIFORM_TYPE_sampler,587   STBVOX_UNIFORM_TYPE_vec2,588   STBVOX_UNIFORM_TYPE_vec3,589   STBVOX_UNIFORM_TYPE_vec4,590};591592struct stbvox_uniform_info593{594   int type;                    // which type of uniform595   int bytes_per_element;       // the size of each uniform array element (e.g. vec3 = 12 bytes)596   int array_length;            // length of the uniform array597   char *name;                  // name in the shader @TODO use numeric binding598   float *default_value;        // if not NULL, you can use this as the uniform pointer599   int use_tex_buffer;          // if true, then the uniform is a sampler but the data can come from default_value600};601602//////////////////////////////////////////////////////////////////////////////603//604// Uniform sample code605//606607#if 0608// Run this once per frame before drawing all the meshes.609// You still need to separately set the 'transform' uniform for every mesh.610void setup_uniforms(GLuint shader, float camera_pos[4], GLuint tex1, GLuint tex2)611{612   int i;613   glUseProgram(shader); // so uniform binding works614   for (i=0; i < STBVOX_UNIFORM_count; ++i) {615      stbvox_uniform_info sui;616      if (stbvox_get_uniform_info(&sui, i)) {617         GLint loc = glGetUniformLocation(shader, sui.name);618         if (loc != -1) {619            switch (i) {620               case STBVOX_UNIFORM_camera_pos: // only needed for fog621                  glUniform4fv(loc, sui.array_length, camera_pos);622                  break;623624               case STBVOX_UNIFORM_tex_array: {625                  GLuint tex_unit[2] = { 0, 1 }; // your choice of samplers626                  glUniform1iv(loc, 2, tex_unit);627628                  glActiveTexture(GL_TEXTURE0 + tex_unit[0]); glBindTexture(GL_TEXTURE_2D_ARRAY, tex1);629                  glActiveTexture(GL_TEXTURE0 + tex_unit[1]); glBindTexture(GL_TEXTURE_2D_ARRAY, tex2);630                  glActiveTexture(GL_TEXTURE0); // reset to default631                  break;632               }633634               case STBVOX_UNIFORM_face_data:635                  glUniform1i(loc, SAMPLER_YOU_WILL_BIND_PER_MESH_FACE_DATA_TO);636                  break;637638               case STBVOX_UNIFORM_ambient:     // you definitely want to override this639               case STBVOX_UNIFORM_color_table: // you might want to override this640               case STBVOX_UNIFORM_texscale:    // you may want to override this641                  glUniform4fv(loc, sui.array_length, sui.default_value);642                  break;643644               case STBVOX_UNIFORM_normals:     // you never want to override this645               case STBVOX_UNIFORM_texgen:      // you never want to override this646                  glUniform3fv(loc, sui.array_length, sui.default_value);647                  break;648            }649         }650      }651   }652}653#endif654655#ifdef __cplusplus656}657#endif658659//////////////////////////////////////////////////////////////////////////////660//661// INPUT TO MESHING662//663664// Shapes of blocks that aren't always cubes665enum666{667   STBVOX_GEOM_empty,668   STBVOX_GEOM_knockout,  // creates a hole in the mesh669   STBVOX_GEOM_solid,670   STBVOX_GEOM_transp,    // solid geometry, but transparent contents so neighbors generate normally, unless same blocktype671672   // following 4 can be represented by vheight as well673   STBVOX_GEOM_slab_upper,674   STBVOX_GEOM_slab_lower,675   STBVOX_GEOM_floor_slope_north_is_top,676   STBVOX_GEOM_ceil_slope_north_is_bottom,677678   STBVOX_GEOM_floor_slope_north_is_top_as_wall_UNIMPLEMENTED,   // same as floor_slope above, but uses wall's texture & texture projection679   STBVOX_GEOM_ceil_slope_north_is_bottom_as_wall_UNIMPLEMENTED,680   STBVOX_GEOM_crossed_pair,    // corner-to-corner pairs, with normal vector bumped upwards681   STBVOX_GEOM_force,           // like GEOM_transp, but faces visible even if neighbor is same type, e.g. minecraft fancy leaves682683   // these access vheight input684   STBVOX_GEOM_floor_vheight_03 = 12,  // diagonal is SW-NE685   STBVOX_GEOM_floor_vheight_12,       // diagonal is SE-NW686   STBVOX_GEOM_ceil_vheight_03,687   STBVOX_GEOM_ceil_vheight_12,688689   STBVOX_GEOM_count, // number of geom cases690};691692enum693{694   STBVOX_FACE_east,695   STBVOX_FACE_north,696   STBVOX_FACE_west,697   STBVOX_FACE_south,698   STBVOX_FACE_up,699   STBVOX_FACE_down,700701   STBVOX_FACE_count,702};703704#ifdef STBVOX_CONFIG_BLOCKTYPE_SHORT705typedef unsigned short stbvox_block_type;706#else707typedef unsigned char stbvox_block_type;708#endif709710// 24-bit color711typedef struct712{713   unsigned char r,g,b;714} stbvox_rgb;715716#define STBVOX_COLOR_TEX1_ENABLE   64717#define STBVOX_COLOR_TEX2_ENABLE  128718719// This is the data structure you fill out. Most of the arrays can be720// NULL, except when one is required to get the value to index another.721//722// The compass system used in the following descriptions is:723//     east means increasing x724//     north means increasing y725//     up means increasing z726struct stbvox_input_description727{728   unsigned char lighting_at_vertices;729   // The default is lighting values (i.e. ambient occlusion) are at block730   // center, and the vertex light is gathered from those adjacent block731   // centers that the vertex is facing. This makes smooth lighting732   // consistent across adjacent faces with the same orientation.733   //734   // Setting this flag to non-zero gives you explicit control735   // of light at each vertex, but now the lighting/ao will be736   // shared by all vertices at the same point, even if they737   // have different normals.738739   // these are mostly 3D maps you use to define your voxel world, using x_stride and y_stride740   // note that for cache efficiency, you want to use the block_foo palettes as much as possible instead741742   stbvox_rgb *rgb;743   // Indexed by 3D coordinate.744   // 24-bit voxel color for STBVOX_CONFIG_MODE = 20 or 21 only745746   unsigned char *lighting;747   // Indexed by 3D coordinate. The lighting value / ambient occlusion748   // value that is used to define the vertex lighting values.749   // The raw lighting values are defined at the center of blocks750   // (or at vertex if 'lighting_at_vertices' is true).751   //752   // If the macro STBVOX_CONFIG_ROTATION_IN_LIGHTING is defined,753   // then an additional 2-bit block rotation value is stored754   // in this field as well.755   //756   // Encode with STBVOX_MAKE_LIGHTING_EXT(lighting,rot)--here757   // 'lighting' should still be 8 bits, as the macro will758   // discard the bottom bits automatically. Similarly, if759   // using STBVOX_CONFIG_VHEIGHT_IN_LIGHTING, encode with760   // STBVOX_MAKE_LIGHTING_EXT(lighting,vheight).761   //762   // (Rationale: rotation needs to be independent of blocktype,763   // but is only 2 bits so doesn't want to be its own array.764   // Lighting is the one thing that was likely to already be765   // in use and that I could easily steal 2 bits from.)766767   stbvox_block_type *blocktype;768   // Indexed by 3D coordinate. This is a core "block type" value, which is used769   // to index into other arrays; essentially a "palette". This is much more770   // memory-efficient and performance-friendly than storing the values explicitly,771   // but only makes sense if the values are always synchronized.772   //773   // If a voxel's blocktype is 0, it is assumed to be empty (STBVOX_GEOM_empty),774   // and no other blocktypes should be STBVOX_GEOM_empty. (Only if you do not775   // have blocktypes should STBVOX_GEOM_empty ever used.)776   //777   // Normally it is an unsigned byte, but you can override it to be778   // a short if you have too many blocktypes.779780   unsigned char *geometry;781   // Indexed by 3D coordinate. Contains the geometry type for the block.782   // Also contains a 2-bit rotation for how the whole block is rotated.783   // Also includes a 2-bit vheight value when using shared vheight values.784   // See the separate vheight documentation.785   // Encode with STBVOX_MAKE_GEOMETRY(geom, rot, vheight)786787   unsigned char *block_geometry;788   // Array indexed by blocktype containing the geometry for this block, plus789   // a 2-bit "simple rotation". Note rotation has limited use since it's not790   // independent of blocktype.791   //792   // Encode with STBVOX_MAKE_GEOMETRY(geom,simple_rot,0)793794   unsigned char *block_tex1;795   // Array indexed by blocktype containing the texture id for texture #1.796797   unsigned char (*block_tex1_face)[6];798   // Array indexed by blocktype and face containing the texture id for texture #1.799   // The N/E/S/W face choices can be rotated by one of the rotation selectors;800   // The top & bottom face textures will rotate to match.801   // Note that it only makes sense to use one of block_tex1 or block_tex1_face;802   // this pattern repeats throughout and this notice is not repeated.803804   unsigned char *tex2;805   // Indexed by 3D coordinate. Contains the texture id for texture #2806   // to use on all faces of the block.807808   unsigned char *block_tex2;809   // Array indexed by blocktype containing the texture id for texture #2.810811   unsigned char (*block_tex2_face)[6];812   // Array indexed by blocktype and face containing the texture id for texture #2.813   // The N/E/S/W face choices can be rotated by one of the rotation selectors;814   // The top & bottom face textures will rotate to match.815816   unsigned char *color;817   // Indexed by 3D coordinate. Contains the color for all faces of the block.818   // The core color value is 0..63.819   // Encode with STBVOX_MAKE_COLOR(color_number, tex1_enable, tex2_enable)820821   unsigned char *block_color;822   // Array indexed by blocktype containing the color value to apply to the faces.823   // The core color value is 0..63.824   // Encode with STBVOX_MAKE_COLOR(color_number, tex1_enable, tex2_enable)825826   unsigned char (*block_color_face)[6];827   // Array indexed by blocktype and face containing the color value to apply to that face.828   // The core color value is 0..63.829   // Encode with STBVOX_MAKE_COLOR(color_number, tex1_enable, tex2_enable)830831   unsigned char *block_texlerp;832   // Array indexed by blocktype containing 3-bit scalar for texture #2 alpha833   // (known throughout as 'texlerp'). This is constant over every face even834   // though the property is potentially per-vertex.835836   unsigned char (*block_texlerp_face)[6];837   // Array indexed by blocktype and face containing 3-bit scalar for texture #2 alpha.838   // This is constant over the face even though the property is potentially per-vertex.839840   unsigned char *block_vheight;841   // Array indexed by blocktype containing the vheight values for the842   // top or bottom face of this block. These will rotate properly if the843   // block is rotated. See discussion of vheight.844   // Encode with STBVOX_MAKE_VHEIGHT(sw_height, se_height, nw_height, ne_height)845846   unsigned char *selector;847   // Array indexed by 3D coordinates indicating which output mesh to select.848849   unsigned char *block_selector;850   // Array indexed by blocktype indicating which output mesh to select.851852   unsigned char *side_texrot;853   // Array indexed by 3D coordinates encoding 2-bit texture rotations for the854   // faces on the E/N/W/S sides of the block.855   // Encode with STBVOX_MAKE_SIDE_TEXROT(rot_e, rot_n, rot_w, rot_s)856857   unsigned char *block_side_texrot;858   // Array indexed by blocktype encoding 2-bit texture rotations for the faces859   // on the E/N/W/S sides of the block.860   // Encode with STBVOX_MAKE_SIDE_TEXROT(rot_e, rot_n, rot_w, rot_s)861862   unsigned char *overlay;                 // index into palettes listed below863   // Indexed by 3D coordinate. If 0, there is no overlay. If non-zero,864   // it indexes into to the below arrays and overrides the values865   // defined by the blocktype.866867   unsigned char (*overlay_tex1)[6];868   // Array indexed by overlay value and face, containing an override value869   // for the texture id for texture #1. If 0, the value defined by blocktype870   // is used.871872   unsigned char (*overlay_tex2)[6];873   // Array indexed by overlay value and face, containing an override value874   // for the texture id for texture #2. If 0, the value defined by blocktype875   // is used.876877   unsigned char (*overlay_color)[6];878   // Array indexed by overlay value and face, containing an override value879   // for the face color. If 0, the value defined by blocktype is used.880881   unsigned char *overlay_side_texrot;882   // Array indexed by overlay value, encoding 2-bit texture rotations for the faces883   // on the E/N/W/S sides of the block.884   // Encode with STBVOX_MAKE_SIDE_TEXROT(rot_e, rot_n, rot_w, rot_s)885886   unsigned char *rotate;887   // Indexed by 3D coordinate. Allows independent rotation of several888   // parts of the voxel, where by rotation I mean swapping textures889   // and colors between E/N/S/W faces.890   //    Block: rotates anything indexed by blocktype891   //    Overlay: rotates anything indexed by overlay892   //    EColor: rotates faces defined in ecolor_facemask893   // Encode with STBVOX_MAKE_MATROT(block,overlay,ecolor)894895   unsigned char *tex2_for_tex1;896   // Array indexed by tex1 containing the texture id for texture #2.897   // You can use this if the two are always/almost-always strictly898   // correlated (e.g. if tex2 is a detail texture for tex1), as it899   // will be more efficient (touching fewer cache lines) than using900   // e.g. block_tex2_face.901902   unsigned char *tex2_replace;903   // Indexed by 3D coordinate. Specifies the texture id for texture #2904   // to use on a single face of the voxel, which must be E/N/W/S (not U/D).905   // The texture id is limited to 6 bits unless tex2_facemask is also906   // defined (see below).907   // Encode with STBVOX_MAKE_TEX2_REPLACE(tex2, face)908909   unsigned char *tex2_facemask;910   // Indexed by 3D coordinate. Specifies which of the six faces should911   // have their tex2 replaced by the value of tex2_replace. In this912   // case, all 8 bits of tex2_replace are used as the texture id.913   // Encode with STBVOX_MAKE_FACE_MASK(east,north,west,south,up,down)914915   unsigned char *extended_color;916   // Indexed by 3D coordinate. Specifies a value that indexes into917   // the ecolor arrays below (both of which must be defined).918919   unsigned char *ecolor_color;920   // Indexed by extended_color value, specifies an optional override921   // for the color value on some faces.922   // Encode with STBVOX_MAKE_COLOR(color_number, tex1_enable, tex2_enable)923924   unsigned char *ecolor_facemask;925   // Indexed by extended_color value, this specifies which faces the926   // color in ecolor_color should be applied to. The faces can be927   // independently rotated by the ecolor value of 'rotate', if it exists.928   // Encode with STBVOX_MAKE_FACE_MASK(e,n,w,s,u,d)929930   unsigned char *color2;931   // Indexed by 3D coordinates, specifies an alternative color to apply932   // to some of the faces of the block.933   // Encode with STBVOX_MAKE_COLOR(color_number, tex1_enable, tex2_enable)934935   unsigned char *color2_facemask;936   // Indexed by 3D coordinates, specifies which faces should use the937   // color defined in color2. No rotation value is applied.938   // Encode with STBVOX_MAKE_FACE_MASK(e,n,w,s,u,d)939940   unsigned char *color3;941   // Indexed by 3D coordinates, specifies an alternative color to apply942   // to some of the faces of the block.943   // Encode with STBVOX_MAKE_COLOR(color_number, tex1_enable, tex2_enable)944945   unsigned char *color3_facemask;946   // Indexed by 3D coordinates, specifies which faces should use the947   // color defined in color3. No rotation value is applied.948   // Encode with STBVOX_MAKE_FACE_MASK(e,n,w,s,u,d)949950   unsigned char *texlerp_simple;951   // Indexed by 3D coordinates, this is the smallest texlerp encoding952   // that can do useful work. It consits of three values: baselerp,953   // vertlerp, and face_vertlerp. Baselerp defines the value954   // to use on all of the faces but one, from the STBVOX_TEXLERP_BASE955   // values. face_vertlerp is one of the 6 face values (or STBVOX_FACE_NONE)956   // which specifies the face should use the vertlerp values.957   // Vertlerp defines a lerp value at every vertex of the mesh.958   // Thus, one face can have per-vertex texlerp values, and those959   // values are encoded in the space so that they will be shared960   // by adjacent faces that also use vertlerp, allowing continuity961   // (this is used for the "texture crossfade" bit of the release video).962   // Encode with STBVOX_MAKE_TEXLERP_SIMPLE(baselerp, vertlerp, face_vertlerp)963964   // The following texlerp encodings are experimental and maybe not965   // that useful.966967   unsigned char *texlerp;968   // Indexed by 3D coordinates, this defines four values:969   //   vertlerp is a lerp value at every vertex of the mesh (using STBVOX_TEXLERP_BASE values).970   //   ud is the value to use on up and down faces, from STBVOX_TEXLERP_FACE values971   //   ew is the value to use on east and west faces, from STBVOX_TEXLERP_FACE values972   //   ns is the value to use on north and south faces, from STBVOX_TEXLERP_FACE values973   // If any of ud, ew, or ns is STBVOX_TEXLERP_FACE_use_vert, then the974   // vertlerp values for the vertices are gathered and used for those faces.975   // Encode with STBVOX_MAKE_TEXLERP(vertlerp,ud,ew,sw)976977   unsigned short *texlerp_vert3;978   // Indexed by 3D coordinates, this works with texlerp and979   // provides a unique texlerp value for every direction at980   // every vertex. The same rules of whether faces share values981   // applies. The STBVOX_TEXLERP_FACE vertlerp value defined in982   // texlerp is only used for the down direction. The values at983   // each vertex in other directions are defined in this array,984   // and each uses the STBVOX_TEXLERP3 values (i.e. full precision985   // 3-bit texlerp values).986   // Encode with STBVOX_MAKE_VERT3(vertlerp_e,vertlerp_n,vertlerp_w,vertlerp_s,vertlerp_u)987988   unsigned short *texlerp_face3;          // e:3,n:3,w:3,s:3,u:2,d:2989   // Indexed by 3D coordinates, this provides a compact way to990   // fully specify the texlerp value indepenendly for every face,991   // but doesn't allow per-vertex variation. E/N/W/S values are992   // encoded using STBVOX_TEXLERP3 values, whereas up and down993   // use STBVOX_TEXLERP_SIMPLE values.994   // Encode with STBVOX_MAKE_FACE3(face_e,face_n,face_w,face_s,face_u,face_d)995996   unsigned char *vheight;                 // STBVOX_MAKE_VHEIGHT   -- sw:2, se:2, nw:2, ne:2, doesn't rotate997   // Indexed by 3D coordinates, this defines the four998   // vheight values to use if the geometry is STBVOX_GEOM_vheight*.999   // See the vheight discussion.10001001   unsigned char *packed_compact;1002   // Stores block rotation, vheight, and texlerp values:1003   //    block rotation: 2 bits1004   //    vertex vheight: 2 bits1005   //    use_texlerp   : 1 bit1006   //    vertex texlerp: 3 bits1007   // If STBVOX_CONFIG_UP_TEXLERP_PACKED is defined, then 'vertex texlerp' is1008   // used for up faces if use_texlerp is 1. If STBVOX_CONFIG_DOWN_TEXLERP_PACKED1009   // is defined, then 'vertex texlerp' is used for down faces if use_texlerp is 1.1010   // Note if those symbols are defined but packed_compact is NULL, the normal1011   // texlerp default will be used.1012   // Encode with STBVOX_MAKE_PACKED_COMPACT(rot, vheight, texlerp, use_texlerp)1013};1014// @OPTIMIZE allow specializing; build a single struct with all of the1015// 3D-indexed arrays combined so it's AoS instead of SoA for better1016// cache efficiency101710181019//////////////////////////////////////////////////////////////////////////////1020//1021//  VHEIGHT DOCUMENTATION1022//1023//  "vheight" is the internal name for the special block types1024//  with sloped tops or bottoms. "vheight" stands for "vertex height".1025//1026//  Note that these blocks are very flexible (there are 256 of them,1027//  although at least 17 of them should never be used), but they1028//  also have a disadvantage that they generate extra invisible1029//  faces; the generator does not currently detect whether adjacent1030//  vheight blocks hide each others sides, so those side faces are1031//  always generated. For a continuous ground terrain, this means1032//  that you may generate 5x as many quads as needed. See notes1033//  on "improvements for shipping products" in the introduction.10341035enum1036{1037   STBVOX_VERTEX_HEIGHT_0,1038   STBVOX_VERTEX_HEIGHT_half,1039   STBVOX_VERTEX_HEIGHT_1,1040   STBVOX_VERTEX_HEIGHT_one_and_a_half,1041};1042// These are the "vheight" values. Vheight stands for "vertex height".1043// The idea is that for a "floor vheight" block, you take a cube and1044// reposition the top-most vertices at various heights as specified by1045// the vheight values. Similarly, a "ceiling vheight" block takes a1046// cube and repositions the bottom-most vertices.1047//1048// A floor block only adjusts the top four vertices; the bottom four vertices1049// remain at the bottom of the block. The height values are 2 bits,1050// measured in halves of a block; so you can specify heights of 0/2,1051// 1/2, 2/2, or 3/2. 0 is the bottom of the block, 1 is halfway1052// up the block, 2 is the top of the block, and 3 is halfway up the1053// next block (and actually outside of the block). The value 3 is1054// actually legal for floor vheight (but not ceiling), and allows you to:1055//1056//     (A) have smoother terrain by having slopes that cross blocks,1057//         e.g. (1,1,3,3) is a regular-seeming slope halfway between blocks1058//     (B) make slopes steeper than 45-degrees, e.g. (0,0,3,3)1059//1060// (Because only z coordinates have half-block precision, and x&y are1061// limited to block corner precision, it's not possible to make these1062// things "properly" out of blocks, e.g. a half-slope block on its side1063// or a sloped block halfway between blocks that's made out of two blocks.)1064//1065// If you define STBVOX_CONFIG_OPTIMIZED_VHEIGHT, then the top face1066// (or bottom face for a ceiling vheight block) will be drawn as a1067// single quad even if the four vertex heights aren't planar, and a1068// single normal will be used over the entire quad. If you1069// don't define it, then if the top face is non-planar, it will be1070// split into two triangles, each with their own normal/lighting.1071// (Note that since all output from stb_voxel_render is quad meshes,1072// triangles are actually rendered as degenerate quads.) In this case,1073// the distinction between STBVOX_GEOM_floor_vheight_03 and1074// STBVOX_GEOM_floor_vheight_12 comes into play; the former introduces1075// an edge from the SW to NE corner (i.e. from <0,0,?> to <1,1,?>),1076// while the latter introduces an edge from the NW to SE corner1077// (i.e. from <0,1,?> to <1,0,?>.) For a "lazy mesh" look, use1078// exclusively _03 or _12. For a "classic mesh" look, alternate1079// _03 and _12 in a checkerboard pattern. For a "smoothest surface"1080// look, choose the edge based on actual vertex heights.1081//1082// The four vertex heights can come from several places. The simplest1083// encoding is to just use the 'vheight' parameter which stores four1084// explicit vertex heights for every block. This allows total independence,1085// but at the cost of the largest memory usage, 1 byte per 3D block.1086// Encode this with STBVOX_MAKE_VHEIGHT(vh_sw, vh_se, vh_nw, vh_ne).1087// These coordinates are absolute, not affected by block rotations.1088//1089// An alternative if you just want to encode some very specific block1090// types, not all the possibilities--say you just want half-height slopes,1091// so you want (0,0,1,1) and (1,1,2,2)--then you can use block_vheight1092// to specify them. The geometry rotation will cause block_vheight values1093// to be rotated (because it's as if you're just defining a type of1094// block). This value is also encoded with STBVOX_MAKE_VHEIGHT.1095//1096// If you want to save memory and you're creating a "continuous ground"1097// sort of effect, you can make each vertex of the lattice share the1098// vheight value; that is, two adjacent blocks that share a vertex will1099// always get the same vheight value for that vertex. Then you need to1100// store two bits of vheight for every block, which you do by storing it1101// as part another data structure. Store the south-west vertex's vheight1102// with the block. You can either use the "geometry" mesh variable (it's1103// a parameter to STBVOX_MAKE_GEOMETRY) or you can store it in the1104// "lighting" mesh variable if you defined STBVOX_CONFIG_VHEIGHT_IN_LIGHTING,1105// using STBVOX_MAKE_LIGHTING_EXT(lighting,vheight).1106//1107// Note that if you start with a 2D height map and generate vheight data from1108// it, you don't necessarily store only one value per (x,y) coordinate,1109// as the same value may need to be set up at multiple z heights. For1110// example, if height(8,8) = 13.5, then you want the block at (8,8,13)1111// to store STBVOX_VERTEX_HEIGHT_half, and this will be used by blocks1112// at (7,7,13), (8,7,13), (7,8,13), and (8,8,13). However, if you're1113// allowing steep slopes, it might be the case that you have a block1114// at (7,7,12) which is supposed to stick up to 13.5; that means1115// you also need to store STBVOX_VERTEX_HEIGHT_one_and_a_half at (8,8,12).11161117enum1118{1119   STBVOX_TEXLERP_FACE_0,1120   STBVOX_TEXLERP_FACE_half,1121   STBVOX_TEXLERP_FACE_1,1122   STBVOX_TEXLERP_FACE_use_vert,1123};11241125enum1126{1127   STBVOX_TEXLERP_BASE_0,    // 0.01128   STBVOX_TEXLERP_BASE_2_7,  // 2/71129   STBVOX_TEXLERP_BASE_5_7,  // 4/71130   STBVOX_TEXLERP_BASE_1     // 1.01131};11321133enum1134{1135   STBVOX_TEXLERP3_0_8,1136   STBVOX_TEXLERP3_1_8,1137   STBVOX_TEXLERP3_2_8,1138   STBVOX_TEXLERP3_3_8,1139   STBVOX_TEXLERP3_4_8,1140   STBVOX_TEXLERP3_5_8,1141   STBVOX_TEXLERP3_6_8,1142   STBVOX_TEXLERP3_7_8,1143};11441145#define STBVOX_FACE_NONE  711461147#define STBVOX_BLOCKTYPE_EMPTY    011481149#ifdef STBVOX_BLOCKTYPE_SHORT1150#define STBVOX_BLOCKTYPE_HOLE  655351151#else1152#define STBVOX_BLOCKTYPE_HOLE    2551153#endif11541155#define STBVOX_MAKE_GEOMETRY(geom, rotate, vheight) ((geom) + (rotate)*16 + (vheight)*64)1156#define STBVOX_MAKE_VHEIGHT(v_sw, v_se, v_nw, v_ne) ((v_sw) + (v_se)*4 + (v_nw)*16 + (v_ne)*64)1157#define STBVOX_MAKE_MATROT(block, overlay, color)  ((block) + (overlay)*4 + (color)*64)1158#define STBVOX_MAKE_TEX2_REPLACE(tex2, tex2_replace_face) ((tex2) + ((tex2_replace_face) & 3)*64)1159#define STBVOX_MAKE_TEXLERP(ns2, ew2, ud2, vert)  ((ew2) + (ns2)*4 + (ud2)*16 + (vert)*64)1160#define STBVOX_MAKE_TEXLERP_SIMPLE(baselerp,vert,face)   ((vert)*32 + (face)*4 + (baselerp))1161#define STBVOX_MAKE_TEXLERP1(vert,e2,n2,w2,s2,u4,d2) STBVOX_MAKE_TEXLERP(s2, w2, d2, vert)1162#define STBVOX_MAKE_TEXLERP2(vert,e2,n2,w2,s2,u4,d2) ((u2)*16 + (n2)*4 + (s2))1163#define STBVOX_MAKE_FACE_MASK(e,n,w,s,u,d)  ((e)+(n)*2+(w)*4+(s)*8+(u)*16+(d)*32)1164#define STBVOX_MAKE_SIDE_TEXROT(e,n,w,s) ((e)+(n)*4+(w)*16+(s)*64)1165#define STBVOX_MAKE_COLOR(color,t1,t2) ((color)+(t1)*64+(t2)*128)1166#define STBVOX_MAKE_TEXLERP_VERT3(e,n,w,s,u)   ((e)+(n)*8+(w)*64+(s)*512+(u)*4096)1167#define STBVOX_MAKE_TEXLERP_FACE3(e,n,w,s,u,d) ((e)+(n)*8+(w)*64+(s)*512+(u)*4096+(d)*16384)1168#define STBVOX_MAKE_PACKED_COMPACT(rot, vheight, texlerp, def) ((rot)+4*(vheight)+16*(use)+32*(texlerp))11691170#define STBVOX_MAKE_LIGHTING_EXT(lighting, rot)  (((lighting)&~3)+(rot))1171#define STBVOX_MAKE_LIGHTING(lighting)       (lighting)11721173#ifndef STBVOX_MAX_MESHES1174#define STBVOX_MAX_MESHES      2           // opaque & transparent1175#endif11761177#define STBVOX_MAX_MESH_SLOTS  3           // one vertex & two faces, or two vertex and one face117811791180// don't mess with this directly, it's just here so you can1181// declare stbvox_mesh_maker on the stack or as a global1182struct stbvox_mesh_maker1183{1184   stbvox_input_description input;1185   int cur_x, cur_y, cur_z;       // last unprocessed voxel if it splits into multiple buffers1186   int x0,y0,z0,x1,y1,z1;1187   int x_stride_in_bytes;1188   int y_stride_in_bytes;1189   int config_dirty;1190   int default_mesh;1191   unsigned int tags;11921193   int cube_vertex_offset[6][4]; // this allows access per-vertex data stored block-centered (like texlerp, ambient)1194   int vertex_gather_offset[6][4];11951196   int pos_x,pos_y,pos_z;1197   int full;11981199   // computed from user input1200   char *output_cur   [STBVOX_MAX_MESHES][STBVOX_MAX_MESH_SLOTS];1201   char *output_end   [STBVOX_MAX_MESHES][STBVOX_MAX_MESH_SLOTS];1202   char *output_buffer[STBVOX_MAX_MESHES][STBVOX_MAX_MESH_SLOTS];1203   int   output_len   [STBVOX_MAX_MESHES][STBVOX_MAX_MESH_SLOTS];12041205   // computed from config1206   int   output_size  [STBVOX_MAX_MESHES][STBVOX_MAX_MESH_SLOTS]; // per quad1207   int   output_step  [STBVOX_MAX_MESHES][STBVOX_MAX_MESH_SLOTS]; // per vertex or per face, depending1208   int   num_mesh_slots;12091210   float default_tex_scale[128][2];1211};12121213#endif //  INCLUDE_STB_VOXEL_RENDER_H121412151216#ifdef STB_VOXEL_RENDER_IMPLEMENTATION12171218#include <stdlib.h>1219#include <assert.h>1220#include <string.h> // memset12211222// have to use our own names to avoid the _MSC_VER path having conflicting type names1223#ifndef _MSC_VER1224   #include <stdint.h>1225   typedef uint16_t stbvox_uint16;1226   typedef uint32_t stbvox_uint32;1227#else1228   typedef unsigned short stbvox_uint16;1229   typedef unsigned int   stbvox_uint32;1230#endif12311232#ifdef _MSC_VER1233   #define STBVOX_NOTUSED(v)  (void)(v)1234#else1235   #define STBVOX_NOTUSED(v)  (void)sizeof(v)1236#endif1237123812391240#ifndef STBVOX_CONFIG_MODE1241#error "Must defined STBVOX_CONFIG_MODE to select the mode"1242#endif12431244#if defined(STBVOX_CONFIG_ROTATION_IN_LIGHTING) && defined(STBVOX_CONFIG_VHEIGHT_IN_LIGHTING)1245#error "Can't store both rotation and vheight in lighting"1246#endif124712481249// The following are candidate voxel modes. Only modes 0, 1, and 20, and 21 are1250// currently implemented. Reducing the storage-per-quad further1251// shouldn't improve performance, although obviously it allow you1252// to create larger worlds without streaming.1253//1254//1255//                      -----------  Two textures -----------       -- One texture --     ---- Color only ----1256//            Mode:     0     1     2     3     4     5     6        10    11    12      20    21    22    23    241257// ============================================================================================================1258//  uses Tex Buffer     n     Y     Y     Y     Y     Y     Y         Y     Y     Y       n     Y     Y     Y     Y1259//   bytes per quad    32    20    14    12    10     6     6         8     8     4      32    20    10     6     41260//       non-blocks   all   all   some  some  some slabs stairs     some  some  none    all   all  slabs slabs  none1261//             tex1   256   256   256   256   256   256   256       256   256   256       n     n     n     n     n1262//             tex2   256   256   256   256   256   256   128         n     n     n       n     n     n     n     n1263//           colors    64    64    64    64    64    64    64         8     n     n     2^24  2^24  2^24  2^24  2561264//        vertex ao     Y     Y     Y     Y     Y     n     n         Y     Y     n       Y     Y     Y     n     n1265//   vertex texlerp     Y     Y     Y     n     n     n     n         -     -     -       -     -     -     -     -1266//      x&y extents   127   127   128    64    64   128    64        64   128   128     127   127   128   128   1281267//        z extents   255   255   128    64?   64?   64    64        32    64   128     255   255   128    64   12812681269// not sure why I only wrote down the above "result data" and didn't preserve1270// the vertex formats, but here I've tried to reconstruct the designs...1271//     mode # 3 is wrong, one byte too large, but they may have been an error originally12721273//            Mode:     0     1     2     3     4     5     6        10    11    12      20    21    22    23    241274// =============================================================================================================1275//   bytes per quad    32    20    14    12    10     6     6         8     8     4            20    10     6     41276//1277//    vertex x bits     7     7     0     6     0     0     0         0     0     0             7     0     0     01278//    vertex y bits     7     7     0     0     0     0     0         0     0     0             7     0     0     01279//    vertex z bits     9     9     7     4     2     0     0         2     2     0             9     2     0     01280//   vertex ao bits     6     6     6     6     6     0     0         6     6     0             6     6     0     01281//  vertex txl bits     3     3     3     0     0     0     0         0     0     0            (3)    0     0     01282//1283//   face tex1 bits    (8)    8     8     8     8     8     8         8     8     81284//   face tex2 bits    (8)    8     8     8     8     8     7         -     -     -1285//  face color bits    (8)    8     8     8     8     8     8         3     0     0            24    24    24     81286// face normal bits    (8)    8     8     8     6     4     7         4     4     3             8     3     4     31287//      face x bits                 7     0     6     7     6         6     7     7             0     7     7     71288//      face y bits                 7     6     6     7     6         6     7     7             0     7     7     71289//      face z bits                 2     2     6     6     6         5     6     7             0     7     6     7129012911292#if STBVOX_CONFIG_MODE==0 || STBVOX_CONFIG_MODE==112931294   #define STBVOX_ICONFIG_VERTEX_321295   #define STBVOX_ICONFIG_FACE1_112961297#elif STBVOX_CONFIG_MODE==20 || STBVOX_CONFIG_MODE==2112981299   #define STBVOX_ICONFIG_VERTEX_321300   #define STBVOX_ICONFIG_FACE1_11301   #define STBVOX_ICONFIG_UNTEXTURED13021303#else1304#error "Selected value of STBVOX_CONFIG_MODE is not supported"1305#endif13061307#if STBVOX_CONFIG_MODE==0 || STBVOX_CONFIG_MODE==201308#define STBVOX_ICONFIG_FACE_ATTRIBUTE1309#endif13101311#ifndef STBVOX_CONFIG_HLSL1312// the fallback if all others are exhausted is GLSL1313#define STBVOX_ICONFIG_GLSL1314#endif13151316#ifdef STBVOX_CONFIG_OPENGL_MODELVIEW1317#define STBVOX_ICONFIG_OPENGL_3_1_COMPATIBILITY1318#endif13191320#if defined(STBVOX_ICONFIG_VERTEX_32)1321   typedef stbvox_uint32 stbvox_mesh_vertex;1322   #define stbvox_vertex_encode(x,y,z,ao,texlerp) \1323      ((stbvox_uint32) ((x)+((y)<<7)+((z)<<14)+((ao)<<23)+((texlerp)<<29)))1324#elif defined(STBVOX_ICONFIG_VERTEX_16_1)  // mode=21325   typedef stbvox_uint16 stbvox_mesh_vertex;1326   #define stbvox_vertex_encode(x,y,z,ao,texlerp) \1327      ((stbvox_uint16) ((z)+((ao)<<7)+((texlerp)<<13)1328#elif defined(STBVOX_ICONFIG_VERTEX_16_2)  // mode=31329   typedef stbvox_uint16 stbvox_mesh_vertex;1330   #define stbvox_vertex_encode(x,y,z,ao,texlerp) \1331      ((stbvox_uint16) ((x)+((z)<<6))+((ao)<<10))1332#elif defined(STBVOX_ICONFIG_VERTEX_8)1333   typedef stbvox_uint8 stbvox_mesh_vertex;1334   #define stbvox_vertex_encode(x,y,z,ao,texlerp) \1335      ((stbvox_uint8) ((z)+((ao)<<6))1336#else1337   #error "internal error, no vertex type"1338#endif13391340#ifdef STBVOX_ICONFIG_FACE1_11341   typedef struct1342   {1343      unsigned char tex1,tex2,color,face_info;1344   } stbvox_mesh_face;1345#else1346   #error "internal error, no face type"1347#endif134813491350// 20-byte quad format:1351//1352// per vertex:1353//1354//     x:71355//     y:71356//     z:91357//     ao:61358//     tex_lerp:31359//1360// per face:1361//1362//     tex1:81363//     tex2:81364//     face:81365//     color:8136613671368// Faces:1369//1370// Faces use the bottom 3 bits to choose the texgen1371// mode, and all the bits to choose the normal.1372// Thus the bottom 3 bits have to be:1373//      e, n, w, s, u, d, u, d1374//1375// These use compact names so tables are readable13761377enum1378{1379   STBVF_e,1380   STBVF_n,1381   STBVF_w,1382   STBVF_s,1383   STBVF_u,1384   STBVF_d,1385   STBVF_eu,1386   STBVF_ed,13871388   STBVF_eu_wall,1389   STBVF_nu_wall,1390   STBVF_wu_wall,1391   STBVF_su_wall,1392   STBVF_ne_u,1393   STBVF_ne_d,1394   STBVF_nu,1395   STBVF_nd,13961397   STBVF_ed_wall,1398   STBVF_nd_wall,1399   STBVF_wd_wall,1400   STBVF_sd_wall,1401   STBVF_nw_u,1402   STBVF_nw_d,1403   STBVF_wu,1404   STBVF_wd,14051406   STBVF_ne_u_cross,1407   STBVF_nw_u_cross,1408   STBVF_sw_u_cross,1409   STBVF_se_u_cross,1410   STBVF_sw_u,1411   STBVF_sw_d,1412   STBVF_su,1413   STBVF_sd,14141415   // @TODO we need more than 5 bits to encode the normal to fit the following1416   // so for now we use the right projection but the wrong normal1417   STBVF_se_u = STBVF_su,1418   STBVF_se_d = STBVF_sd,14191420   STBVF_count,1421};14221423/////////////////////////////////////////////////////////////////////////////1424//1425//    tables -- i'd prefer if these were at the end of the file, but: C++1426//14271428static float stbvox_default_texgen[2][32][3] =1429{1430   { {  0, 1,0 }, { 0, 0, 1 }, {  0,-1,0 }, { 0, 0,-1 },1431     { -1, 0,0 }, { 0, 0, 1 }, {  1, 0,0 }, { 0, 0,-1 },1432     {  0,-1,0 }, { 0, 0, 1 }, {  0, 1,0 }, { 0, 0,-1 },1433     {  1, 0,0 }, { 0, 0, 1 }, { -1, 0,0 }, { 0, 0,-1 },14341435     {  1, 0,0 }, { 0, 1, 0 }, { -1, 0,0 }, { 0,-1, 0 },1436     { -1, 0,0 }, { 0,-1, 0 }, {  1, 0,0 }, { 0, 1, 0 },1437     {  1, 0,0 }, { 0, 1, 0 }, { -1, 0,0 }, { 0,-1, 0 },1438     { -1, 0,0 }, { 0,-1, 0 }, {  1, 0,0 }, { 0, 1, 0 },1439   },1440   { { 0, 0,-1 }, {  0, 1,0 }, { 0, 0, 1 }, {  0,-1,0 },1441     { 0, 0,-1 }, { -1, 0,0 }, { 0, 0, 1 }, {  1, 0,0 },1442     { 0, 0,-1 }, {  0,-1,0 }, { 0, 0, 1 }, {  0, 1,0 },1443     { 0, 0,-1 }, {  1, 0,0 }, { 0, 0, 1 }, { -1, 0,0 },14441445     { 0,-1, 0 }, {  1, 0,0 }, { 0, 1, 0 }, { -1, 0,0 },1446     { 0, 1, 0 }, { -1, 0,0 }, { 0,-1, 0 }, {  1, 0,0 },1447     { 0,-1, 0 }, {  1, 0,0 }, { 0, 1, 0 }, { -1, 0,0 },1448     { 0, 1, 0 }, { -1, 0,0 }, { 0,-1, 0 }, {  1, 0,0 },1449   },1450};14511452#define STBVOX_RSQRT2   0.7071067811865f1453#define STBVOX_RSQRT3   0.5773502691896f14541455static float stbvox_default_normals[32][3] =1456{1457   { 1,0,0 },  // east1458   { 0,1,0 },  // north1459   { -1,0,0 }, // west1460   { 0,-1,0 }, // south1461   { 0,0,1 },  // up1462   { 0,0,-1 }, // down1463   {  STBVOX_RSQRT2,0, STBVOX_RSQRT2 }, // east & up1464   {  STBVOX_RSQRT2,0, -STBVOX_RSQRT2 }, // east & down14651466   {  STBVOX_RSQRT2,0, STBVOX_RSQRT2 }, // east & up1467   { 0, STBVOX_RSQRT2, STBVOX_RSQRT2 }, // north & up1468   { -STBVOX_RSQRT2,0, STBVOX_RSQRT2 }, // west & up1469   { 0,-STBVOX_RSQRT2, STBVOX_RSQRT2 }, // south & up1470   {  STBVOX_RSQRT3, STBVOX_RSQRT3, STBVOX_RSQRT3 }, // ne & up1471   {  STBVOX_RSQRT3, STBVOX_RSQRT3,-STBVOX_RSQRT3 }, // ne & down1472   { 0, STBVOX_RSQRT2, STBVOX_RSQRT2 }, // north & up1473   { 0, STBVOX_RSQRT2, -STBVOX_RSQRT2 }, // north & down14741475   {  STBVOX_RSQRT2,0, -STBVOX_RSQRT2 }, // east & down1476   { 0, STBVOX_RSQRT2, -STBVOX_RSQRT2 }, // north & down1477   { -STBVOX_RSQRT2,0, -STBVOX_RSQRT2 }, // west & down1478   { 0,-STBVOX_RSQRT2, -STBVOX_RSQRT2 }, // south & down1479   { -STBVOX_RSQRT3, STBVOX_RSQRT3, STBVOX_RSQRT3 }, // NW & up1480   { -STBVOX_RSQRT3, STBVOX_RSQRT3,-STBVOX_RSQRT3 }, // NW & down1481   { -STBVOX_RSQRT2,0, STBVOX_RSQRT2 }, // west & up1482   { -STBVOX_RSQRT2,0, -STBVOX_RSQRT2 }, // west & down14831484   {  STBVOX_RSQRT3, STBVOX_RSQRT3,STBVOX_RSQRT3 }, // NE & up crossed1485   { -STBVOX_RSQRT3, STBVOX_RSQRT3,STBVOX_RSQRT3 }, // NW & up crossed1486   { -STBVOX_RSQRT3,-STBVOX_RSQRT3,STBVOX_RSQRT3 }, // SW & up crossed1487   {  STBVOX_RSQRT3,-STBVOX_RSQRT3,STBVOX_RSQRT3 }, // SE & up crossed1488   { -STBVOX_RSQRT3,-STBVOX_RSQRT3, STBVOX_RSQRT3 }, // SW & up1489   { -STBVOX_RSQRT3,-STBVOX_RSQRT3,-STBVOX_RSQRT3 }, // SW & up1490   { 0,-STBVOX_RSQRT2, STBVOX_RSQRT2 }, // south & up1491   { 0,-STBVOX_RSQRT2, -STBVOX_RSQRT2 }, // south & down1492};14931494static float stbvox_default_texscale[128][4] =1495{1496   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},1497   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},1498   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},1499   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},1500   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},1501   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},1502   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},1503   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},1504   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},1505   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},1506   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},1507   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},1508   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},1509   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},1510   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},1511   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},1512};15131514static unsigned char stbvox_default_palette_compact[64][3] =1515{1516   { 255,255,255 }, { 238,238,238 }, { 221,221,221 }, { 204,204,204 },1517   { 187,187,187 }, { 170,170,170 }, { 153,153,153 }, { 136,136,136 },1518   { 119,119,119 }, { 102,102,102 }, {  85, 85, 85 }, {  68, 68, 68 },1519   {  51, 51, 51 }, {  34, 34, 34 }, {  17, 17, 17 }, {   0,  0,  0 },1520   { 255,240,240 }, { 255,220,220 }, { 255,160,160 }, { 255, 32, 32 },1521   { 200,120,160 }, { 200, 60,150 }, { 220,100,130 }, { 255,  0,128 },1522   { 240,240,255 }, { 220,220,255 }, { 160,160,255 }, {  32, 32,255 },1523   { 120,160,200 }, {  60,150,200 }, { 100,130,220 }, {   0,128,255 },1524   { 240,255,240 }, { 220,255,220 }, { 160,255,160 }, {  32,255, 32 },1525   { 160,200,120 }, { 150,200, 60 }, { 130,220,100 }, { 128,255,  0 },1526   { 255,255,240 }, { 255,255,220 }, { 220,220,180 }, { 255,255, 32 },1527   { 200,160,120 }, { 200,150, 60 }, { 220,130,100 }, { 255,128,  0 },1528   { 255,240,255 }, { 255,220,255 }, { 220,180,220 }, { 255, 32,255 },1529   { 160,120,200 }, { 150, 60,200 }, { 130,100,220 }, { 128,  0,255 },1530   { 240,255,255 }, { 220,255,255 }, { 180,220,220 }, {  32,255,255 },1531   { 120,200,160 }, {  60,200,150 }, { 100,220,130 }, {   0,255,128 },1532};15331534static float stbvox_default_ambient[4][4] =1535{1536   { 0,0,1      ,0 }, // reversed lighting direction1537   { 0.5,0.5,0.5,0 }, // directional color1538   { 0.5,0.5,0.5,0 }, // constant color1539   { 0.5,0.5,0.5,1.0f/1000.0f/1000.0f }, // fog data for simple_fog1540};15411542static float stbvox_default_palette[64][4];15431544static void stbvox_build_default_palette(void)1545{1546   int i;1547   for (i=0; i < 64; ++i) {1548      stbvox_default_palette[i][0] = stbvox_default_palette_compact[i][0] / 255.0f;1549      stbvox_default_palette[i][1] = stbvox_default_palette_compact[i][1] / 255.0f;1550      stbvox_default_palette[i][2] = stbvox_default_palette_compact[i][2] / 255.0f;1551      stbvox_default_palette[i][3] = 1.0f;1552   }1553}15541555//////////////////////////////////////////////////////////////////////////////1556//1557// Shaders1558//15591560#if defined(STBVOX_ICONFIG_OPENGL_3_1_COMPATIBILITY)1561   #define STBVOX_SHADER_VERSION "#version 150 compatibility\n"1562#elif defined(STBVOX_ICONFIG_OPENGL_3_0)1563   #define STBVOX_SHADER_VERSION "#version 130\n"1564#elif defined(STBVOX_ICONFIG_GLSL)1565   #define STBVOX_SHADER_VERSION "#version 150\n"1566#else1567   #define STBVOX_SHADER_VERSION ""1568#endif15691570static const char *stbvox_vertex_program =1571{1572      STBVOX_SHADER_VERSION15731574   #ifdef STBVOX_ICONFIG_FACE_ATTRIBUTE  // NOT TAG_face_sampled1575      "in uvec4 attr_face;\n"1576   #else1577      "uniform usamplerBuffer facearray;\n"1578   #endif15791580   #ifdef STBVOX_ICONFIG_FACE_ARRAY_21581      "uniform usamplerBuffer facearray2;\n"1582   #endif15831584      // vertex input data1585      "in uint attr_vertex;\n"15861587      // per-buffer data1588      "uniform vec3 transform[3];\n"15891590      // per-frame data1591      "uniform vec4 camera_pos;\n"  // 4th value is used for arbitrary hacking15921593      // to simplify things, we avoid using more than 256 uniform vectors1594      // in fragment shader to avoid possible 1024 component limit, so1595      // we access this table in the fragment shader.1596      "uniform vec3 normal_table[32];\n"15971598      #ifndef STBVOX_CONFIG_OPENGL_MODELVIEW1599         "uniform mat4x4 model_view;\n"1600      #endif16011602      // fragment output data1603      "flat out uvec4  facedata;\n"1604      "     out  vec3  voxelspace_pos;\n"1605      "     out  vec3  vnormal;\n"1606      "     out float  texlerp;\n"1607      "     out float  amb_occ;\n"16081609      // @TODO handle the HLSL way to do this1610      "void main()\n"1611      "{\n"1612      #ifdef STBVOX_ICONFIG_FACE_ATTRIBUTE1613         "   facedata = attr_face;\n"1614      #else1615         "   int faceID = gl_VertexID >> 2;\n"1616         "   facedata   = texelFetch(facearray, faceID);\n"1617      #endif16181619      // extract data for vertex1620      "   vec3 offset;\n"1621      "   offset.x = float( (attr_vertex       ) & 127u );\n"             // a[0..6]1622      "   offset.y = float( (attr_vertex >>  7u) & 127u );\n"             // a[7..13]1623      "   offset.z = float( (attr_vertex >> 14u) & 511u );\n"             // a[14..22]1624      "   amb_occ  = float( (attr_vertex >> 23u) &  63u ) / 63.0;\n"      // a[23..28]1625      "   texlerp  = float( (attr_vertex >> 29u)        ) /  7.0;\n"      // a[29..31]16261627      "   vnormal = normal_table[(facedata.w>>2u) & 31u];\n"1628      "   voxelspace_pos = offset * transform[0];\n"  // mesh-to-object scale1629      "   vec3 position  = voxelspace_pos + transform[1];\n"  // mesh-to-object translate16301631      #ifdef STBVOX_DEBUG_TEST_NORMALS1632         "   if ((facedata.w & 28u) == 16u || (facedata.w & 28u) == 24u)\n"1633         "      position += vnormal.xyz * camera_pos.w;\n"1634      #endif16351636      #ifndef STBVOX_CONFIG_OPENGL_MODELVIEW1637         "   gl_Position = model_view * vec4(position,1.0);\n"1638      #else1639         "   gl_Position = gl_ModelViewProjectionMatrix * vec4(position,1.0);\n"1640      #endif16411642      "}\n"1643};164416451646static const char *stbvox_fragment_program =1647{1648      STBVOX_SHADER_VERSION16491650      // rlerp is lerp but with t on the left, like god intended1651      #if defined(STBVOX_ICONFIG_GLSL)1652         "#define rlerp(t,x,y) mix(x,y,t)\n"1653      #elif defined(STBVOX_CONFIG_HLSL)1654         "#define rlerp(t,x,y) lerp(x,y,t)\n"1655      #else1656         #error "need definition of rlerp()"1657      #endif165816591660      // vertex-shader output data1661      "flat in uvec4  facedata;\n"1662      "     in  vec3  voxelspace_pos;\n"1663      "     in  vec3  vnormal;\n"1664      "     in float  texlerp;\n"1665      "     in float  amb_occ;\n"16661667      // per-buffer data1668      "uniform vec3 transform[3];\n"16691670      // per-frame data1671      "uniform vec4 camera_pos;\n"  // 4th value is used for arbitrary hacking16721673      // probably constant data1674      "uniform vec4 ambient[4];\n"16751676      #ifndef STBVOX_ICONFIG_UNTEXTURED1677         // generally constant data1678         "uniform sampler2DArray tex_array[2];\n"16791680         #ifdef STBVOX_CONFIG_PREFER_TEXBUFFER1681            "uniform samplerBuffer color_table;\n"1682            "uniform samplerBuffer texscale;\n"1683            "uniform samplerBuffer texgen;\n"1684         #else1685            "uniform vec4 color_table[64];\n"1686            "uniform vec4 texscale[64];\n" // instead of 128, to avoid running out of uniforms1687            "uniform vec3 texgen[64];\n"1688         #endif1689      #endif16901691      "out vec4  outcolor;\n"16921693      #if defined(STBVOX_CONFIG_LIGHTING) || defined(STBVOX_CONFIG_LIGHTING_SIMPLE)1694      "vec3 compute_lighting(vec3 pos, vec3 norm, vec3 albedo, vec3 ambient);\n"1695      #endif1696      #if defined(STBVOX_CONFIG_FOG) || defined(STBVOX_CONFIG_FOG_SMOOTHSTEP)1697      "vec3 compute_fog(vec3 color, vec3 relative_pos, float fragment_alpha);\n"1698      #endif16991700      "void main()\n"1701      "{\n"1702      "   vec3 albedo;\n"1703      "   float fragment_alpha;\n"17041705      #ifndef STBVOX_ICONFIG_UNTEXTURED1706         // unpack the values1707         "   uint tex1_id = facedata.x;\n"1708         "   uint tex2_id = facedata.y;\n"1709         "   uint texprojid = facedata.w & 31u;\n"1710         "   uint color_id  = facedata.z;\n"17111712         #ifndef STBVOX_CONFIG_PREFER_TEXBUFFER1713            // load from uniforms / texture buffers1714            "   vec3 texgen_s = texgen[texprojid];\n"1715            "   vec3 texgen_t = texgen[texprojid+32u];\n"1716            "   float tex1_scale = texscale[tex1_id & 63u].x;\n"1717            "   vec4 color = color_table[color_id & 63u];\n"1718            #ifndef STBVOX_CONFIG_DISABLE_TEX21719            "   vec4 tex2_props = texscale[tex2_id & 63u];\n"1720            #endif1721         #else1722            "   vec3 texgen_s = texelFetch(texgen, int(texprojid)).xyz;\n"1723            "   vec3 texgen_t = texelFetch(texgen, int(texprojid+32u)).xyz;\n"1724            "   float tex1_scale = texelFetch(texscale, int(tex1_id & 127u)).x;\n"1725            "   vec4 color = texelFetch(color_table, int(color_id & 63u));\n"1726            #ifndef STBVOX_CONFIG_DISABLE_TEX21727            "   vec4 tex2_props = texelFetch(texscale, int(tex1_id & 127u));\n"1728            #endif1729         #endif17301731         #ifndef STBVOX_CONFIG_DISABLE_TEX21732         "   float tex2_scale = tex2_props.y;\n"1733         "   bool texblend_mode = tex2_props.z != 0.0;\n"1734         #endif1735         "   vec2 texcoord;\n"1736         "   vec3 texturespace_pos = voxelspace_pos + transform[2].xyz;\n"1737         "   texcoord.s = dot(texturespace_pos, texgen_s);\n"1738         "   texcoord.t = dot(texturespace_pos, texgen_t);\n"17391740         "   vec2  texcoord_1 = tex1_scale * texcoord;\n"1741         #ifndef STBVOX_CONFIG_DISABLE_TEX21742         "   vec2  texcoord_2 = tex2_scale * texcoord;\n"1743         #endif17441745         #ifdef STBVOX_CONFIG_TEX1_EDGE_CLAMP1746         "   texcoord_1 = texcoord_1 - floor(texcoord_1);\n"1747         "   vec4 tex1 = textureGrad(tex_array[0], vec3(texcoord_1, float(tex1_id)), dFdx(tex1_scale*texcoord), dFdy(tex1_scale*texcoord));\n"1748         #else1749         "   vec4 tex1 = texture(tex_array[0], vec3(texcoord_1, float(tex1_id)));\n"1750         #endif17511752         #ifndef STBVOX_CONFIG_DISABLE_TEX21753         #ifdef STBVOX_CONFIG_TEX2_EDGE_CLAMP1754         "   texcoord_2 = texcoord_2 - floor(texcoord_2);\n"1755         "   vec4 tex2 = textureGrad(tex_array[0], vec3(texcoord_2, float(tex2_id)), dFdx(tex2_scale*texcoord), dFdy(tex2_scale*texcoord));\n"1756         #else1757         "   vec4 tex2 = texture(tex_array[1], vec3(texcoord_2, float(tex2_id)));\n"1758         #endif1759         #endif17601761         "   bool emissive = (color.a > 1.0);\n"1762         "   color.a = min(color.a, 1.0);\n"17631764         // recolor textures1765         "   if ((color_id &  64u) != 0u) tex1.rgba *= color.rgba;\n"1766         "   fragment_alpha = tex1.a;\n"1767         #ifndef STBVOX_CONFIG_DISABLE_TEX21768            "   if ((color_id & 128u) != 0u) tex2.rgba *= color.rgba;\n"17691770            #ifdef STBVOX_CONFIG_PREMULTIPLIED_ALPHA1771            "   tex2.rgba *= texlerp;\n"1772            #else1773            "   tex2.a *= texlerp;\n"1774            #endif17751776            "   if (texblend_mode)\n"1777            "      albedo = tex1.xyz * rlerp(tex2.a, vec3(1.0,1.0,1.0), 2.0*tex2.xyz);\n"1778            "   else {\n"1779            #ifdef STBVOX_CONFIG_PREMULTIPLIED_ALPHA1780            "      albedo = (1.0-tex2.a)*tex1.xyz + tex2.xyz;\n"1781            #else1782            "      albedo = rlerp(tex2.a, tex1.xyz, tex2.xyz);\n"1783            #endif1784            "      fragment_alpha = tex1.a*(1-tex2.a)+tex2.a;\n"1785            "   }\n"1786         #else1787            "      albedo = tex1.xyz;\n"1788         #endif17891790      #else // UNTEXTURED1791         "   vec4 color;"1792         "   color.xyz = vec3(facedata.xyz) / 255.0;\n"1793         "   bool emissive = false;\n"1794         "   albedo = color.xyz;\n"1795         "   fragment_alpha = 1.0;\n"1796      #endif17971798      #ifdef STBVOX_ICONFIG_VARYING_VERTEX_NORMALS1799         // currently, there are no modes that trigger this path; idea is that there1800         // could be a couple of bits per vertex to perturb the normal to e.g. get curved look1801         "   vec3 normal = normalize(vnormal);\n"1802      #else1803         "   vec3 normal = vnormal;\n"1804      #endif18051806      "   vec3 ambient_color = dot(normal, ambient[0].xyz) * ambient[1].xyz + ambient[2].xyz;\n"18071808      "   ambient_color = clamp(ambient_color, 0.0, 1.0);"1809      "   ambient_color *= amb_occ;\n"18101811      "   vec3 lit_color;\n"1812      "   if (!emissive)\n"1813      #if defined(STBVOX_ICONFIG_LIGHTING) || defined(STBVOX_CONFIG_LIGHTING_SIMPLE)1814         "      lit_color = compute_lighting(voxelspace_pos + transform[1], normal, albedo, ambient_color);\n"1815      #else1816         "      lit_color = albedo * ambient_color ;\n"1817      #endif1818      "   else\n"1819      "      lit_color = albedo;\n"18201821      #if defined(STBVOX_ICONFIG_FOG) || defined(STBVOX_CONFIG_FOG_SMOOTHSTEP)1822         "   vec3 dist = voxelspace_pos + (transform[1] - camera_pos.xyz);\n"1823         "   lit_color = compute_fog(lit_color, dist, fragment_alpha);\n"1824      #endif18251826      #ifdef STBVOX_CONFIG_UNPREMULTIPLY1827      "   vec4 final_color = vec4(lit_color/fragment_alpha, fragment_alpha);\n"1828      #else1829      "   vec4 final_color = vec4(lit_color, fragment_alpha);\n"1830      #endif1831      "   outcolor = final_color;\n"1832      "}\n"18331834   #ifdef STBVOX_CONFIG_LIGHTING_SIMPLE1835      "\n"1836      "uniform vec3 light_source[2];\n"1837      "vec3 compute_lighting(vec3 pos, vec3 norm, vec3 albedo, vec3 ambient)\n"1838      "{\n"1839      "   vec3 light_dir = light_source[0] - pos;\n"1840      "   float lambert = dot(light_dir, norm) / dot(light_dir, light_dir);\n"1841      "   vec3 diffuse = clamp(light_source[1] * clamp(lambert, 0.0, 1.0), 0.0, 1.0);\n"1842      "   return (diffuse + ambient) * albedo;\n"1843      "}\n"1844   #endif18451846   #ifdef STBVOX_CONFIG_FOG_SMOOTHSTEP1847      "\n"1848      "vec3 compute_fog(vec3 color, vec3 relative_pos, float fragment_alpha)\n"1849      "{\n"1850      "   float f = dot(relative_pos,relative_pos)*ambient[3].w;\n"1851      //"   f = rlerp(f, -2,1);\n"1852      "   f = clamp(f, 0.0, 1.0);\n"1853      "   f = 3.0*f*f - 2.0*f*f*f;\n" // smoothstep1854      //"   f = f*f;\n"  // fade in more smoothly1855      #ifdef STBVOX_CONFIG_PREMULTIPLIED_ALPHA1856      "   return rlerp(f, color.xyz, ambient[3].xyz*fragment_alpha);\n"1857      #else1858      "   return rlerp(f, color.xyz, ambient[3].xyz);\n"1859      #endif1860      "}\n"1861   #endif1862};186318641865// still requires full alpha lookups, including tex2 if texblend is enabled1866static const char *stbvox_fragment_program_alpha_only =1867{1868   STBVOX_SHADER_VERSION18691870   // vertex-shader output data1871   "flat in uvec4  facedata;\n"1872   "     in  vec3  voxelspace_pos;\n"1873   "     in float  texlerp;\n"18741875   // per-buffer data1876   "uniform vec3 transform[3];\n"18771878   #ifndef STBVOX_ICONFIG_UNTEXTURED1879      // generally constant data1880      "uniform sampler2DArray tex_array[2];\n"18811882      #ifdef STBVOX_CONFIG_PREFER_TEXBUFFER1883         "uniform samplerBuffer texscale;\n"1884         "uniform samplerBuffer texgen;\n"1885      #else1886         "uniform vec4 texscale[64];\n" // instead of 128, to avoid running out of uniforms1887         "uniform vec3 texgen[64];\n"1888      #endif1889   #endif18901891   "out vec4  outcolor;\n"18921893   "void main()\n"1894   "{\n"1895   "   vec3 albedo;\n"1896   "   float fragment_alpha;\n"18971898   #ifndef STBVOX_ICONFIG_UNTEXTURED1899      // unpack the values1900      "   uint tex1_id = facedata.x;\n"1901      "   uint tex2_id = facedata.y;\n"1902      "   uint texprojid = facedata.w & 31u;\n"1903      "   uint color_id  = facedata.z;\n"19041905      #ifndef STBVOX_CONFIG_PREFER_TEXBUFFER1906         // load from uniforms / texture buffers1907         "   vec3 texgen_s = texgen[texprojid];\n"1908         "   vec3 texgen_t = texgen[texprojid+32u];\n"1909         "   float tex1_scale = texscale[tex1_id & 63u].x;\n"1910         "   vec4 color = color_table[color_id & 63u];\n"1911         "   vec4 tex2_props = texscale[tex2_id & 63u];\n"1912      #else1913         "   vec3 texgen_s = texelFetch(texgen, int(texprojid)).xyz;\n"1914         "   vec3 texgen_t = texelFetch(texgen, int(texprojid+32u)).xyz;\n"1915         "   float tex1_scale = texelFetch(texscale, int(tex1_id & 127u)).x;\n"1916         "   vec4 color = texelFetch(color_table, int(color_id & 63u));\n"1917         "   vec4 tex2_props = texelFetch(texscale, int(tex2_id & 127u));\n"1918      #endif19191920      #ifndef STBVOX_CONFIG_DISABLE_TEX21921      "   float tex2_scale = tex2_props.y;\n"1922      "   bool texblend_mode = tex2_props.z &((facedata.w & 128u) != 0u);\n"1923      #endif19241925      "   color.a = min(color.a, 1.0);\n"19261927      "   vec2 texcoord;\n"1928      "   vec3 texturespace_pos = voxelspace_pos + transform[2].xyz;\n"1929      "   texcoord.s = dot(texturespace_pos, texgen_s);\n"1930      "   texcoord.t = dot(texturespace_pos, texgen_t);\n"19311932      "   vec2  texcoord_1 = tex1_scale * texcoord;\n"1933      "   vec2  texcoord_2 = tex2_scale * texcoord;\n"19341935      #ifdef STBVOX_CONFIG_TEX1_EDGE_CLAMP1936      "   texcoord_1 = texcoord_1 - floor(texcoord_1);\n"1937      "   vec4 tex1 = textureGrad(tex_array[0], vec3(texcoord_1, float(tex1_id)), dFdx(tex1_scale*texcoord), dFdy(tex1_scale*texcoord));\n"1938      #else1939      "   vec4 tex1 = texture(tex_array[0], vec3(texcoord_1, float(tex1_id)));\n"1940      #endif19411942      "   if ((color_id &  64u) != 0u) tex1.a *= color.a;\n"1943      "   fragment_alpha = tex1.a;\n"19441945      #ifndef STBVOX_CONFIG_DISABLE_TEX21946      "   if (!texblend_mode) {\n"1947         #ifdef STBVOX_CONFIG_TEX2_EDGE_CLAMP1948         "      texcoord_2 = texcoord_2 - floor(texcoord_2);\n"1949         "      vec4 tex2 = textureGrad(tex_array[0], vec3(texcoord_2, float(tex2_id)), dFdx(tex2_scale*texcoord), dFdy(tex2_scale*texcoord));\n"1950         #else1951         "      vec4 tex2 = texture(tex_array[1], vec3(texcoord_2, float(tex2_id)));\n"1952         #endif19531954         "      tex2.a *= texlerp;\n"1955         "      if ((color_id & 128u) != 0u) tex2.rgba *= color.a;\n"1956         "      fragment_alpha = tex1.a*(1-tex2.a)+tex2.a;\n"1957         "}\n"1958      "\n"1959      #endif19601961   #else // UNTEXTURED1962      "   fragment_alpha = 1.0;\n"1963   #endif19641965   "   outcolor = vec4(0.0, 0.0, 0.0, fragment_alpha);\n"1966   "}\n"1967};196819691970STBVXDEC char *stbvox_get_vertex_shader(void)1971{1972   return (char *) stbvox_vertex_program;1973}19741975STBVXDEC char *stbvox_get_fragment_shader(void)1976{1977   return (char *) stbvox_fragment_program;1978}19791980STBVXDEC char *stbvox_get_fragment_shader_alpha_only(void)1981{1982   return (char *) stbvox_fragment_program_alpha_only;1983}19841985static float stbvox_dummy_transform[3][3];19861987#ifdef STBVOX_CONFIG_PREFER_TEXBUFFER1988#define STBVOX_TEXBUF 11989#else1990#define STBVOX_TEXBUF 01991#endif19921993static stbvox_uniform_info stbvox_uniforms[] =1994{1995   { STBVOX_UNIFORM_TYPE_sampler  ,  4,   1, (char*) "facearray"    , 0                           },1996   { STBVOX_UNIFORM_TYPE_vec3     , 12,   3, (char*) "transform"    , stbvox_dummy_transform[0]   },1997   { STBVOX_UNIFORM_TYPE_sampler  ,  4,   2, (char*) "tex_array"    , 0                           },1998   { STBVOX_UNIFORM_TYPE_vec4     , 16, 128, (char*) "texscale"     , stbvox_default_texscale[0] , STBVOX_TEXBUF },1999   { STBVOX_UNIFORM_TYPE_vec4     , 16,  64, (char*) "color_table"  , stbvox_default_palette[0]  , STBVOX_TEXBUF },2000   { STBVOX_UNIFORM_TYPE_vec3     , 12,  32, (char*) "normal_table" , stbvox_default_normals[0]   },

The first 2,000 of 3,807 lines.