• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
  • entries
    44
  • comments
    44
  • views
    58213

About this blog

About the game Caveman

Entries in this blog

Norman Barrows

The new PC has arrived (i7-6700K, GTX1080), and I'm starting on the final graphics for the game.

Better grass plants were one of the first things. The placeholder graphics were ultra-low-poly, just 3 or 4 quads. I could only draw them every 5 feet or so, any closer together was too many instances. They were scaled very wide and flat to cover the gaps. it looked ok en masse, but individual plants weren't that great.

So after watching Youtube tutorials, i made some better plant models. I was testing them out, but noticed a frame rate hit. 2500 instances was ok, but a bit of a performance hit. 10,000 was a big performance hit.

So i did some experimenting. i would track the number actually drawn, and the number of polys in the mesh being used, and the FPS, and the scale. at first it seemed the number of draw calls was having the biggest effect, followed by the number of tris in the mesh used, with mesh scale (big tri rasteriization) practically no effect (scale up the grass in your game to 20-30 feet tall - it looks wild!). but on closer inspection, i was drawing about the same number of quads with 10000 one quad meshes vs 2500 3 quad meshes, but 10000 was half as fast. turned out it was the figuring out of which of the 10,000 to draw that was the performance hit.

So then it was time for some test code. The optimal way to do it would be to pre-calc the lsit of plants to draw, along with their world mats. set the texture, material, mesh, clamp, cull, tex scale, etc just once, then for each plant in the list, set world mat, then call D.I.P.

I tried it with 2500 plants. a 100x100 foot area with one plant every 2 feet. worked like a charm. no change in framerate. still 60 FPS. then i tried 10000 plants (200x200 foot area, one plant every 2 feet). worked like a charm. no change in framerate.

screenshots:

gallery_197293_593_962883.jpg

the total meshes drawn is in addition to the 10000 grass plant meshes. those are the ground, tress, berry bushes, the huts, the teepee, the fire, people, etc.

gallery_197293_593_871115.jpg

this shows a closeup of the grass. still needs work, but its getting better.

and here's the test code: /* optimal: pre-calc all world mats set alphatest, cull, clamp, material, and tex scaling once. set each tex once. for each tex, set each mesh once. for each mesh, set world mat, call DIP */ #define max_grass_list 10000D3DXMATRIX grass_list[max_grass_list]; int num_grass_list;void init_savanna_grass_list(){ int x1,z1; float x,y,z,sx,sy,sz,ry,jitter,scale; ZeroMemory(grass_list,sizeof(D3DXMATRIX)*max_grass_list); num_grass_list=0; for (x1=0; x1<100; x1++) { for (z1=0; z1<100; z1++) { x=26200.0f+(float)x1*2.0f; z=13100.0f+(float)z1*2.0f; jitter=grass_offset((int)x,(int)z); jitter/=2.0f; x+=jitter; z+=jitter; y=heightmap(cm[cm0].mx,cm[cm0].mz,x,z); scale=(float)grass_scale((int)x,(int)z); sx=scale*0.05f; sy=scale*0.03f; sz=scale*0.05f; ry=grass_rotation((int)x,(int)z); Mstart(); Mscale(sx,sy,sz);// MrotateRADS(0,rx); MrotateRADS(1,ry);// MrotateRADS(2,rz); Mmove(x,y,z); grass_list[num_grass_list]=Mmat; num_grass_list++; } } }void test_draw_savanna_grass(){int a;HRESULT result;trace[0]=0;Zsettex(454); // 6=oceanZsetmesh(4);Zalphatest(1);Zcull(1);Zclamp(1); Zsetmaterial(7);Ztexture_scaling(0);for (a=0; aSetTransform(D3DTS_WORLD,&grass_list[a]); result=Zd3d_device_ptr->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,0,0,Znum_verts,0,Znum_primitives); trace[0]++; if (result != D3D_OK) { Zmsg2("test draw savanna grass error"); exit(1); } }}
so it would seem that lots of drawcalls is not necessarily a bottleneck. perhaps even less of a bottleneck than high poly meshes. i tested plant meshes with as few as two triangles, and as many as 64 triangles. as is often the case, its visible surface determination that's the bottleneck here. In such cases, optimization in the form of DOD seems to be the best approach.


EDIT:

I turned off the test code to draw savanna grass, and turned generate_savanna_grass back on. I kicked it up from one plant every 3 feet to 1 plant every 2 feet (from 10,000 to 22,500 plants per 300x300 foot chunk). This required an increase in the number of max_meshes in a terrain chunk (from 20,000 meshes to 25,000 meshes). but with a chunk cache of 90 chunks, that ran out of memory. So i knocked the cache size back down to its original 30 chunk size.

i'm now making 36,000+ draw calls per frame at 60 FPS - clip range in this shot is set to 400 feet for everything:

gallery_197293_593_1236413.jpg

Since the data structure for visible surface determination is the key to all this, i'll provide a few details....

the entire graphics engine is build around a struct called a Zdrawinfo struct. it contains all the basic parameters for a draw call, such as mesh ID, texture ID, material ID, and flags like cull, clamp, alphatest, etc.

When a terrain chunk is generated, data from the world map and plant maps determine the terrain type and placement of trees etc. A terrain chunk is a list of Zdrawinfo structs - all the meshes in the chunk. it also has an index, which lists the structs in texture, mesh order. When a mesh is added to the list, an in-order insertion is done to the index. so the chunk contains the list of Zdrawinfo structs, and an index that consists of a list of textures, and for each texture, a list of meshes, and for each mesh, a list of instances in the Zdrawinfo list that use that texture and mesh combo. The index is implemented using ints for storage, and stores texture IDs, mesh IDs, and Zdrawinfo list indices . When rendering, the index is used to draw the meshes in texture, mesh order - to minimize state changes. The graphics engine includes state managers for all states such as cull clamp, alpha test, etc. - so so any redundant changes occurring there while rendering the instances of a texture.mesh combo will be automatically filtered out. Chunks are generated on-demand in the foreground if necessary, as well as being generated in the background using a multi-pass look ahead system to generate chunks around the player before they move into visible range. Generating 22,500 plants vs 10,000 in a single background pass is slightly noticeable. I'll probably need to split that up into two passes. Depending on the type of terrain in a chunk, a chunk can require up to 6 or 8 passes to generate in the background. background chunk generation runs at 15Hz. The game now features a user defined variable frame rate limiter that scales update to the desired framerate. Vsync is still on to avoid tearing, but desired FPS values of 1 through 1000.are supported by the code - if you have the hardware to do it.

NOTE: Apologies for the somewhat dark images. these screenshots were taken at 6:30 AM game time under natural lighting conditions.

Norman Barrows

status report 6-15-2016

the game is really coming along. its now complete, stable, and appealing enough that i've started playing it just for fun, instead of playing store bought games i own. "resource tracking on a per resource basis" and "lack of variety in diet affecting mood" have really made gathering and preparing food more realistic, challenging, and interesting. the addition of large and small flint points and pitch has made crafting much more realistic. it amazing how small rule changes in the mechanics of a game can result in big changes in the dynamics of a game. those two small changes have raised gameplay immersion levels by amazing amounts.

highlights of new features:
* about 20 types of quest generators completed so far
* A* (A-star) path finding
* wood palisaides
* villages
* cave painings
* numerous new actions and objects

big stuff left to do:
* quest generators
* final graphics

new since the last status report on 3-17-2016:
* game tracks last 10 types of food eaten. eating the same thing too often reduces mood.
* followers and pets now moveto owner at rng 50 and stop at rng 10.
* TAMED no longer migrate as part of graze behavior
* added msg if your pet gets killed
* all damage in the game now uses hit loction. old damage variables turned off.
* crippling affects animal and NPC movement rates and attack capabilities.
* give some indication of effect upon eating a spirit plant.
* changed popup & fullscreen menus and messages to dark stone background for greater contrast with white text.
* fixed: selected_pet wasnt hooked up.
* make BMs move out of your way when you push against them. when player collides w/ bm doing nothing, they go into collision recovery.
* fixed: sleep in bedding in hut, then get stuck in walls when wake up. sleep in bedding snaps them to bedding center. bedding center is in walls. select picks spot 3-4 feet in front of BM, inside hut. beding is made 5 feet infront of BM, and thus inside the hut walls. simply create bedding at BM loc, then its guaranteed to not be inside the wall! : )
* pets should reduce chance of being suprised - should raise alarm when encounters happen. pet within 100 cuts BM chance of being suprised in half.
* option to switch to bm if they are attacked while doing an action
* companions, warriors, and pets move out of your way when you push against them.
* make b2_avian_eatkill use meat resources, not general resources.
* defend berrybush, fruit tree and waterhole quests now fail if player flees.
* fixed: rockshelter collisions not working. terrain_in_way and terrain_in_way2 now use rockshelter_in_way instead of collision map. a rockshelter is not a BBox radius type obstacle. generic_move2 and b2_bm_move didnt do collision checks when BM was inside rock shelter. so BM sometimes got stuck in collision against interior walls.
* fixed: silvatherium attacks CHR cavemen at rockshelter, and they just stand around. friendly AI was just targeting HOSTILE, not WILD.
* new_set_tgt must consider all potential threats when selecting targets, or fight or flght won't work. so friendly AI must tgt WILD and hostile for
example.
+ wild should target: all but their own kind.
+ goodguys should target: hostile and wild
+ hostiles should tgt all but hostiles.
+ nobody targets captured or subdued
WARROIR, COMPANION, and TAMED now use set_friendly_tgt (all wilds/hostiles) set_wild_tgt and set_hostile_tgt are already correct. set_friendly_tgt was fixed yesterday.
* fixed: forgot to add "staunch wounds" to the "other actions" menu.
* fixed: dropall and a number of similar routines (give_all, storeall, etc) didnt check for active object. all were code used by routines that call
shift_select. checked all calls to shift_select, to make sure all such routines were fixed. this was the cause of nuts appearing in storage pits!
* defend quests: takes too long for badguys to show up. i'm defending a rockshelter. gotten a dozen animals encounters (its a busy place!), but no badguys. been there almost a day. increased raid chance from 1 in 100K per sec to 1 in 10K per sec. avg of 2.77 hrs, vs 27.777 hrs between encounters.
* fixed: boost stats doesnt un-cripple limbs
* cut encounter ranges for dense terrain types (woods, grass, jungle, rocks)
* volcano collision rad is off - increased to 55. volcanos can span more than 1 collision map. so portion in adjacent map doesnt get set to impassable. will need different collsion check for volcanos. removed volcanos from collision maps. now uses true 2d rad of 70 ft.
* not many volcanoes in the world? increased chance 10x
* fixed: quest_animals_removed doesnt work with multiple simultaneous defloc encounters.
+ add is_quest_animal, quest_BM, and questnum to animalrec.
+ set is_quest_animal etc when spawn quest animals.
+ add animals_removed to questrec.
+ make remove_animals set cm[quest_BM].quest[questnum].animals_removed if it removes a quest animal.
* new: need non-defloc aggressive quest AI. if quest animal and not defloc, runs new quest AI.
new quest gens:
defend rock shelter
defend hut
defend berry bush
defend fruit tree
defend waterhole
moveto
transport
get special item
volcano quest
* attack cave rockshelter and hut quests done
* new fuction: dist3. bbdist in ft. works up to 75K map sq range! (375,000 miles!)
* fixed: crh encounters now spawn outside the crh
* replace quest_animal_alive (any defloc alive) w/ quest_animal_alive2 (any quest animal for cm1 quest q alive)
* replace quest_animal_removed with cm[a].quest.animals_removed
* done: all quest gens: must trap out player simply fleeing and quest animals deactivating.
* checked volcano quest. double spawn is fixed.
* kill animals for reward - places animals at a map sq too far from questor, should be 1-2 sq radius. same for kill cavemen for reward. made a version of randommapsquare that takes a radius.
* MOVETO_QUEST (find treasure) need to change view_quest message when quest begins. general loc is now known. no longer random chance to find treasure, now must look for it.
* refactor: getter and setter functions for animal, caveman, and worldobj locations. make them call generic location getter and setter fucntions.
* success, fail, and encounter wavs for quest messages.
* fixed: friendlies talking to you: if they ask you to talk and you say yes, and you do a talk action, they greet you again after the talk action. didn't set flag to "npc done talking to player" when called the talk action. so after the talk action, it went back to NPC talks to player again.
* increase clip rad of gt moa
* fixed: cant eat w/ 1 crippled arm. EAT was not set to 1 hand action. made a couple other actions 1 hand (like staunch wounds).
* crh hostiles get stuck in / spawn in rocks. uses something_in_way_of_animal for placement. 5 calls to terrain_in_way with +1 on rad - uses collision maps for rocks. uses terrain_in_way2 for movement. one call. uses collision maps for rocks. the +1 rad fix might take care of it. have to wait and see.
* make sure new items like teepees and bedrolls are on treasure tables.
* grunt sfx for npc talk to player dialog messages.
* success and fail wavs for talk to caveman menu
* to do an action, anvil stones can now be nearby or in your inventory.
* only one BM at a time can use a dropped anvil stone to do an action.
* picking up an anvil stone in use stops the user's action.
* tried lessons and advisor
* improved character creation
* improved tutorial
* set bleeding, crippled, etc to false when bring them back to life.
* anvilstone nearby fixed
* butcher time and butcher quality fixed.
* improved getstring
* improved fullscreen menu
* new: stone buttons
* make sure all calls to getstring say "Enter ..."
* add success and fail wavs to run_tutor
* checked: resource depletion by other bands works with the new resource levels by type
* fixed: BM_bestwpn and npc_bestwpn now take crippling vs 1 and 2 handed wpns into account.
* fixed: if missile tries to hit animal, animal sets all nearby friendly animals to "taking fire". even if animal is killed in a single shot, the rest have been alerted.
* fixed: terrain_in_way and terrain_in_way2 sometimes returned CM terrian type, not 1. made someting_in_way_of_animal not work. thats why animals were spawning in rocks.
* put trace on pet wolf AI
* added collsion map check w/ radius to something in way of animals. rocks are still an issue.
* fixed: run_pack_ai didnt check if animal was wild. only wild animals run pack ai. bug made tamed run pack ai sometimes.
* collsion avoidance doesn't look as far ahead, doesn't move as far.
* collision recovery ends sooner
* bandmembers, companions, warriors, and tamed now follow you in and out of caves and caverns, either as owner, or via follow orders.
* fixed: friendly leaders collision avoid cm0 while approaching cm0 to greet.
* fixed: 3pv cam vs NPC huts. adjusted check for crh huts to match that for player huts. added check for crh huts to 1pv vs 3pv code. wrote new routine to check abandoned huts. made it match the code for player huts. added that to 1pv vs 3pv code.
* fixed: 3pv: draw player in hut if doing action. if they are doing an action, it does not check for "don't draw in hut".
* fixed: 1pv skin tex not set when follower joins band
* fixed: 1pv skin tex not set for playtest game
* fixed: reduce radius for fire light and sound.
* fixed: no grass area around tarpit is too big? tarpit too small? its that darn 10 rez on the ground mesh. cant model small curves well. make tarpits bigger. increased rad of tarpit from 15 to 30.
* fix: lakes should be bigger. be sure to resize both graphics AND collision checks! increased rad from 30 to 100.
* implemented A*. still ned to test it, then hook it up to the game.
* spiced veggies: findtime and findchance were not set. was using defaults (1 hour and 1% chance of success). removed spiced veggies from the init lookup functions and into the regular init code.
* learn hafting: now requires flint knife, not cutting tool as part.
* change stoneworking to knapping. require flint, knapping tool, and one hand hammer to learn.
* changed time to make wood arrow from 8 hrs to 30 min.
* add large & small flint point objects. large to make knifes and spears, small to make everything else. 300 stoneworking to make small, 500 to make large. need small to learn hafting. draw lg point as flint knife w/o handle. draw small point as 1/3 size lg point.
* make cutting tool no longer requires knapping skill. make cutting tool now increases knapping skill.
* got 2d map A* working. long setup time. high ram requirements. fast.
* got traditional 2 list A* working. zero setup time. low ram requirements. fast. not fully optimized yet.
* fixed AI vs campfires. flee from campfire has its own vars now. wild animals don't target entities near fires.
* added fight or flight to predator respond to missile fire.
* collision map system now supports collision maps at arbitrary scales. no public API change required! just get_CM_index API used by A*.
* got A* fully working in the game.
* collision checks use high rez collision maps once again.
* added +0.5 x and z offsets for collsion map checks for "pixel perfect" accuracy (rasterization rules).
* "make small flint point" action now repeats as long as you have parts.
* social is zero, but not nuking mood. changed mood reduction from 23 in 10000 chance of 1 every 15 minutes to 1 every 15 minutes.
* make cordage: says no anvil stone on or nearby, when there is. there are 2 stones, one already in use. but use of second stone was stopped by combat. it still may be flagged as in use. added stop_usng_anvilstone if new action==DONOTHING to setaction.
* removed from game: (not realistic)
stone arrow
stone spear
stone javelin
stone atlatl dart
stone fish spear
throwhatchet.
flint throw rock
* add 1 wood required for flint knife. knife gets wood handle. need model.
already added leather handle requierd. added cordgae, hafting, etc. made new model.
draw 1pv wih doen't use new model yet.
* cook foods: ask how many to make? just make all? make up to 5 at a time? already makes as many as you have parts for. how many would require modding each try_cook(somefood) call.
* pet: check health: left arm hp/dmg: need space after "l arm".
* as friendly leaders migrate and get removed, each new leader come up to player and greets them. should set all nearby friendlies to will_talk=0 when set leader to will_talk=0. now sets all freindlies within 500 feet of player to done talking when leader is done.
* quit to desktop from ingame menu
* fight or flight: should do flight for some period of time, not just until reach edge of fight or flight check range.
* CRH npc asks to trade: should do band trade, not individual trade.
* add band dialog action: ask ally to join village (move next door). checked and done!
* if CRH band is ally and shelter is within 500 of player's shelter, divide migration rate by 10 when changing the map. checked and done!
* villages - ally invite to join - add build hut quest. checked and done!
* allies should not ask you to join village if they have already asked you and you accepted but have not buiilt a hut there yet. checked and done!
* allies should not ask you to join village if you already have a hut near them. checked and done!
* added log object checked and done!
* heavy objects are exempt from container rules checked and done!
* heavy objects need only be nearby to use them checked and done!
* mark and unmark nearby objects as in use checked and done!
* added gather logs action checked and done!
* added wood wall object checked and done!
* added make wood wall action checked and done!
* inspect wood wall action checked and done!
* repair wood wall action checked and done!
* demolish wood wall action checked and done!
* select dead BM, take stuff. checked and done!
* add ability (IE action) to check resoureces in the area, see how low they are. . checked and done!
* new: fish with fishnet action. new object: fishnet. - already done : )
* new: add fishing actions to shoreline/ocean terrain . checked and done!
* new action: play with water. all water terrains. . checked and done!
* watch sunrise action . checked and done!
* watch sunset action . checked and done!
* new action: watch snow fall, like watch clouds.
* chat w/ bm action . checked and done!
* chat w/ npc action. . checked and done!
* catch rain in mouth (drink)
* catch snow in mouth (drink)
* select snow on the ground
* eat snow on ground for water. water goes up, but food goes down a little.
* melt snow with fire to make water
* shoreline: swim in ocean action . checked and done!
* select cave interior wall. checked and done!
* make cave painting. checked and done!
* new: obsidian resource. better than flint.- fisrt and easiest thing you can do is make it so you can find flint (obsidian) at volcanoes. then you can add the obsidian object (like the flint object), and the small obsidian point, and large obsidian point (takes less time, lower chance of success, higher value than flint). and then add obsidian weapons and tools. or just use obsidian to make higher quality flint tools. add obsidian object, only gather ta volcano. add small and large obsidian points. when make stuff with points, give option to use flint or obsidian, if obsidian, increase quality of weapon. or just add obsidian object, and give choice of obsidian or flint when making the point, and it increses the quality of the point, which will ultimately increase the quality of the tool or weapon. thats the easiest way to do it. so add obsidian object which can be gathered near volcanos (say within 300 feet). when make points, give optin to use flint or obsidian. if obsidian, increase quality greatly, or simply have obsidian always be 150 or 200 quality or something. coyuuld just have it display the name obsidian if the quality is high, and obsidian is just a high quality type of flint. that would be even easier. so add "gather obsidian (high quality flint)" to the volacano menu. takes a long time? yields high quality flint. requires one hand hammer stone?. checked and done!
* new object: pitch. a glue used for hafting etc. can use tar or tree (pine) pitch. to harvest pitch, wound the tree, then wait a few days. hmm - how to model that? woods - cut trees for pitch. woods gather pitch. must cut trees for pitch first. marks trees as cut - with a timestamp. when harvest, only
proceed if timestamp is old enough. clear timestamp when they harvest. make pitch use wood resources. make all objects require pitch for crafting. can't use tar yet, just pitch. checked and done!
* add to game: S_MEATVEGGIESTEW. already in there: S_STEW. object #31.
* new object: sundial compass stick. stick it in the ground pointing at the sun, and wait 15 minutes. the shadow points roughly east.
* find sundial compass stick action
* use sundial compass stick action
* researched deadfall traps, fishtraps, and tanning
* changed requirements for making tanned hide.
tanned furs:
1. scrape inside w/ scraper
2. mix brains and water, coat inside(?). soak & stretch to soften. - smoking can hasten process somewhat?
3. smoke to make insect repellent (optional)
tanned leather:
1. remove fur - scrape
2. scrape interior
3. soak in brains and water and stretch to soften - smoking can hasten process somewhat?
3. smoke to make easer to re-soften after getting wet. (optional)
so they are both basically the same, one you scrape off the fur, the other you don't.
so a tanned hide can be with or without fur.
and it requires brains, water, a clay pot, a scraper.
and all items should be made from tanned hides, not hides.
need to add brains object.... ugh could assume they take the brains with the hide... and the weight and value represents the hide and brains as a "package deal". until they make a tanned hide. then the brains are there, ready and waiting. except for buffalo, whose brains are too small to tan their own hide. no need to track eacj part of a butchered critter, just one per type of use. so for tanning you need hides and brains - in equal numbers, and you get hides and brains in equal numbers. so unless you get into trading them, you can just track one, and assume you always have the other to go with it - the "package deal" concept. so a hide is really more like "tanned hide parts".
* all objects now require tanned hide for crafting, not hide.
* removed tanned hide armors. all hide armors are now tanned.
* removed stone and shell armors - unrealistic.
* add funnel fishtrap object - inventory item
* add make funnel fishtrap action
* add set funnel fishtrap action. requires bait and stream, river, or lake. sets timestamp.
* add check funnel fishtrap action. check timestamp, add fish and remove bait
based on elapsed time.
* wood stake fishtrap object
* draw_dropped_obj draws wood stake fishtrap at water level
* make wood stake fishtrap action
* inspect wood stake fishtrap action
* repair wood stake fishtrap action
* abandon wood stake fishtrap action
* bait wood stake fishtrap action
* check wood stake fishtrap for fish action
* maps as treasure on dead hostiles. adds info to player's world map.
* musical bow object
* make musical bow action
* play musical bow action
* added stufflist_wt_carried_in_containers() routine
* added stufflist_container_capacity() routine
* added stufflist_needs_more_waterskins() routine
* added stufflist_can_carry() routine
* added encumberance checks to transfer_items
* added container checks to transfer_items
* added waterskin checks to transfer_items
* added transfer_items to storepit menu
* added transfer_items to travois menu
* added transfer_items to bandmember menu
* added transfer_items to exchange items with companion menu
* added avoid_cliffs() to B2_avian_common_part1 AI. if below and just south of cliffs, flies south and climbs.
* defend friendly questgen:
player hears of friendly w/ quest. player goes to friendly. freindly aks for help killing badguys threatening them. player hangs out, badguys attack. if friendly survives and all badguys dead, player gets reqqrd and end of quest. if frieindly dies, no reward and end of quest. if badguys get away, trigger another badguy attack after a while.
* random_active_npc now handles "all known npcs already active in sim".
* new_npc now returns -1 on error.
* all calls to new_npc now handle -1 errors.
* all calls to set_npc now check for npc_in_sim first
* fixed: add_gift_giver now checks for npc_in_sim already. was just adding the first npc found. used by both gifts and call for aid. get both at once and it tries to add the same npc twice - and BOOM! animation controller collision!
* turned off title screen
* allies ask you to join village: menu() is off by 1.
* fixed: allies give gifts too often?
* fixed: allies ask for help too often ?
* fixed: allies ask you to join village: menu() does yes when you click no and vica versa.
* decreased time for find wild veggies
* increased food boost of wild veggies
* fixed: gather pitch was missing from savanna and jungle menus.
* sleep goes down 10% slower on average.
* reduced frequency of ally gift encounters
* reduced frequency of ally call for aid encounters
* fixed: search dead BM: shows player's inventory, not dead BM's. says "give 10" and "give all", not "get 10" and "get all"
* exit cave: place them a little farther from the entrance.
* can't select cave interior to paint cave painiting!
* collision rad for cave interiors is a little too big.
* don't let them select the sky when inside a cave.
* adjutsed time and chance to find flint.
* fixed: gather pitch: shows fail msg after showing success msg.
* fixed: dont let them start gathering pitch if another BM in the map sq is already gathering pitch. action stops if another BM gathers the pitch first.

Norman Barrows

Major changes to Caveman v3.0 since the August 2015 release of beta 21:

ENCOUNTERS: (encounters and treasure now scale to party size AND level, not just party size)
* regular and quest encounter number appearing now scales based on party strength (numbers AND combat skills), so you get tougher encounters at higher levels of experience.
* regular and quest encounter treasure quantity scales with number appearing - which is now based on party strength (not just party size).
* quest treasure quality now scales with party strength.
* time of day now affects encounter chances.
* remaining resource levels in a map square now affect encounter chances in that map square.

COMBAT:
* hit location and damage by body section, including cripppling, and its effect on combat, movement, and all actions.
* modeling of critical hits.
* modeling of bleedout, including a new "staunch wounds" action.
* check follower health and and check pet health actions (shows dmg by section, bleeding, etc).
* separate weapon hotkeys for each bandmember.
* new orders: alarm! (IE battlestations, we're under attack), stop what you're doing (stop current action).
* new action: automatically walk around and pickup ammo. super nice when you have dozens of arrows lying about after a combat.
* you can now change weapons while attacking. you just have to start the attack over with the new weapon, thats all.
* option to switch to bandmember when they get an encounter if they are not the current bandmember (IE the one the player is currently controlling).
* new skill: combat defense. works in lieu of hp increasing with level. refects you getting better at defending yourself.
* new combat move: dodge. quickly moves you fwd/back/left/right.

AI:
* new land predator AI.
* new defend location AI (used by quest encounters).
* new pack hunter AI.
* new domesticable wild animal AI (used by dire wolves).
* new follower AI
* new pet AI
* new combo defend/maintain distance AI - maintains distance from stronger animals, stands its ground and defends against others.
* respond to missile fire by animal type (all of a type attack or flee, not just the one fired upon).
* animals flee from campfires.
* graze behavior (wander, stand, flock, migrate) for pets.
* improved (but not perfect yet) AI for avians vs cliffs.


BUTCHERING ANIMALS:
* re-balanced amount of meat, hides, tendon, etc from animals. amount of meat, bone, hides, etc on an animal is now based on animal weight. all animal types now have a weight. the heaviest being Stegodon (a type of mastodon) at 28,000 lbs.
* individual tracking of meat, hide, bones etc left on a carcass (and thus available for harvesting). also tracks meat quality - and meat on carcasses spoils over time too.
* butcher actions now take a short amount of time, and yield one unit of resources, and continue until you can't carry any more or there are no more resources. it used to take a long time (like a week for a single caveman vs a mammoth carcass!), then give you everything at once.
* multiple band members can now butcher the same carcass simultaneously.

QUEST GENERATORS:
* implemented 20 of 50 planned quest generators.

NEW OBJECTS:
* teepee - basically a portable hut.
* bedroll - basically a portable version of bedding.
the teepee and bedroll combined with the travois means you can now take your entire camp with you.


ACTIONS:
* you can now build huts and lean-to's in caves.
* new dialog option: greet caveman
* new dialog option: exchange news - added in anticipation of adding fame and / or reputation to the game. exchanging news is how fame/reputation will travel.
* added ability to abandon quests you no longer wish to pursue.
* success or failure sound effects and messages for all actions upon completion

TRADE:
* re-balanced trade value of items
* traders now have limited quantities of inventory and money.

SIMULATION:
* max band members increased to 50
* max active animals increased to 500
* water stat goes down faster in hot weather.
* band members now stop most actions if their mood drops too low.
* improved domestication of dire wolves.
* local temperature now affects rate of food spoilage.
* tracking of resource depletion in a map sqaure on a per type basis, instead of as one generic resource.
* resources now replenish continually over time, instead of being totally depleted for a while before instantly replenishing to 100%.
* wild vegetables and poison plants are now found in more types of terrain.
* ability to exchange items with your travelling companions. includes tracking ownership, yours vs theirs. and NO, you can't take their stuff!
* gifts to NPCs now appear in their inventories.
* automatic transfer of liquids with containers finally works correctly.
* rafts have now been fully implemented. collision checks, AI, actions, etc - everything works with rafts now. during testing, it was very cool sailing across the ocean on a raft with one other band member, one companion, and my pet dire wolf, and seeing a new shore for the first time.
* friendly cavemen now have a chance to come up to you and initiate various dialog actions when you encounter them.

SKINNED MESHES:
* better animations
* correct materials
* correct pitch relative to the 3pv camera
* drawing of equipment

TUTORIAL:
* added making a wood spear to the tutorial - the stone knife object became a cutting tool, which is no longer a weapon.

OTHER:
* numerous minor adjustments and fixes to game balance - god is in the details!

a long period of time was spent addressing the question of "what to do when you're high level?".
the traditional solution of "Build a castle, raise an army, conquer the world!" from classic Dungeons & Dragons doesn't really work that well with a stone age setting.
turns out, its not "what to do when you're high level?", its "what to do when you've done it all?" (IE used up all the content in the game).
players need a continual supply of compelling new content appropriate for their level, not that hard in classic D&D, given an obliging DM. somewhat harder to do in video games (free high quality DLC to the rescue).
regular and quest encounters and treasure that scale to player's level provides content of appropriate difficulty for the player's level.
the ability to generate 50 different types of quests (compare to two for Skyrim's radiant quest system) will help keep things from getting repetitive too quickly.
a quest editor is also planned, along with some number of quests made with it, such as one or more optional story line campaigns. this will allow users to create and share their own quests. which may provide another possible source for compelling new content appropriate for the players level (since quest editor quests -IE number appearing, and treasure quantity and quality- will also scale automatically to player level).

WHATS NEXT:
* the ability to build a castle - caveman style. IE wood, dirt, and stone wall objects.
* multi-band settlements (proto-villages) - ask you allies to move next door.
* making the player seek out a wide variety of foods so they don't just stockpile and eat nuts all the time (for example). eating the same thing all the time will nuke your mood. maybe your stats too if mood isn't enough motivation.
* there are still a number of new actions, objects, and animal types still to be added to the game.
* misc features such as browsers for object types, animal types, and actions.
* multi-band gatherings
* mini games:
- stick and hoops (similar to lawn darts)
- chunkey (hit the thrown ball with the spear)
- non-lethal combat
- archery competitions
- and of course "rock", as in rock-paper-scissors. but its the stone age, so its before they invented paper and scissors, so they just have "rock". pretty boring game actually - always ends in a tie! .
* boss monster and boss caveman encounters for high level players.
* final graphics

and then it will finally be time to release. smile.png


there is currently no beta demo available. the public beta was a smashing success, with only two users reporting issues, one related to startup resolution detection, and the other unrelated to the game (corrupt UAC file interferes with install/launch, causing the dreaded BEX error). as a result, the startup resolution detection code has been beefed up to explicitly check caps, instead of assuming that caps which should be there are there.

I may run a semi-private beta for folks interested in providing feedback on gameplay. not sure at this point. if anyone is interested in something like that, PM me. you can never have too much feedback - whether you're talking games or guitars! . (yeah, i play the electric guitar).
.

Norman Barrows
Beta 21 w/ skinned meshes released!

guys look kinda dumb, girls aren't that pretty, the guy walk ani is kinda awkward (leg bones rotated outwards too far), no action animations or drawing of equipment yet other than weapon in hand, but its a start!

http://rocklandsoftware.net/beta.php

action animations and drawing equipment is next. I'll clean up that guy walk ani too. i found an unbelievably beautiful female head while looking for PD skinned meshes, which i plan to try and "Dr Frankenstein" onto a body. plus i also have the pretty girl heads from the rigid body models. Good looking guys - not so much luck. Just ultra high poly stuff i cant use - such as my original rigid body guy - the search continues. Just like a writer / producer / director in the film industry, i want/need/should use the most photogenic actors. My players deserve no less.
Norman Barrows
Work on skinned meshes continues

I added the ability to draw weapon-in-hand to the skinned mesh test routine. It can toggle between weapon types, and uses the game's built-in matrix editor to position the weapon with respect to the hand bone. The test routine is used to determine the fixup transform for a weapon, which is then added to the database info for that weapon type.

It now draws all 65 or so different types of weapons in a skinned mesh female's hand.

A fixup transform for male meshes is next. Male and female meshes share almost identical skeletons, so just a single fixup for male vs female skinned mesh is required to make all the weapons draw in a male skinned mesh hand as well - IE move everything down and right a bit to account for the difference in the male and female hand meshes. These fixup transforms are roughly the equivalent of positioning a weapon bone for each skinned mesh in the modeling software, and transforming all weapon models in the modeling software so their grip point is at the origin, then drawing the weapon at the weapon bone with no transform. Unlike your typical shooter, not every weapon in Caveman has a uniform type and size of grip, such as a pistol grip or sword handle. so tweaking on a per weapon basis is really required to get the best possible fit.

Then comes the remaining attack animations. One hand attack is already done. spear thrust, bow attack, and a few others still need to be made. It looks like I can even share animations between male and female skeletons. It also looks like I need to clean up the skin weights a bit on the male meshes - the upper arm influences the ribs area. I thought it was from using the female attack animation, but its just a weight tweak issue, not an animation sharing issue.

I'll need to make a version of the skinned mesh textures for use with the existing 1st person attack animations - a simple copy/paste type operation in paint.net or gimp.

I also need to make some improvements to the startup resolution autodetect code. Right now its selects the resolution with the highest horizontal value that supports A8R8G8B8, and assumes 24bit depth buffer support is available at that resolution - which may not be a safe assumption in rare cases. I've only had two people report such issues.

And then its time to release beta 21. Beta 20 has already expired, so at the moment there is no beta available for download. Beta 21 should be ready in a couple of weeks. In order to get beta 21 out sooner, it will not draw armor or equipment, and won't have action animations. those will all be included in beta 22, which will probably take 2-3 weeks from the time beta 21 is released.

And then comes skinned mesh animals....

i'd better get back to work!
Norman Barrows
Adding skinned meshes to Caveman


A quick update since i haven't posted anything in a while.

I'm busy adding skinned meshes to the game.

When i started working on the game, i was not sure if i could draw the required number of skinned meshes on the target platform, so i used rigid body models to start with.

Now that i'm putting the final whammy on graphics, i decided to give skinned meshes a try.

A test run of the DX9 multianim sample showed the code could draw the required number of characters onscreen at once on the target platform.

So I turned the code from tiny.cpp into a skinned mesh library, got the dx9 animation controllers working, and figured out how to get blender and directx to work together.

You can take a look at the code here:
https://www.gamedev.net/blog/1729/entry-2261223-skinned-mesh-code-part-1-low-level-microsoft-code/

I'm able to share skeletons in blender, share animations via a batch file of copy+ commands, and the code has been designed to share meshes, textures, and materials. meshes, textures, materials, and controllers are all pooled.

The first thing i did was a test routine in the game to test the drawing of 100 characters onscreen at once with individual animations.

so far i've made all the human models and all the movement animations, and they are all up an running in the game.

i also added "change character appearance" to the playtest menu, allowing you to change a band member's appearance (even sex) at any time. This was required to assign new skinned mesh values for the band members in the long term playtest game.

attack animations are the next step. and then comes drawing weapons in hand, and equipment which is worn. i hope to simply attach all equipment to a bone, but i may need to animate some with the skeleton, the way i do for bra and loincloth. even attaching to a bone, i'll probably need a fixup transform on a per object basis to position it precisely with respect to a bone. and there are 65 kinds of weapons....

and then comes action animations.

and then comes skinned mesh animals... i'm going to be busy for a while!

actually, its going faster than anticipated. about 2 weeks to figure out dx skinned meshes. about 1 week for coding - really only about 3 days work there. another week or so to figure out blender. perhaps a week to do the meshes - there's basically just two, a male and female, 5 versions of each with different facial features and shared skeletons and animations. animations are taking about 30 minutes each on average to create, add to the game, test, and fix as needed.

i think there are only about a dozen attack animations per sex. and two to three dozen action animations. maybe a week's worth of work there.

for animals, i hope to use a few basic skeletons (such as quadruped) scaled to various body meshes, with shared animations. i think i'll be able to share animations between similarly scaled quadrupeds. so maybe one set for large quadrupeds, and one for small. each animal will only need about half a dozen animations. but there are fifty of them....

i don't plan to release a new beta until i have at least the attack and a few placeholder action animations in, as well as drawing weapons and equipment. The current demo expires soon, so there may not be a demo available for a while while i make the necessary changes.

once attack and weapons are in, i'll post a new demo, then move on to doing more action animations and skinned mesh animals.
Norman Barrows
Caveman v3.0 Beta 19 released!


Play now!
http://rocklandsoftware.net/beta.php

Numerous changes in Beta 19:

* added export band member
* added import band member
* added de-activate band member
* make pigment rock object smaller.
* draws obj in hand for find pigment rock action.
* confirmed game won't run on XP.
* added obj in hand for make/find objects #70 pigments thru #173 blanket (103 objects - some need new anis though). added dinfo and fix as needed. made draw_dropped_object use dinfo where appropriate.
* added: stone drill required to make stone top armor.
* completed first pass at assigning obj in hand for make or find anis for all 237 object types. but some still need new graphics and / or anis. so most make, find, and repair animations draw object in right hand now, say 400-500 animations or so.
* reduced size of clay object
* make, repair, demolish type animations drawn closer to ground.
* increased NPC base chance to hit from 50% to 70%.
* increased BM hand attack base chance to hit from 60% to 70%.
* increased BM missile attack base chance to hit from 50% to 70%.
* moved make ani back down to -1.5
* made selected_dropped_object the first check in select().
* turned off colision avoidance in rocks. terrains is so thick they appear to just cycle between collision avoidance and collision recovery.
* select: checks for shelter before bedding.
* collision recovery: cut recovery time in half, since they now move at sprint speed (2x run speed)
* BM attack AI: explicitly calcs rng to tgt for start of attack. rng may have not been preset in cases such as "attack orders tgt", which overrides the tgt set by set_tgt. set_tgt pre-calcs rng and rh to tgt when it set the tgt.
* BM AI: no badguys nearby: priorities changed to:
1. do action
2. collision recovery
3. do orders
4. recover fatigue
5. stand
* BM collision recovery: cut recovery time in half, since they now move at sprint speed (2x run speed)
* maintain dist ai: added is_maintaining _distance AI state flag to animalrec.
AI now flees at 25 and stops fleeing at 50, instead of starting and stopping at 20.
* added BM AI on/off for CM0 via backslash key w/ AI display
* BM AI: draws wpn if attacking
* BM AI: reduced start atk rng
* sleep ani drawn lower to ground
* made sleep take a little longer
* increased rad for "inside perm shelter" from 5 to 10 feet
* daydream, watch clouds, stargaze: mood now goes up one every 5 minutes not 6.
* improved bigdice routine
* AI backs up at half speed
* BM AI start attack range for missile wpns set to 50.
* turned off collision avoiadance in woods - too dense
* collision avoidance rng reduced fro 15 to 10 ft
* playtesting
* flint spear: reduced cordage required from 3 to 2
* doubled value of hides and all objects made from hides
* done - made int affect building and fixing hut
* done - made int affect learn action: time, chance, and xp earned.
* done - fill waterskins takes too long
* done - draw all bm's on local map
* done - remove dead / butchered / sacrificed anilas after a while
* done - kick bm out of band
* done: " you learned something new about " msg
* done: show bm name for a few secs when tab to next bm
* done: changed "do" and ".do" keywords in cscript to "d" and ".d". removed all c++ code blocks from source code. all code is now cscript or c++ that does not conflict with cscipt keywords. no c++ code pass thru blocks required! no "cpp" and ".cpp" everyhwere in the code! recompiled all source code with new version of cscript.
* done: made perm shelters a world object
* done: repair: parts reqd: 1/2 round down, not up.
* done: repair: quality is now avg of old and new.
* done - too easy to find cool rocks
* done - adj party str - too many badguys?
* done - companion ai stop when within 20
* done - increase base chance to make lean-to
* done - made int have greater effect on time and chance to learn stuff
* done: increase value of hides and stuff made with hides
* done: make flint tipped spear: only reqires two cordage.
* done: objects ropped in aved get placed outside caves.
* done: made int affect qual of tirm repaired
* dont let them pickup player huts - and abandoned huts - and landmarks
* adjust hut collision checks
* separate key for pickup dropped object. - z?
* bmsg "you pass out from lack of sleep"
* add "quiting caveman" screen at end of prog
* storepit full msg added, objects no longer lost when pit is full.
* precip increases water table by twice as much. no precip reduces water table by half as much. water table goes to baseline twice as fast over time. had global warming issues.
* automap_small_stuff radius increased to 300 feet
* fixed: automap_small_stuff does huts now.
* added next idle band member hotkey "N"
* daydream etc increases mood faster
* bmsg you arrive at your dest
* quiting caveman screen
* show all parts / skils for action if you dont have something
* joke and story actions: increased chance of relations improvement, increased mood boost.
* doubled find time for flint and cool rocks
* added initializing blank game msg
* increased base chance to make temp shelter. made int affect chance. improved how chance is calculated.
* increased chance to make storepit
* reduced caveman base number appearing.
* reduced effect of party strength on cavean number appearing
* party strength based on those within 300 feet, not on those in same map sqaure.
* increased drawing radius of bedding and storepits
* fixed: party_strength: using a continue statment in the while loop skipped the call to next_active_BM at the end of the loop. hazards of using a "findfirst/findnext while loop" instead of a "0 to max for loop". bloody generic iterators!
* make cordage, make arrow actions: now continue until you run out of parts.
* show next BM name in UL corner of screen for a moment when tab to next BM.
* remove butchered / sacrificed animals after some period of time.
* increased no draw rng for huts and storepits.
* fixed: common ai: tgt is stronger: was using BMs hp adjusted for diff lvl, not base hp for a type 2 animal (homo sapien). predators would close, then flee during common fight or flight.
* fixed: subdued and captured animals shouldn't be able to move.
* turned off atk to subdue. doesnt make sense for domesticating dire wolves, and you can't subdue and capture cavemen, and you shouldnt really be able to domesticate anything else, so...
* dire wolf hp reduced to less than humans so they dont atk people.
* need to implement new way to domesticate dire wolf. dire wolf goes for dropped meat. drop enough they follow you. drop more they allow you to approach. give meat action. give enough meat, they become pet. added new dire wolf AI: if dropped meat nearby, they goto dropped meat and eat it. eat enough, they start following the closest BM at that time. eat more, that bm can approach and select and get dire wolf menu (give meat, cancel). give enough eat, they become state=TAMED.
* dire wolf - they dont move to the meat - exhausted? called run (spd based on rng to tgt) instead of run maxspd
* fixed: predators ignore stronger animals. sets pred tgt (ignore equal or stronger) only when hunting, and sets wild tgt (dont ignore any) the rest of the time.
* fatigued animals now rest until fully rested, not 2% rested
* wolf: moveto owner: runs if rng > 100
* wolves with relations > 1000 are not removed when distant
* player can now accel tieme faster than 128x when only predators weaker than humans are nearby
* added message when tame wolf
* added "enter name for new pet..." when tame wolf
* fixed: other wolves attack your wolf when you tame it. friendly wolves no longer count as leader for flock behavior. other wolves now wander off.
* fixed: wounded tame animals flee forever. made AI flee from closest threat, not current target (pet owner if pet is far from owner). added closest threat function based on animal type (wild animals and hostile cavemen, -or- pets, warriors, companions, friendly cavemen, and bandmembers).
* predators now only target weaker foes, not equal or weaker.
* wild leaders for flock behavoir now excludes tamed animals and friendly wolves.
* fixed: drink from leaves: says its snowing when its raining! used 40 degrees instead of SNOW_TEMP. searched the entire code. this was the only place SNOW_TEMP wasn't used when it should be.
* fixed: pick fruit crashes game. tool_and_part_quality: calculating avg quality of tools and parts used: did divide by zero if numtools and numparts was zero. now returns quality of 100 of numtools and numparts is zero. did same fix to RR_tool_and_part_quality. no other occurances of similar code "/ sum count" in the game. shift select blows up if list full, no range check? - same bug.
* fixed: pick fruit action - game crashes. tool_and_part_quality: calculate avg tool and part quality: divide by zero if numparts and numtools = 0. now returns quality 100 if numprts and numtools = 0. did same fix to RR_tool_and_part_quality. searched entire code for: "/ sum" to find bugs similar to: "/ sum count". none found.
* fixed: full storpit - get stuff - scroll way down crahses? select_object and shift_select_object: list was 20 long, now is 40 long, scroll limit was still max-20, not max-40. no similar bugs found.
* animals list full? added error messages everywhere the game adds animals.
* cool rocks still too easy to find. doubled time required. cut chance in half. works out to about 4x as hard.
* fixed: demolish wood shelter doesnt take long enough. demolish_shelter action used buildtime(world_object_index), not buildtime(world_object_index.shelter_type) oops! .
* fixed: demolish leanto doesnt take long enough: fix to demolish_shelter action fixed this too!
* base chance to make bedding too low? increased from 50% to 70%
* bow wears out too quickly? cut avg rate of wear by factor of 10.
* add storepit - doesnt rest chunks and collision maps? the low level funtion now does it for all calls to add storpit.
* fixed: demolish bedding in shelter demolishes the bedding. was demolishing sheletr_index, not sheleter_index.bedding_index oops! .
* fixed: shelter weathers away while bm inside asleep, or inside in general. added msg that your temp shelter weathered away.
* fixed: ingame menu: increase width of hotspots
* fixed: ingame menu: video and gameplay hotspots overlap
* fixed: ingame menu: only play klik when the click on an option.
* fixed: dont let them move x-country from inside temp shelter. did "up a tree" too! now can only move x-country when OUTSIDE or ONRAFT
* fixed: npcs: all interests should be unique
* show msg when complete search dead caveman action, then show the take item screen.
* search dead caveman: if they dont have anything, just show a msg instead of the take item screen.
* fixed: daydream etc should reduce fatigue. energy wasn't set to 1 for daydream, stargaze, and watch clouds actions. energy=1 means they recharge fatigue while doing that action.
* fill waterskinrain doesnt take long enough - increased time by factor of 10.
* done: to make / fix (skills list) msg: dont say make / fix. its used for stuff like learn too!
* fixed: collision recovery moves before it finishes turning? now it doesnt move until abs(rh) < ~11 degrees, not <45 degreees.
* what happens when run out of ani players? turned on error msg in z3d library
* fixed: falling rain should not wake up bms inside a hut. BMs in player huts and rock shelters are not woken up by precip.
* fixed: move following bm's moves any following even if not nearby or following someone else. only move nearby who are following the BM in question.
* increase size of collision map cache. increased from 20 to 40.
* done: make mouse wheel zoom camera in and out faster. did keyboard controls too (numpad plus and minus by default).
* done: 3pv cam vs hut interior - switch to 1pv temporarily? uses 1pv when player is inside hut.
* fixed: glypto moves too fast. cut speed in half.
* big cats get stuck in woods
. big animal encounter spacing vs rocks and other dense terrain
. big animal encounter rng too close
. elasmo vs woods
. imp mammoth encounters too close to player.
. imp mammoths start too close togetehr. flip betw collision avoiddance and recovery.
. palorchestes gets stuck in woods
increased spacing. increased encounter range based on size of group. now near edge of group, not center of group, is at encounter range. fixed something in way of animal - it didnt take radius into account - thus the animals stuck in rocks etc. now it checks center, and the 4 bbox corners for something in way of an animal when doing initial placement of animals encountered.
* fixed: game crashes when you try to fix something that can't be fixed (wood grindstone, 1 hand hammer, etc). now it gives you a message saying that type of object can't be repaiered.
* fixed: follower joins band: rain sfx stops. player stuck in collision with new BM.
action sfx init-ed to 0 not -1. didn't adjust bandmember location. adj bm loc didnt handle radius.
stuck in collsion with new bm: rounding error: animal_in_way_of_bm used float rng, bm_in_way_of_bm used ints. now both use floats.
* fixed: move followers, moves those with orders to the contrary suchas wait here goto here, etc. followers with goto orders, or orders to follow someone other than the moving BM, dont get moved.
* attack thief - all neutrals become hostile? only if you attack before the dialog shows.
* yield: init NPC_type so yield works? test yield. make sure it works. it may not use npc_type anymore. yield works. npc type is set already. make thief_dialog set thief to NPC_KILLER if they
become a HOSTILE.
* cave hyena didn't attack? increased hp of some predators so their AI will attack humans
* orders: atk: doesn't work when no tgt? or at all? need to test it some. if no orders tgt, uses current tgt, if none, doesnt atk. tested. woking fine.
* fixed: order pet to wait here doesnt work. b2_issue_animal_orders told animal i to goto bandmember i's location, not animal i's location. a copy-paste-edit error, introduced when converting the code from cm[] to animal[]. but follower AI still needs help. they follow owner before following orders!
* follower ai needs help - make it like bm ai. changed follower ai:

old priorities:
do common AI
move2owner if > 100
if tgt nearby do orders or atk
listen to story etc
moveto owner if > 20
stand

new priorities:
do common AI
do orders (if has orders)
atk nearby tgt (if has one)
listen to story etc
set move2owner_flag
move2owner (if flag set)
stand

* fixed: game doesn't model spoilage of food in storepits
* already done: teach doesn't take as long as learn? already fixed: learn was called once per game minute, and teach was called once per frame (update or turn) - IE 15x per game second.
* show skills: dont show last 3 undefined skills. dont show mapmaking. is bonelore used? mapmaking? re-did view_skills - made a new view_skills2 routine. bonelore and mapmaking are gone.
* order everyone: gets goto location, target, or who to follow just once, instead of once for each party member ordered.
* fixed: didnt set bedding's world object ID when resting on bedding.
* DONE: dont let 2 BMs use the same bedding at same time. when select bedding, need to check all other bm's for bedding action with that bedding, if found, show msg saying someone is already using that bedding.

DONE: WATER and WATERSKINS:
* improve how water and waterskins work. move the water with the container.
make sure they have sufficient waterskins whenever they transfer water. store in pit, drop on ground, fill waterskins (water source or rain), give water to bm, pickup dropped, etc.
when they transfer a waterskin, transfer water as needed. dont let them drop water. only let them drop water in waterskins. abandon water as requierd if they abandon waterskin.
need to possibly mod calls to add2inventory and add2stufflist. fill waterskin watersource, fill waterskin rain, give water to bm, npc menu (trade, ask for item), trade with band (get water).
* fill waterskins and fill waterskins rain check for waterskins full and max encumberance at start of action handlers. fill waterskins didnt check encumberance until water was gathered. fill waterskins rain didnt check it at all!
* all fill waterskin from water source actions now use try_fill_waterskins.
* made sure fill waterskins and fill waterskins rain check for player has waterskins. so now - for sure - they can't gather water without waterskins. can only get it from storepit, other BM, NPC, or trading with a friendly band.
* checked: get stuff from storepit makes sure they can carry water before giving it to them. so it makes sure they have enough waterskins.
* store stuff: checks for waterskins in the pit, and not all full. now you cant store water in a pit that doesnt have non-full waterskins.
* drop object: no longer lets you drop water. tells you to drop a waterskin instead.
* checked: pickup dropped object calls can_carry, which check encumberance, container capacity, and waterskin capacity. so they can't pickup dropped water without a non-full waterskin.
* newtrade and trade_with_band: doesnt let you trade for water if you dont have non-full waterskin.
* ask for item: doesnt give water if cant carry
* trader hut: doesnt trade for water if cant carry
* give_item2bandmember: doesnt give water if cant carry
* getstuff and storestuff: transfers water as needed when get/store waterskin.
* give_item2bandmember: transfers water as needed when give waterskin.
* trade_with_band: removes water as needed when trade away waterskins
* new_trade: removes water as needed when trade away waterskins
* trader_hut: removes water as needed when trade away waterskins
* fixed: some calls to indexdropat checked for return of 0, not -1 on error.
* indexdropat activates new record for each waterskin dropped. no longer adds waterskins to existing active records. so each active record with a waterskin has only one waterskin, and data[0] can be used to store how much water is in it.
* drop object: transfers water to dropped waterskin as needed. amount of water is stored in waterskin worldobj[].data[0].
* abandon object: removes water as needed when abandon waterskins
* transfer_to_waterskin_as_needed: calcs avg qual of water transferred, and stores it in worldobj[].data[1]
* pickup_object: if object is WATERSKIN, checks encumbrance vs waterskin+the water in it, and transfers the water with the waterskin, if they can carry both the waterskin and the water in it.
--- END WATER AND WATERSKINS CHANGES ---

* DONE: turn clip ranges and autocliprange on again. this also fixed: clip rng for animals too far compared to clip rng for terrain chunks.
* cant see small dead animal under the water. draw them at y = 0. dead animal in water are now drawn at y=0 (water level) - IE half floating in the water.
* 3pv cam, make min altitude ground + a few feet so its above ground coverage. defined MIN_ALT_3PV_CAM. set it to 3.0f (three feet). old hard coded value was 1 foot.
added it to set 3pv cam for: cave, cavern, outdoors, perm shelter, rockshelter, and hut.
* make anis: need different y's for male and female.
* dawn & dusk are a little to dark. they are now lower limited to nighttime lightness.
* fixed: doesnt do fire light in adjacent map sq
* make 3pv cam look over avatar's rt shoulder
* sleep ani - draw at different heights dependingon has bedding
* dont draw avatar in 3pv if player is looking almost straight up.
* make sure accel time display, tutor messages, hud, etc dont overdraw each other.
* already done: not stop and start anis correctly when NPC joins band?
* already done: view inventory: flush sprites before drawmouse
* sleep on bedding: make them line up on the bedding. adjust location and orientation.
* dont play rain sfx when snowing
* doesnt play fire sfx in adj map sq. typo bug. called dist w/ mx,mx,x,z, not mx,mz,x,z.
* view stats - only play klick when they click on the done or rename buttons.
* add tada sfx to game saved.
* make animals do sliding collisions
* already done during playtesting: show all BMs on local map
* make mouse wheel zoom world map in and out.
* reinit dice from time to time. now calls initdice once per game day.
* more animals ? double the base chance of animal encounters?
increased by 10x. try it and see...
* more water. rocks etc?
water: every map sq, to once every 10-100 map squares
rocks:
chert, flint: 28% of land = 1 in 3.57 map sq's on avg.
obsidian, quartzite: 1 per 230 map squares (mtns & volcanos only)
volcanoes: one per 4600 map sq on avg. in lines along plate boundaries.
tar: seeps from underground oil deposits which cover perhaps 10% of the planet. = 1 in 10 map sq's on avg.
* talk to caveman: ask directions to rocks, berry bushes, good hunting grounds, etc. a simple goto location quest. getting there is the reward. talk to cavemen: ask directions to water, woods, rocks, etc. do they always know where stuff is? do they always tell you? do they sometimes tell you a bogus location? can you ask them more than once and get a different response?-no
+ trade maps w/ npcs, will they trade? do they gve you a bogus map? can you trade more than once and get different maps?-no
+ npcs: ask whats around: do they always know? will they tell always you? do they sometimes give you bogus info? can you ask more than once and get a different response?-no
+ combine ask directions, whats around, and trade maps, and what do you get? an extended whats around. npc: exchange knowledge of area. caveman: ask whats nearby - automaps everything in a 1 or 2 (or more?) map square radius around the player. not as realistic as tracking what each npc knows, wheter they will tell you, if they give you bogus info, if you've already asked them, etc. so you need flags for "what they know", and "if you've asked them already" for each thing you can ask them (where's rocks, water, wood, whats to the north, etc)
+ simpler - relations governs if they tell you or not, and it reveals world map in a 2 map sq rad (for example) on success, and nukes relations some on failure. but can ask again, (with ever decreasing chance of success due to ever decreasing relations from repeatedly asking ; ) ).
+ or would early humans freely share such knowledge? friendly caveman: exchange knowledge of local region. why wouldnt they? resource competition? not in early stages when resoureces where plentiful. cant see why they wouldnt share knowldge of local area. it would automap say, everything in a 1 map sq radius around current location - world and local maps - completely - IE entire local maps revealed.
* talk to cavemen, ask if you can travel with them. - if yes...then what? you can follow them around -whooptie do! if no...then what? they throw rocks at you to keep you from following them? i mean - hey, its a free planet - right? if you happen to go where they do, as long as you dont interact with tem and nuke relations, no biggie. - or- you become their companion, and must hang out near them, and they fight with you, and give you orders. go here, wait, attack that, etc. but a nearby friendly will generally fight with you. so ask to travel with may not be needed. you can just follow them if you feel like it.
* add dismiss follower action
* already done: encounters don't correct for encounter location in adjacent map sq when player near map sq edge.
* "move storepit" added to playtest menu
* fixed: Zdomessages, getmouse, and mouse wheel. now fps view and world map both zoom with mouse wheel.
* grogs game converted to new savegame format.
* new world map generated for grogs game. moved the base camp. added new huts and bedding. moved all storepuits. abandodned empty storepits.
* finished converting grogs game to new world map. demolished all old huts and bedding. now they're all at the new camp, making arrows, gathering wood, or sleeping.
* made BM vs BM and BM vs NPC relations go to zero over time
* followers: take shares. original version, followers took a share of hides, meat etc from kills at the end of fps combat mode. now follower reations go down over time. if < 50, they leave your party. so you have to give hides etc to keep them in your party.
* types and numbers of animals at crh's is not persistant. when gen encounter, have to set type and num. when one dies, reduce num. added animal_type and num_animals to crhrec. added is_crh_animal and crh_num to animal rec. if game does cave or rocksheletr animal encounter, if crh2.num_animals<1, it generates crh2.animal_type and crh2.num_animals. else it uses the current values. when an animal is killed, if animal.is_crh_animal, crh2[animal.crh_num].num_animals--.
* eruptions: should be 10% chance per year per volcano of 1 eruption. = 10/365/24% chance per hour for a given volcano. reduced from one per week on avg to ~10% chance per year, specifically: 11 in 1000000 per hour.
* improve timing of state changes in graze AI. reduced chance for state changes by factor of 10. flock rng changed from 50 to 25*animaltype.rad.
* make int have greater effect on time and chance to make and fix stuff. some of this is already done, but not all make and fix actions. make int affect time, chance, and qual of all items made or repaired. also added adjust for dex as needed.
ALREADY DONE:
makeobj
learn
fix_object
build_playerhut
repair_playerhut
makeobj2
repair_world_obj
repair_trap
teach bandmember (learners int only, not teachers)
FIXED:
makefire
cook
make_shelter
repair_shelter
make_bedding
makebedshelter
fixbedding
make_storepit
repair_storepit
make_raft
repair_raft
poison wpn
find_object
addwood2fire
forrage
train (w/ wpn)
learn_from_caveman
teach_caveman
learn_sailing
apply_camo
* improve avian ai. fixed: move_avian set y to ground height! made "orders: maintain distance" use new maintain_distance AI code. made avian AI code match animal AI code. collapsed some redundant code into single stand alone function calls.
* drop object doesnt handle dropping objects across a map sq edge into the next map sq! need to normalize dropat location rel to cm0. either that or remove distant dropped doesnt work across map squares. fixed: drop_object now normalizes drop location. any_BM_near_worldobj: added check for BB map sq dist < 2. it already handled map sq edges in other respects.
* game doesn't model bedding weathering, just wearing out from use.
* fixed: bedding.data[0]=is_in_shelter, bedding.data[1]=shelter_num, shelter.data[0]=has_bedding, shelter.data[1]=bedding_num
* make teachers int affect "teach bandmember" action.
* fixed: bm_in_way_of_bm: call to BBdist: typo: was mx1 mx1 mx2 mz2, not mx1 mz1 mx2 mz2. duh! took all morning to find and fix. will check all calls to bbdist for similar typos. and calls to dist2!
* fixed: get_fire_sfx: typo in call to bbdist
* fixed: get_fire_sfx: typo in call to dist2
* checked all 174 occurances of BBdist for typos. only found the one in get_fire_sfx.
* checked all 68 occurances of dist2 for typos. get_fire_sfx was the only one.
* fixed: getstuff and storestuff: was if index==WATER, not if object[index].type==WATER.
* fixed: getstuff and storestuff: was "if index==WATER", not "if object[index].type==WATER".
* fixed: drop_object: was "if index==WATER", not "if object[index].type==WATER".
* fixed: too many encounters are elephants. now all 6 elephant types collectively have the same chance as any other single animal type of appearing in a given type of terrain. IE if there are say, 32 differnt types of common animals in a given terrain type, now just one will be "some sort of elephant". what sort of elephant is then determined based on the terrain type (not all types of elephants appear in all terrain types). this for example, reduced elphant encounters in savanna from 16% to 3% of all animal encounters.
* checked out skinned meshes. code looks doable. .x files look ok. truespace has rigged models ready to go. need to learn how to animate models in truespace.
* eat/drink: show a menu of edible inventory to choose from.
* make mouse wheel zoom world map faster.
* butcher: add bmsg(). added ": you butchered an animal!"
made all messages such as "you get some meat!" read ": you get some meat!". that should help keep things straight when the band is butchering kills after a hunt.
* automatically load last saved game if player dies (except in tutor). added to continue, new, and load.
* replace all calls to select_item with shift_select_item. now only repair_object and sell_to_trader actions have you select just one object at a time. only "select item to trade band for" needed to be changed. all others already used shift_select_item.
* implemented new zoom-able local map! : )
* more hotkeys for world map: arrow keys and numpad arrow keys to scroll u/d/l/r.
* more hotkeys for local map: arrow keys and numpad arrow keys to scroll u/d/l/r.
* fixed: 1pv w/ wpn drawn, or sprinting, can see 3pv avatar! code got screwed up when "dont draw avatar in 3pv when looking almost straight up" was added. this also fixed: still draws 3pv cam when look up
* fixed: 3pv cam is too far to the right. moved to from 1 foot to 1/2 foot right of center. #defined xofs_3pv_cam. made all six versions of set3pv cam use it. there are six versions to adjust to the six different types of complex environments in the game (outdoors, in hut, in rockshelter, in cave, in cavern, and in playerhut).
* girl sleep on bedding: bandmember y is too high. chnged from baseline_y-1 to baseline_y-1.5
* increase drawing clip rad of animal #30 small antelope. increased from 2 to 3.
* change loading screen to copyright 2015. made new loadmsg() routine.
* add ability to toggle between world and local maps
* test avian attack ai - not working right?
+ fixed: didnt call set_predator_tgt (weaker prey only) when hunting. it would target strong prey, then flee when close!
+ fixed: didn't call do_animal_attack when attacking! it would dive on a target correctly (the hard part), but not attack when it got there!
+ fixed: avians start their attack too late. doubled avian vs ground target start_attack_range from 30 to 60. makes perfect sense. the new AI attacks at sprint speed, not run speed - IE double the speed it used to. so now it needs to start its attack twice as far away. i love it when the physics works out correctly! now once again, if there are big hungry avian predators around, you'd better do something or you're going to die!
+ fixed: avians now land before resting due to fatigue
+ fixed: set xr (pitch) to zero when standing.
+ fixed: climb/dive vs avian tgt: it was setting desired_altitude to ground level at target's location for all targets, even avains. now it sets desired_altitude for avian targets to the target's altitude.
***** still need to test avian vs avain start_attack_range. in general, start attack range formula may need to get fancier, and take into account speed and direction of attacker and target, not just speed of attacker and range to target. stuff done to fix avian vs avian AI:
* renamed b2_avian_attack() to b2_avian_attack_ground_target(). B2_avain_attack() is tailored for ground attack.
* added b2_avian_attak_avian_target()
* added: b2_avian_match_targets_altitude() for use by avians against avian targets.
* fixed: draw_animal_model: if dead: if in water draw at water level, else draw at ground level.
was backwards: if in_water draw at ground level, else draw at water level. (oops!)
* fixed: didnt start to land to eat carcass until right above it. now: if not at carcass, but within within 50: if flying, lands, else fly a bit (towards carcass). landing starting at 50 put them close, fly a bit (which causes oscillation betwen fly and land, until at carcass) make them "hop up" to the carcass - just like a real bird.
* added instructions to the "create a new character" screen
* demo now starts player in temperate savanna terrain.
* end demo: removed references to atk to subdue and capture.
* tutor: added info about "z" key to pick up dropped objects
* turned off playtest hotkeys in demo
* increased cave hyena hp in demo so they attack player.
* tutor: gives encounter advice right after the normal encounter message - not right before.
* upatree: badguys dont leave! simply have them ignore targets that are up a tree. set_predator_target now ignores band members who are up a tree if the animal type can`t climb trees.
Norman Barrows
While I wait for a build, I thought I'd do a quick update. Its been too long since I posted a progress report.

I've been play testing the game a lot recently. About one game year so far with the same play test character (Grog).

I've gotten perhaps half of the screenshots from that posted.

Play testing revealed no major problems. A few things to tweak and adjust. One I make those changes I'll post a new beta.

One big change is that attack to subdue is out, and "dances with wolves" is in.

Domestication of animals has been totally re-designed to be more realistic.

No longer do you attack to subdue, capture with rope, then tame with meat, for any animal you can catch.

Now, you drop meat, and dire wolves will eat it. Dire wolves have been reduced in hit points to just less than humans, so they won't target humans as prey. And they will flee if apprached too closely. relations with the wolf increase by the quality of the meat dropped. when relations go over 1000, the wolf "adopts" the closest band member at the time, and will begin to follow them around - at a respectable distance. dropping more meat will continue to increase relations with the wolf. when relations go over 2000, the wolf will allow the band member to approach. then the player can select the wolf and get the "dire wolf" menu. just one action: give meat. when the player gives the wolf enough meat to increase relations over 3000, the wolf becomes tamed, and fights at your side just like any other follower.

I'll post a proper update with details, and the rest of the screen shots soon. I'm torn between needing to keep the world abreast of progress on the game, and needing to finish the darn thing!

Back to dancing with wolves!
Norman Barrows
An example of a big change to Caveman

I've been playtesting a lot recently.
Drawing objects in an avatar's hands in animations
is the next thing on the todo list - and that's just
eye candy. I'm into gameplay, not eye candy.
So I've been playtesting my long term playtest game,
making note of fixes to be made. I've gotten to the
point where I have 10 bandmembers in my band!
Occasionally I'll stop and make a change necessary
to continue testing. But that is becoming less
and less frequent. I can test for an entire day
with no changes required to continue testing.
That's a sure sign that the game is getting closer
to completion, when everything is working correctly
and no major issues are encountered while testing
for hours or days on end.

I just finished a change that was really required
for futher testing. Permanent shelters have been
replaced by a new type of object, a PLAYERHUT.
Before the change, each bandmember had to create
or takeover their own hut, and they were limited
to one each. Now, each bandmember can create
or takeover as many huts as they wish, and huts
are owned by the band, not individual bandmembers.
So one bandmember with lots of construction skills
can build huts for all the bandmembers.

A description of the changes involved:

#declare object type
--------------------
defines an ID number for this type of object.

the game tracks items in the world using a
"objrec2", which is an instance of 1 or more
items of a given type and quality at a given location.
lists of objrec2's are used for containers, PC and
NPC inventories, and the world objects list (dropped
inventory items and items built by the player -
such as huts! ).
The game uses a relational database design, with
objrec2's pointing to object type instances in the
object types database, via a object type ID number.
object type instances contain info like name, weight,
and price which are common to all objects of a given
type.

init_object_types_database
--------------------------
inits the object type's entry in the object types
database. IE sets name, weight, price, etc.
not much here, i set the name and radius but the
code uses neither! :O



PLAYERHUT methods:
------------------
build
inspect
repair
demolish
in_way_of_drawing // boolean. dont draw plants etc in huts!
in_way_of_moving // boolean. collision check
add_to_collision_map
// adjusts 3pv camera location to hut interior
get_3pv_camera_coordinates
first_BM_nearby
raid // conducts hostile caveman raid on a player hut


should get_3pv_camera_coordinates be a camera method or a
playerhut method?
it uses both...
continuing along those lines...
should in_way_of_drawing be a render method?
should in_way_of_moving be a physics method?
should add_to_collision_map be a collision map method?
should first_BM_nearby be a bandmember method?

more and more its seems that for loose coupling and tight
cohesion, code ought to be divied up into two types:
1. low level classes that know only about themselves,
and
2. controling code that uses low level classes.

then the controling code would do something like:
loc=bandmember.get_location
loc2=calculate 3pv camera location from loc
playerhut.adjust_3pv_cam_location(&loc2)
camera.set(loc2)
bandmember, playerhut, and camera only know about
themsleves. only locations are passed between them and
the controling code.







world objects list methods:
---------------------------
// checks if a world object is in any player hut
worldobj_in_playerhut
// checks if a bandmember is in any player hut
BM_in_playerhut
remove_stuff_nearby_playerhut



render methods:
---------------
draw_world_objects
draw_local_map
draw_world_map


process_input methods:
----------------------
selected_playerhut // boolean
playerhut_menu // playerhut actions
takeover_abandonded_hut


update methods:
---------------
remove_distant_dropped_objects // dont remove stuff near huts!
model_playerhut_raids // calls playerhut.raid if a raid occurs
model_playerhut_weathering


other methods:
--------------
// boolean. checks if bandmember is near a player owned cave, rockshelter, or hut
BM_near_shelter
// boolean. checks if player owns a cave, rockshelter, or hut
owns_shelter




The actual changes were pretty straightforward.

permanent shelters used:
bandmember.has_perm_shelter
bandmember.perm_shel_quality
bandmember.shel_mx
bandmember.shel_mz
bandmember.shel_x
bandmember.shel_z

and player huts use:
worldobj.active
worldobj.qual
worldobj.mx
worldobj.mz
worldobj.x
worldobj.z

all the code already existed, it just needed to be changed to use
PLAYERHUT world objects instead of a bandmember's permanent shelter.

One prime motivation for this change was the fact that caves,
rockshelters, and NPC huts you can take over now occur at random
locations in a map square (a square 5 miles across). They used to
be at most one of each per map square, and always in the same place.
And if there was water in the map square it was always nearby all
of them - IE everything was near the center of the map square.
Now its much rarer for a cave or hut to be near water and all
rockshelters are more than a mile from the closest water. So
building a hut is the best way to get a shelter close to water,
which is the most frequently required required resource in the
game. And it takes a lot of skills to build a hut. The research
tree is incredibly long and complex. So requiring each bandmember
to go through this to be able to build a hut when their fellow
bandmember(s) already have the skills to do so didn't make sense.
Not sufficiently realistic, needed to be improved. Thus the change.

And now...

I'm off to build huts for all my bandmembers! smile.png

You should see what its like trying to cram all ten of them in one
hut so their mood doesn't go down from being out in the rain! .
Norman Barrows

AI in Caveman

Caveman ai:

ai in caveman has been through three major versions.

the first version was just quick and dirty code to get things going. like
all code of this type, it quickly grew and evolved into an ugly mess.

the second version of the ai was a more traditional setstate/runstate
type affair. setstate selected one of about 14 or so AI states for an
entity, depending on what was going on. runstate was a big switch
statement that executed the code for the various states. one problem
with the traditional setstate/runstate model is that it only has one
state variable. so if you have multiple states at once you must have
different states for each combo.

the third and current version of the AI uses a different approach.

it uses prioritized condition checks to determine what to do. as soon as
a condition is found it should react to, it does so, then returns. no
setstate/runstate. as soon as condition is found, the equivalent setstate
is therby determined and the appropriate runstate code can be immediately
executed.

it also uses multiple AI state variables (mostly booleans) in lieu of a
single AIstate variable as in setstate/runstate. so it has AI state
variables like in_collsion _recovery, in_collsion_avoidance,
taking_missile_fire, orders (goto, attack, follow, etc.), and so on.
this allows an entity to be in multiple states at once such as:
"in_collision_recovery" while moving to attack due to
"taking_missile_fire" while "following" another entity. when they finish
collision recovery, they resume moving to attack. when done attacking,
they resume following the entity. without the need to push and pop states
on and off a state stack. the condition check priorities cause them to
automatically resume a lower priority state once a higher priority
state is no longer in effect.

the prioritized condition checks work as an expert system.
the condition handlers (code) in turn are each mini expert systems in
handling their condition. implementation varies depending on the condition
being handled. most are rule based systems. some are state machines. the
handlers in turn may call even lower level expert systems for tasks such
as selecting best weapon to use, etc.

all told, the game implements about 18 different types of ai depending on
the entity type and whose side they're on. so for example, AI for a pet
dire wolf is different from that for a wild, subdued, or captured dire wolf.
and AI for a traveling companion caveman is different from that of a neutral,
hostile, thief, hired warrior, or band member caveman.

there are four basic types of AI for animals:
1. defend - the animal will stand its ground and defend itself if approached.
2. maintain_distance - the animal will attempt to maintain a safe distance
from all threats. if approached, it will flee.
3. attack - the animal is predator. when hungry it will go hunting, feeding
on nearby carcasses if available, or attacking other animals not bigger than
itself. when not hungry it just hangs out.
4. defend_location - the animal will defend a specific location in the game
world. used by quests where animals guard treasure. if far from the
location, the animal will move to the location. if at the location, it will
attack all who approach.

Avian AI is completely separate from that for ground animals, although it
takes the same form.

All animals include "graze" as one of their possible AI moves. its usually
the last choice - IE when there's nothing more important to do.
"graze" cycles between stand, wander, flock, and migrate states periodically
at random. its an example of a condition handler that uses a state machine.
wander simply moves to a random wander_to point. flock moves towards the leader
(the first animal of a given type appearing in the entities list). in the case
of the leader, flock becomes stand. migrate is only used by the leader. the
leader moves off in a migrate_direction determined by the type of animal (so
they still migrate the same direction even if the leader is killed). if a
leader is killed, the next active animal of that type becomes the new "leader".

note that leader migration behavior in combo with flock behavior leads to emergent herd migration behavior! ; )

model the little stuff right and the big stuff happens on its own! - well at least sometimes - if you do it right.

multiple AI states vs setstate/runstate is another example of this. by tracking _multiple_ states (which setstate/runstate does not do) - IE by modeling state in greater depth than setstate/runstate - you automatically get emergent push-state, pop-state type behavior with no pushing, popping or state stack required.
Norman Barrows
Building a large procedurally genrated world with no load screens:
How caveman 3.0 works.
======================================================================


GAME WORLD DATA STRUCTURES:
=====================================================================


1. the world map
---------------------------------------------------------------------
the world map is stored in a 500x500 array of structs.
each map square is 5 miles across.

terrain chunks and collisions maps are generated from the world map data.

assets are loaded once at program start. asset reuse is maximized.
load times are on the order of 20 seconds or so for EVERYTHING! : )

if required, paging of assets could be implemented.

the map structs hold info about elevation (heightmap used), vegetation
(what plants to draw, what ground texture tile set to use), water
(what water to draw), and miscellaneous terrain features, such as rock
outcroppings, fruit trees, berry bushes, tar pits, etc (more stuff to
draw).

the world map is randomly generated at game start, updated (changes)
once per game day, and is included in a save game.




2. pattern maps:
------------------------------------------------------------------------
so the world map tells us more or less what to draw, but not necessarily
where exactly to draw stuff.

enter "pattern maps".

a pattern map is a 2d array, either a true 2d array, or implemented as
a sparse matrix (a list).

so you have a pattern maps to tell you where to draw trees, rocks, etc.
pattern maps are then repeatedly tiled over a map square to place trees,
etc. The size of a pattern map should be big enough that no moiarre'
patterns are discernible within viewing range. this usually works out to
a size of two times visible range.

multiple pattern maps are used for different things so rocks and trees
for example don't all appear at the same locations.

pattern maps can contain more information that just location, they can
also include things like type information for determining drawing info,
or even render and physics info like scale, bbox dimensions, etc.

ground coverage plants can simply be draw every x number of feet with
type based on "location mod ".

caveman uses 5 pattern maps: one for trees, one for rocks, one for berry
bushes, one for fruit trees, and a generic pattern map for tall grass,
canyon heightmaps, and a few other things.

pattern maps are randomly generated at game start, and are included
in a save game.





3. The CRH list:
----------------------------------------------------------------------
the CRH list is a list of all the caves, rock shelters, and huts in the
game (IE all buildings in essence). an index is used to speed searches.
the index is a 2d array the size of the world map. for each map square,
the index holds a list of the CRH's in that map square
(IE their indexes in the CRH list).
the CRH list is randomly generated at game start, is updated once per
game day, and is included in a save game.






4. The world objects list:
-----------------------------------------------------------------------
this is a list of all the immobile objects the player has built in the
game world such as shelters, huts, landmarks, traps, bedding, etc.
it also includes all inventory objects the player has dropped. dropped
objects are only persistent inside player owned CRH's, otherwise they
are removed from the simulation when the player is no longer nearby.
so its ok to store them here without running out of room.






TERRAIN CHUNK GENERATION:
=======================================================================
when it comes time to render, the game determines the terrain chunks
in visible range, and draws each one. if a chunk is not in the cache
its generated on the fly. chunks are also generated in the background.

a terrain chunk is basically a pre-generated render queue list of all
the meshes in the chunk to be drawn, ready for sort on distance
(if desired), frustum cull and rendering.

a chunk is generated by clearing the cache slot, then adding meshes, then
setting the slot to active for use by the renderer.


the coverage and miscellaneous terrain features in a map square
determines what to draw, and the pattern maps are used to place items
such as trees, rocks, and plants.

the world map, pattern map, and world objects list determine the meshes
added to the chunk. once the meshes are added, the chunk is marked as
active for use by the renderer.

the optimal size for a chunk appears to be whatever visual range is.




ground mesh generation:
-----------------------------------------------------------------------
ground meshes are generated as follows:
pre-allocated static buffers are used.
the ground is composed of four interleaved meshes, one for each of the
four texture tiles used. a pattern map determines the texture used
by a quad. all quads using a texture are heightmapped and added to the
static buffers (VB and IB) for that mesh. the four meshes draw together
form one continuous ground mesh with tiled textures that still follows
the game's mantra of "one texture per mesh" for speed.

the elevation in a map square determines the heightmap used by the
ground meshes. elevations can vary from map square to map sqaure.
a "heightmap seam fixer" is used at map square edges. the ground
texture pattern map determines which texture a ground quad uses.







collision maps:
------------------------------------------------------------------------------
collision maps are generated on the fly, in a manner similar to terrain chunks,
and stored in a collision map cache.
the maps are 2d arrays of ints, with different values indicating different types
of obstacles: 0=none 1=rock 2=tree, etc.
collision maps are the same size as terrain chunks.
when a collision check is made, the location is translated to a collision map
and coordinates in the map. if the map indicates something there, true is returned
for the collision check.
if a collision map is not in the cache, its generated on the fly.
a maps is generated by clearing it, then adding trees, rocks, buildings, etc.
as specified by the world map, pattern maps, and world objects list. collision map
generation is faster than terrain chunk generation because it only sets a few ints
instead of adding a drawinfo struct to a database with a 2d index. so background
generation is unnecessary.





overall results:
--------------------------------------------------------------------------------------
as the player moves across the world, terrain chunks and collision maps are generated
as needed. right now there is a slight delay when a large number terrain chunks must be
generated in the foreground on the fly, but its too short to even display a
"generating area..." message. as i fine tune the background chunk generation to run
faster with more passes of less stuff per pass, and increase terrain chunk cache size,
and perhaps increase the background generator's look ahead range, i hope to eliminate
the slight delay entirely.

this approach gives you a procedurally generated random persistent modifiable game world
with no load screens.
Norman Barrows
Caveman 3.0 Beta 18 released!

HEURISTIC COLLISION AVOIDANCE, BACKGROUND TERRAIN CHUNK GENERATION, SOUND DETECTION STEALTH MODELING,
UNLIMITED SAVE GAMES.

Play now!
http://rocklandsoftware.net/beta.php

Game homepage:
http://rocklandsoftware.net/Caveman.php



New for Beta 18:
___________________________________________


* added heuristic collision avoidance to AI
* added background terrain chunk generation.
* added sound detection modeling to stealth modeling. chance of detection based on whether you're moving, terrain type, and stealth skill experience points.
* game now plays combat music when player is hunting non-hostile animals: IE when wpn drawn and wild animal within 40 feet.
* added "select file" screen for loading games.
* added automatic save game file name generation. this along with "select file" for loading allows for practically unlimited saves of a game
(up to 4.2 billion or so per save name, or the limits of disk space).
* added drumroll sfx to important messages: succes or failure on make or repair or learn. kill with hand or missile wpn, all encounters, taking damage, death, getting sick, recover from illness, all damage heals, etc.
Norman Barrows
SLIDING COLLISIONS, BETTER GRAPHICS, BETTER COLLISIONS

Caveman 3.0 Beta 17 released!

Play Now!
http://rocklandsoftware.net/beta.php

Game Homepage:
http://rocklandsoftware.net/Caveman.php

Rockland Website:
http://rocklandsoftware.net/Home.php





Latest update: Beta 17, Jan 16th 2015 (88 Meg)



New for Beta 17:
_____________________________________________


SLIDING COLLISIONS
BETTER SAVANNA GRASS GRAPHICS
BETTER ROCK COLLISIONS
BETTER HUT COLLISIONS
SINGLE ENCOUNTER CHECK PER PARTY


* turned off f9-f12 in fps input. anytime input already does them.
* improved graphics: made savanna grass spacing and x,y,z scales data driven. adjusted savanna grass spacing and scales.
* fixed: collision maps didn't "hollow out" huts and perm shelters
* more accurate collision checking vs huts & perm shelters. if collision map says its a collision,
it then checks using the older more accurate method (true 2d distance from hut) to determine if collision occurred.
* changed draw, collision map, and action area for rocks so they all match up nicely.
* bm2 gets animal encounters when near bm1. it should only check for bm1, and skip bm2. or in general: check for bm "lowest" and skip all bm "highers". fixed: off by one error in encounters_already_checked(). it looped over 0 thru Bm-2 not 0 thru Bm-1.
* move following bm's: don't move if they're doing an action.
* make ani: draw them higher off the ground.
* make it so you slide off obstacles, instead of stopping.
* added slide on collision to collisions with band members, animals, steep rises, cave walls, and cavern walls, as well as terrain obstacles.
Norman Barrows
Caveman 3 Beta 16 released!

Play now!
http://rocklandsoftware.net/beta.php

Game homepage
http://rocklandsoftware.net/Caveman.php


New for beta 16:

* fixed: rock collisions not working, and "select" only selects rocks in terrain with rocks.
rocks bounding box radius used by "select" and "collision map" was not the same as that used by "terrain chunks".
this was a result of the change to calc_rock_BBox made in beta 14.
This did not turn up immediately in testing, or it would have been fixed before beta 14 was released.
* fixed: local map: action areas for "center on player" and "center on quest" buttons were off.
* the game now shows a message when there are hostiles nearby and you try to accelerate time > 128 times normal speed.
* doubled y scaling used for (IE: thickness of) stone knife mesh.
* added nobutton after "center on player" and "center on quest" in local map.
* added alt-tab support to modeler.
* cut size of stone object in half
* cut size of wood object in half
* the game now draws objects in hand during action animations for (action - item in hand):
find stone - 2 hand hammer (large chunk of stone)
find one hand hammer - 1 hand hammer
find two hand hammer - 2 hand hammer
find flint - flint
find cool rock - cool rock
find throwing rock - throwing rock
make stone knife - one hand hammer
butcher action - stone knife
make raincatch - stone knife
find wood - wood
find herbs - herbs
make waterskin - stone knife
find spices - spices
find nuts - nuts
find grain - handful of grain
find veggies - digging stick
find fire sticks - wood
make boiling bag - stone knife
find boiling stone - two hand hammer (large chunk of stone)
find grinding slab - two hand hammer (large chunk of stone)
find grinding stone - two hand hammer (large chunk of stone)
make flint knife - one hand hammer
make torch - stone knife
Norman Barrows
So the next thing is to make the game draw animations when a band member is performing an action such as making a spear, starting a fire, gathering wood, practicing with a flint throwing hatchet, etc.

So for every action - and there are over 100 TYPES of actions - there will be an animation, and an animation object in hand, and zero or more animation objects on the ground.

And some actions such as cook, make, gather, repair, etc will use different objects in hand and on the ground, depending on whats being made, gathered, repaired, etc.

And the Learn action will required animations and objects in hand and on the ground for each skill in the game (about 50).

so every object (about 300) will have a make or find animation along with an animation object in hand and animation objects on the ground list. every object will also have drawing information, and a fixup translation and rotations for placing it in an avatar's hand. the fixup for each object will need to be determined experimentally in the modeler. the fixup locates the object with respect to the avatar's "weapon bone". its required because the size of an object at its "grip point" and its required orientation can vary.

and every action (about 100 types) will have an animation along with an animation object in hand and animation objects on the ground list - or use those for an object or skill.

and every skill (about 50) will have a learn animation along with an animation object in hand and animation objects on the ground list.



All the basic animations are in the game and hooked up for all actions. But actions that work with different objects (make, cook, etc), and learn, which works with different skills, all use the same animation for the moment.

i hope to make maximum effect of asset reuse. but the first thing i tried was drawing reeds in hand when gathering reeds, only to discover that i need a new asset (handful of reeds) because the best existing one (bundle of reeds) simply didn't look right. I decided to do that one later . My second attempt with the makefire action fared little better, as it will require its own custom animation - or two if i decide to actually show a fire bow when they use one.

so this item on the todo list is going to take a LONG time. its pretty much the last major thing left to do on the game project.


beyond that i'm down to adding better graphics, more actions, skills, and objects that were thought of late in the project, more animal types (i have no modern animals or sea creatures yet), and high level things like mini-games. Other nice things like a target browser.

so mostly nice features, add-ons, eye candy, and gold plating, but nothing that must absolutely ship in the first release.

which means, once i get the animations done and finish play testing and polishing, it should be ready to go! finally!
Norman Barrows
Try it now!
http://rocklandsoftware.net/beta.php

Game homepage:
http://rocklandsoftware.net/Caveman.php

New for beta 15:
Minor fixes
AI priorities reorganized a bit - resting moved to a lower priority, to go with the new full fatigue modeling
Added death by food poisoning
Automatic screen dump file names

Details:
* increased collision radius of Gigantopithicus.
* only says "Bagaba" (essentially Caveman speak for "Ok" ) if its the current band member starting an action.
* local map: + and - dont do anything! - removed. unlike the world map, the local map doesn't zoom (yet at least).
*add klik sfx to draw / sheath wpn key
* add klik to run walk
* add klik to continuous move, crouch, and climb, and toggle view.
* animal cliprng > chunk cliprng! set default for all clip ranges to 300 ft.
* fixed: bedding that used to be in a shelter that subsequently weathered away: can't rest or rest and heal, says "lean-to wore out". bedding_menu() was passing the shelter's ID instead of the bedding's ID to wearout_world_object().
* bm follow me: they flee if wounded (when badguys nearby). BMAI reorganized into two types: badguys_nearby, and no_badguys_nearby. changed AI priorities: "follow orders" before "flee if half dead", etc. now it only tests for and reacts to conditions appropriate for badguys or no badguys nearby. b2_bm_do_common_ai was inlined into the beginning of b2_run_BM() before b2_run_BM() was split into badguys nearby, and
no badguys nearby.
* fixed: give to BM: add ctrl clik and shift click to prompt. made sure prompts were correct for all calls to shift_select_object(). "give to band"
prompts were also fixed. "give BM" and "give to band" were recently improved by switching from select_object() to shift_select_object(),
which added shift-click to select up to 10 of a type and quality, and ctrl-click to select all of a type, any quality. but the prompts were not
updated to reflect the new capabilities. the prompts are now correct.
* add nobutton (wait for mouse button release) after teleport in world and local maps.
* pass out, lack of sleep, while moving x-country: need to adj_bm_loc before sleeping. when pass out, if moving, calls stop_moving(cm1). this adjusts BM location, and moves CM1's followers and any other bandmembers following cm1.
* klik on esc from local map
* eat spoiled food, do 1dp as well as make sick. adds a new way to die! food poisoning!
* increased collision radius of elasmotherium.
* fixed: x-country move: should be walk speed. added walk_movement_rate() and increase_walk_fatigue() for use by x-country movement.
* stream: make action area a bit wider: changed from 15 ft to 18 ft rad from center line.
* creek: make action area a bit narrower: changed from 10 ft to 8 ft rad from center line.
* remove_non_hostiles_over_time: removes too quickly. reduced from 10% to 1% chance per minute.
*move x-country: adj_bm_loc and move followers before rest action. now calls stop_moving if moving.
* regen terrain chunk when make or destroy or weather away store pit, or any other world obj.
removed redundant bedding_in_way check from generate_chunk() - bedding already handled by storepit_in_way.
added init_chunks to:
bedding: add, wearout, demolish
huts: come, go
storepit: make, weather, abandon
tmp shelter: add, demolish, weather
abandoned hut: add, bm takeover, weather away.
perm shelter: build, demolish, weather away, abandon and build new one, abandon and takeover existing abandoned one.
* clear_CM_cache when init_chunks. added call to clear collision maps when it inits (clears) terrain chunks when the terrain changes due to
player or npc strutcures coming and going.
* fixed: sneak hand attak doesn't trigger detection. a sneak hand attack hit that doesn't kill now sets sneak state to "detected by hostiles".
*flock: they crowd around the leader so tightly he/she can't move. now stops at 40, not 30 feet.
* animal AI - resting when under attack? common_flee_AI had rest as highest priority, moved it to lowest priority
* added automatic screen dump file names.
* increased minimum encounter range to 75 feet (affected mountains, woods and jungle).
* increased encounter ranges. min is now 100. large herds of big game were still rather close in dense terrain. may need to make encounter
range the range to closest encountered, not range to center of group. disburse the group away from player starting at the encounter point,
instead of disbursing them around the encounter point.
* added draw_obj_in_hand to draw_bandmember when current_action!=DONTHING. temporarily disabled in the demo until assets are
created for and assigned to all actions.
* fixed the height an avatar is drawn at when playing pray, sacrifice, and prayfire animations.
* fixed: caveman encounter messages used name of cm0 - the current band member - the one the human player is currently controlling, not the band member having the encounter.
* cut spacing between animals at time of encounter from 3x to 2.5x animal.rad
* only shows the "you're so fatigued you have to stop and rest" msg if its the current band member.
* added: footstep sfx when moving cross country
* caverns: now does new style caveman encounters (no talk / attack / ignore menu anymore).
Norman Barrows
How can i kill thee? let me count the ways...

There are lots of ways to die in Caveman. For a long time, I've been wanting to post a list, but have never gotten around to it until now. I've been play testing the past few days. Now I'm implementing the changes that play testing uncovered. Then I'll post beta 15. One change is taking 1 dp as well as getting sick from eating raw or spoiled food. But if you take damage, you can die! So now there's yet another way to die in Caveman! . This got me to wondering just how many ways you could die now in Caveman, so I searched the code, and made a list:

Ways to die in Caveman:
--------------------------------------------
1. killed by hostile caveman
2. killed by wild animal
3. swept away by flood waters and drown
4. food poisoning - NEW! before was only indirectly through death by illness (caused by food poisoning).
5. drug overdose
6. dehydration
7. illness
8. exposure to cold
9. heatstroke
10. starvation
11. volcano
12. earthquake
13. comet strike
14. meteor shower
15. hailstorm
16. wildfire
17. fall from tree while climbing up or down
18. falling to your death (fall off cliff, etc)
19. background radiation (old age)
20. drown while swimming

did I forget any? .
Norman Barrows
Caveman 3.0 Beta 14 released!

This is a late announcement. Beta 14 was actually released Dec 26th, 2014.

download:

http://rocklandsoftware.net/beta.php


game homepage:

http://rocklandsoftware.net/Caveman.php


new for beta 14:

* only plays combat sounds if source is within 75ft of player

* new action: abandon object: as drop, but removes object from sim.

* clears collision map cache when perm or temp shelter weathers away.

* enter shelter ani - draws higher off the ground.

* random music - adjust for gamespeed as to how often it plays. right now at high gamespeed it plays more frequently.
1 in 800 at 15 fps < 1 in 800 at 15 fps at 128x speed!
added bigdice()routine, goes up to dice(327,670,000) made music play if dice(100M) < 20000/turns_per_render

* don't let BM enter occupied shelter

* view inventory - alphabetize and sort on quality

* Fixed: bboxes for rocks are not correct. it now takes the rock mesh, and for each vertex, scales it and rotates it,
then checks it against the current bbox size (init'ed to zero), increasing the bbox as needed. so all verticies are scaled and rotated,
and the min and max x,y,z's of the results are the bbox corners.

* select item to trade: use shift select (shift-click for select 10, ctrl-click for select all).

* select item to trade: set select_object_offset to zero the first time, so the list is not scrolled down when they first enter the
select item screen.

* click sfx for all mouse clicks and key presses

* tab between bm's: takes a long time to generate chunks. increase size of chunk cache? cache increased from 30 to 60 chunks.
helps some, but they're travelling cross country, so you're always generating new chunks, so you still run out of chunks, no matter what.
forgot to add more ground meshes to go with more chunks, took a while to track that bug down.

* nokey in world and local map after spacebar press, etc, so klik doesnt play a million times.

* add klik to keypresses in process input

* shift select, world map, local map, etc - add destroy_finished_voices

* gt kangas attacked Buh-ah! wrong ai? defend ai range too big? defend AI rng cut from 50 to 30 feet.

* added nokey to end of wpn hotkeys - waits for key release, instead of clicking repeatedly.

* avians flying awfully low - switch away from wander, flock, etc, too fast? increased alt to 20 ft from 10.
increased max wander time. increased max wander range from leader. reduced chance to stop wandering at random.
reduced flock stop rng to 20 ft. added leader migrate to graze.

* learn rope making, should wear out best nearby anvil stone, not first nearby anvil stone.
added best_nearby() function: returns world object index of the highest quality object of a given type within 20 feet
of a given band member. wearout_nearby() now uses best_nearby() instead of doing a sequential search to find first nearby.

* make maintain distance and other non aggressive AI's flee when taking missile fire instead of attacking.

* cross country travel - navigation experience now has small chance to go up each minute you're in cross country travel mode,
instead of going up when you successfully arrive at your destination.

* cross country travel on rafts - navigation experience now has small chance to go up each minute you're in cross country travel
on board a raft mode, instead of going up when you successfully arrive at your destination.

* updated text on superfast screen (1-6 for gamespeed, x to stop action).

* action mode: use 1-9 for game speed. action mode and super fast screen text updated too.

* make it say "bah-gah-bah" when you start an action

* reduce chunk size to reduce chunk gen time? tested 100, 200, 300, and 400. 100 needs bigger cache, 200: no noticeable difference, 400 was slow. set it back to 300. perhaps as as big as you can generate/stream/load in a reasonable amount of time is the best terrain chunk size?

* fixed: max_ground_quads_per_chunk was set to chunksize, not (chunksize/quadsize) squared.

* in game menu: music on/off: need nobutton. added.
Norman Barrows
Caveman 3.0 beta 13 released!

[color=rgb(40,40,40)][font=arial]PLAY NOW![/font][/color]
http://rocklandsoftware.net/beta.php

[color=rgb(40,40,40)][font=arial]Game info:[/font][/color]
http://rocklandsoftware.net/Caveman.php
[color=rgb(0,0,0)][font=Verdana]


New for beta 13:

[/font][/color][color=rgb(0,0,0)][font=Verdana]


___________________________________________

[/font][/color][color=rgb(0,0,0)][font=Verdana]


[font=inherit][size=1]

[/font][/font][/color][color=rgb(0,0,0)][font=Verdana]



* abandon current hut and take over this one: they will lose all dropped objects at the old hut!
when hut is abandoned, instead of asking player if they want to abandon their old hut and take this one over,
create an abandoned hut world object that weathers away over time.
player can take it over at any time.
abandoned hut actions: takeover, inspect, demolish.
added abandoned_hut object, and takeover, inspect, and demolish actions for abandoned_huts
* remove non-hostiles over time when game speed > 128x
* increased volume of smallherd_takehit.wav
* fixed defend ai: now only attacks if tgt is within 50.
* tutor: automatically stops cross country movement when the player first finds water, food, and rocks.
* audio: fixed: didn't check for voice ptr=0 in voice is playing
* doesn't switch to action ani fast enough? was calling startani with params reversed!
* fixed: cave hyena attak sfx is lame
* fixed: by coding convention, all startani and setani routines now use model,ani as the parameter order.
all calls to start or set anis changed to use model,ani parameter order throughout the code, including the Zlib.
* fixed: thief dialog not triggering. was going into "comon ai: target is near: fight or flight" first. and approaching thieves are friendly
cavemen who don't attack band members. so it would run up to the player to attack, but not attack them, and never trigger the
dialog. common ai has been modified so thieves whose target is cm0 dont go into fight or flight, giving them a chance to trigger
the dialog.
* improved modeling of full fatigue for band members, cavemen, and animals: movement rate changed from zero to 1/2 walking speed.
attacks changed from not allowed to allowed with 1/2 damage and a minimum of 1 dp. jump changed to initial vertical velocity cut in
half.
* fixed: band member y not set when moving following band members in cross country movement. adjust_bandmember_location only set
band member y if it actually adjusted location due to collision with terrain or other entity. now it always sets band member y after first
making any necessary adjustments to location.
* select_object and shift_select_object now sort on name AND quality
* random_music plays song #0 (intro music) less often
* savanna grass size cut by 1/3. height cut by 1/2.
* input split into fps mode, action mode, and anytime mode. anytime mode input now available during action mode.
* improved camera angle for action mode animations
* band member AI: follow band member: now stops at range 10, not 20.
* game plays random grunt sfx more often
* increased find time for reeds
* increased find time for flint
* fixed: not always starting animal anis correctly when adding new animals to the simulation.
* fixed: not setting action anis for BMs other than current BM.
* fixed: lockup in bandmember_in_way_of_bandmember when BM #2 crossed into next map sq from BM #1. replaced iterator with good old
fashioned for loop. works fine now. unsure what was wrong with original code. but new code should be bullet-proof.
* fixed: move action not set ani correctly. set_action_ani was using male walk ani for both sexes. move action was using female walk ani
for females. made females switch anis all the time. set_action_ani now used both male and female walk anis. call to set ani in move()
procedure turned off. action anis are now set just before draw if needed.
* fixed: animal attacking interrupts bm leaving shelter. make BMAI automatically leave shelter if needed with no action required.
* animal AI: dont stop to rest if attacking or fleeing. make rest a lower priority action. rest moved from highest to lowest priority
common AI action.
* fixed: friendly cavemen following their leader, they dont stop! was using rng to wander point, not rng to leader for stopping.
* game automatically sheaths BM's wpn when they start an action
* change ani cam view to looking at BM from their right
* better savanna grass (changed scale AGAIN! now at 1.0 1.0 1.0)
* changed stop action to "X" key. now ESC works during action mode to pull up the ingame menu.
* default learn ani set to find.ani for now.
* option to turn off music so player can play their own via winamp etc.
* sleep action ani: draw them higher off the ground

[/font][/color]
please send feedback to rockland@rocklandsoftware.net
Norman Barrows
Caveman 3.0 Beta 12 released!

PLAY NOW!
http://rocklandsoftware.net/beta.php

Game info:
http://rocklandsoftware.net/Caveman.php


New for beta 12:
---------------------------------------------
* refactored and improved AI
* give orders to party members
* sound effects
* music
* animations for actions

details:
* following band members now keep up during cross country movement.
* band member AI uses best weapon
* band member AI leaves temp shelter on hostile encounter
* band member AI: stops action if animals nearby. animal must now be within 50, not 100. warriors, companions, tamed, subdued, captured, and non attack_AI animals are now excluded.
* game now checks for encounters once per party, not once per BM. doesn't check encounters for BMs who are within 300 of a BM who has already had their encounters checked.
* fixed: don't let 2 bm's butcher same animal!
* band member AI: attack orders: doesn't attack wounded fleeing thief? cant catch - target too fast?
fixed: was comparing target run speed vs BM walk speed for "skip if target is to fast to catch"
* new AI and orders menu design
* new bandmember AI done
* new orders menu done
* compiles with no warnings with all warnings turned on. fixed a half dozen non-explicit conversions, made them explicit.
* compiles with no warnings in static code analysis. fixed a few potential range check errors, and a couple of possibly uninitialized variables.
* made new band member AI use sprint speed
* made new band member AI play correct animations
* animal and avian AI done
* model animal fatigue
* model animal (flunkey) sneak detection
* set "animal taking fire variables" in check_missile_collision code
* avian version of do_orders
* new avian AI
* load and save animal[a].diving
* collision maps
* ambient sfx
* water sfx
* fire sfx
* BM atttack sfx
* play action animations w/ ani camera view
* finished animal attack sfx
* npc attack sfx
* bm take non-missile hit sfx
* npc take non-missile hit sfx
* code for animal take non-missile hit sfx
* takehit sfx for all animals
* random grunts - caveman ambient audio
* missile hitting tgt sfx
* code to play action sfx
* assign sfx's to all actions
* assign make/repair sfx's to all object types
* get/find sfx for all object types
* sfx when learn skills that use male/female voice (singing and talking type skills)
* ocean sfx when near ocean
* action anis
* stop all wavs when quit game.
* don't let player tab to dead BM
* music
* all audio working
* no random sfx at high game speeds - runs out of voices
* destroy_finished voices added to run_song, stop_all_wavs, and play_ambient_audio
* music starts at title screen now - not main menu
* when possible, uses sfx/wav # != -1, not Zvoice_is_playing to determine if a wav is playing
* use shift select for give bm item
* band member menu: show bm name and relations
* abandon current hut and take over this one: i suspect they will lose all their stuff at the old hut!
when hut is abandoned, instead of asking player if they want to abandon their old hut and take this one over,
create an abandoned hut world object that weathers away over time.
player can take it over at any time.
abandoned hut actions: takeover, inspect, demolish.
added abandoned_hut object, and inspect and demolish actions for abandoned_huts
* remove non-hostiles over time when gamespeed > 128x
* increased volume of smallherd_takehit.wav
* fixed defend ai: now only attacks if tgt is within 50.
* tutor: automatically stops cross country movement when the player first finds water, food, and rocks.
* audio: fixed: didnt check for voice ptr=0 in voice is playing
* doesn't switch to action ani fast enough? was calling startani with params reversed!
* fixed: cave hyena attak sfx is lame
Norman Barrows
The building of Caveman - part 6 - data structures

When i first got into programming as my major, my biggest fear was that I'd end up as a database programmer.
Turns out I became a gamedev. But i still have to do database programming. Sure, games are interactive
multimedia entertainment simulations, but underneath all that is - you guessed it - relational databases!
It turns out that a complex game can have a rather complex relational database system behind it.

Terminology:
database or list: a static array of structs, usually a one dimensional array.
record: a struct in an array
field: a variable in a struct.

In the game, most databases and lists are implemented as static arrays of structs. structs are referenced
via their array index. Maximum sizes required are known ahead of time, which allows the use of fast simple
static data structures. Many of the databases are relational, with some field (variable) in a record
(struct) being the array index of some other record (struct) in some other database (array of structs).
Some of the databases are nested, with one field in a record being an entire list. IE a variable in a
struct might be a whole array of structs. For example, each band member struct has a member varable which
is a list of active traps, implemented as an array of structs.

These are the data structures used by the game:

Asset databases:
First off, the generic databases for assets:
1. meshes - a VB and IB, numtris, and numverts.
2. textures - a d3d texture of some type
3. models - models simply refer to meshes and textures.
4. animations - a list of keyframes with limb orientations
5. animation players - a playback counter, plus model and animation references.
Caveman follows a mantra of one texture per mesh for speed. Models are made up of multiple meshes. An
entry in the models database references meshes in the mesh database, and textures in the texture database.
An entry in the animation players database references a model from the models database, and an animation
from the animations database. All asset databases are part of the generic Z game library used by Caveman.


Type databases:
1. actions - prerequisites, time required, chance of success, etc. prerequisites can include references to
skills and object types.
2. skills - prerequisites to learn, time required to learn, chance of learning success, etc. prerequisites
can include references to skills and object types.
3. object types - prerequisites to craft, weight, damage, cost, time to craft, chance to craft, etc.
prerequisites can include references to skills and object types.
4. animal types - hit points, turn rate, speed, etc. IE non-variable stats. animal types include a reference
to the models database, and references to the animations database.






single instance lists:
1. active bandmembers - an entity list for PCs. the player can tab between PCs at any time. Other PCs are
controlled by AI. each active bandmember has an inventory list, a list of active traps, a list of active
quests, and a list of active intoxicants. a bandmeber record has references to the following databases:
models (for body), meshes (for face and hair), textures (for skintone), and animations.
2. active animals - all NPC cavamen and animals (every non-PC entity). animals which are of type 2
(homo sapien) refer to an entry in the NPCs database where additional NPC specific data is stored.
animal records also refer to the animal types database, and the bandmembers list (for owners of pets).
3. active missiles - arrows, throwing rocks, etc. Smoke from fires may be implemented as a type of missile.
missile records refer to either the bandmember list or the active animals list (for owner), and also
refers to the object types database.
4. world objects - temporary shelters, storage pits, rafts, landmarks, dropped objects, etc. Basically
anything man-made except for huts. structs in this array reference the object types database.
5. active storage pits - a list of storage pits created by the player. refers to the world objects database
(a storage pit is a world object). includes an inventory list for each pit.
6. active rafts list - a list of active rafts. references the world objects database (a raft is a world
object).
7. NPCs - non bandmember cavemen. contains info on NPCs encountered by the player. references the
model, mesh, and texture databases. includes an inventory list for each NPC. NPCs at a CRH reference the
CRH list.
8. CRHs (caves, rockshelters, and huts) - a list of all the caves, rockshelters, and huts in the game -
83,000 of them! each entry has an inventory list (paged from disk). CRHs occupied by animals refer to
the animal types database. There is also a player's version of the CRH list, that only contains info
about CRHs the player has discovered.
9. player cave list - a list of those CRHs controlled by the player. references the CRH list. basically
an index of player controlled CRHs for use with the CRH database.



single instance matrixes (2d arrays of ints):
1. numconvos - tracks the number of conversations this day between band members and NPCs
2. relations - tracks relations amongst bandmembers, and between bandmembers and NPCs.



multiple instance lists:
1. inventory lists - list of objects carried, stored, or for trade. entires in the list refer to the
object types database. each bandmember, storage pit, NPC, and cave/rockshelter/hut occupied by
friendlies has an inventory list as one variable in their struct declarations.
2. Trap lists - a list of the status of active traps set by a band member. refers to the world objects
list (the trap is a world object). each band memeber record includes a trap list field (variable).
3. Active quest lists - a list of active quests. references the animal types database. each band member
struct has an active quest list.
4. Active intoxicants lists - a list of intoxicants currently affecting a band member. references the
object types database. each bandmember struct has an active intoxicants list.



handy structs used in the game:
i find that sometimes its handy to have a sturct to pass info around.
1. location - the world map is a 500x500 grid of map squares. each map square is 5 miles across.
a location is specifed by its map square indices (mx,mz) and by its d3d location in that map
square (x,y,z). a scale of 1 d3d unit = 1 foot is used. a location struct is a handy way to store
both the map sqaure and location of an object.
2. requirementsrec - a list of parts, tools, and skills required to do something. used by skills,
object types, and actions.
3. Zdrawinfo - all the info to draw a mesh, static model, animated model, 2d billboard, or 3d billboard.
used everyhwere to pass drawing info around.
4. objectrec2 - an inventory list entry: active, object type, quantity, quality, location. Used for
inventory and world object lists.





world map data structures:
1. the world map - a 2d array of structs. the world map is 500x500 map squares in size. a map square is
5 miles across. a location is specified by its map sqaure indices (mx,mz), and its d3d location in the
map square (x,y,z). a scale of 1 d3d unit = 1 foot is used. a maps sqaure struct contains info for
elevation, vegetation coverage, water, resources, etc. there is also a player's version of the world map
that only contians data for explored areas.
2. the local map - basically a 2d array of ints, used as booleans, explored/unexplored. This is used as
a "bitmap mask" to cover over unexplored sections of a map square when viewing the local map.
3. cavern maps - a 2d array of ints. values indicate walls, open space, encouter points, exits, etc.
4. plant maps - i needed a way to tell it where to draw plants, rocks, trees, etc. generating a bunch of
level maps was out of the question - too big for memory. what i came up with was what i call a "pattern
map". its a sparse matrix list of objects (trees, rocks, plants, etc). when drawing the scene, this
pattern map is tiled across the ground. Maps are large enough that no repetition is within visible range.
the game uses 4 such pattern maps - each one different - to place rocks, trees, berry bushes, etc.
4. wood grass map - another pattern map, for undergrowth in woods.
5. ground texture map - a 2d array of ints. caveman uses ground texture tile sets of 4 textures each. the
ground texture map contains random values 0 through 3, indicating which tile in the set to use for
texturing a ground quad. Agian, this "pattern map" is large enough so repetition is not within visible
range.
6. generic pattern map - as development progressed, i found myself needing a pattern map from time to time.
so i decided to create a generic one that i could write functions for that would return whatever i needed.
the geneic pattern map is a 100x100 array of random ints 0 through 100. functions are then written to
return values as needed. example: return the scale of a plant at x,z: map x,z to 0-99,0-99, and return
some permutation of the value in the generic pattern map at that location. Uses of the generic pattern
map include control of model, texture, scale, rotation, and offset of tall grass plants, and as the
basis for a double interpolated height map for canyons.




terrain chunks:
originally, the game drew the scene by brute force, drawing the ground one quad at a time, or with a dynamic
buffer, and iterating thorough the various pattern maps drawing tress and rocks etc, all the while checking
for collisions with man made objects (dont draw plants inside a hut!). Scene composition simply took too
long this way. So i stared at the lowest level and let that define how the code should work and how the
data should be organized. basically, what directx wants is an ordered list of renderables, sorted on
texture, then mesh, then near to far (for non-alpha). instead of generating the list of renderables each
frame, i decided to divide the terrain into chunks 300x300 d3d units (feet) in size. a chunk consists of
an unordered list of all renderables in the 300x300 area (in zdrawinfo structs), and a 3D index: a list of
textures, and for each texture, a list of meshes, and for each mesh, a list of instances which are indexes
into the list of renderables for the chunk. chuncks are genrated as needed and then stored in a cache with
LRU discard. to draw a chunk, the index is used to traverse the list of renderables in correct drawing order.
for each renderable, a frustum cull check is preformed, and if it passes, its added to the render queue.





the render queue:
the 3d indexed renerables list from chunks worked out so well that i redesigned the render queue in the Z
game library to use a 3d index. originally it was a simple list that got sorted just before drawing. Now,
as a renderable is added to the queue, its also added to the 3d index, in what is essentially a bucket
sort type of thing.




And that's pretty much it for the data structures. If i had to do it all over gain, i'd use more of a
composition type approach, and give animals and bandmebers a location struct for example. that way i
could write one piece of code to work with a location instead of one to work with bandmembers and one
for animals. As i go along, i try to do this with new code i write.

Note that almost everything is stored in ram. local maps use a cache and are paged to and from disk as
needed. Cavern maps are generated as needed, saved when you leave a cavern, and loaded when you
re-enter a cavern.


Part 5:
https://www.gamedev.net/blog/1730/entry-2260302-the-building-of-caveman-part-5-general-code-organization/
Norman Barrows
The building of Caveman - Part 5 - General code organization


This is the general code organization used in Caveman:


void main:
----------------
initprog
runprog
endprog





initprog
------------------
init z3d game library - creates window, goes into 3d mode, creates fonts, inits audio, random number generator, timers, etc.
rockland animation - show company logo animation
load all assests - show loading screen. load: meshes, textures, models, animations, wavs, etc.
show title screen



runprog
-------------------
show main menu:
continue - load last saved game, rungame.
tutorial - init tutorial game, rungame.
new game - init new game, rungame.
load game - load saved game, rungame.
help - show help
tools - show modding tools menu
quit - quit caveman


endprog
-------------------------
unload all assets
shutdown d3d, audio, etc




Rungame is the main game loop, the real guts of the game. The game uses a fixed time step. The framerate is limited
to 15 FPS. Testing has shown this is the slowest a game can run and still be sufficiently responsive. The game has
accelerated time, so render is called one or fewer times per turn (update frame), depending on game speed. Caveman is
a hybrid game that combines FPS/RPG play with with the ability to interact with the environment, as seen in The SIMs.
The are hundreds of possible actions, from drinking water to making a stone knife. When the player is perfoming an
action, they can't move or fight, and must wait for the action to complete. Action specific handler code is called
each turn (update frame). When they are not performing an action, they can run around like in any normal FPS/RPG.

rungame
--------------------------while !quit { if ((turn_counter % turns_per_render)==0) drawscreen // render if (player_doing_action) do_action else process_input increment_game_clock run_simulation // update limit_framerate }
do_action
-----------------------------
runs the action handler code for the current action.
action handler code typically increments a counter, and after some limit is reached, performs a success check,
updates the simuation as needed, and ends the action. While performing an action, input is limited to
changing game speed and stopping the action.


An example action handler: drink water. this increases the bandmembers water by one every 10 turns until it hits
100, at which point it stops the action:

drink water
------------------------------------------------inc bandmember[a].action_counter[DRINK_WATER]if bandmember[a].action_counter[DRINK_WATER] < 10 returnbandmember[a].action_counter[DRINK_WATER]=0inc bandmember[a].waterif bandmember[a].water>=100 { bandmember[a].water=100 bandmember[a].current_action=DO_NOTHING }


process_input
------------------------------------
processes mouse and keyboard input. input controls can be remapped. raw inputs are mapped to input controls
such as IN_LEFT, or IN_ATTACK. process_input polls the input controls at 15 FPS, and always polls at least
once per render. movement inputs are translated into a move direction of forward, back, left, right, one of
the four diagonal directions, or none. code is then called to move the player in that direction, and play the
correct movement animation. About the only unusual thing about the code is the fact that movement must be
processed before jump, for movement velocties at takeoff to take effect while airborne. Caveman uses realistic
gravity and physics modeling for missiles and falling creatures (including jumping). So just like the real
world, once your feet leave the ground, you can't change your velocity. its all about your initial launch
velocities. Movement must be processed before jump to set those velocities.







run_simulation
-----------------------------------------
this is the main "update" routine. updates are done on an as needed basis. so things that get updated every
frame are updated in do_global_frame2, and things that only need to be updated once per second are updated
in do_global_second2, and so on for global minute, hour, day, and year.void run_simulation2() // the "model stuff" engine{do_global_frame2();if (frame==0) { do_global_second2(); if (second==0) { do_global_minute2(); if (minute==0) { do_global_hour2(); if (hour==0) { do_global_day2(); if (day==0) { do_global_year(); } } } } }}



do_global_frame2
-------------------------------------------------------------------------
this is the main update routine called every frame. it updates: bandmembers (PCs), missiles, animals (NPCs), rafts,
and clouds. Note that attacks are resolved one second after they are initiated, and a hit is only scored if the
weapon hits someone at that point in time. Also note that surprise is modeled in the form of "freezing" for a few
seconds before an entity can move or attack. move_rafts2 models raft movement (duh!) but also moves bandmembers,
NPCs, and dropped objects which are aboard the raft. So you can actually walk around and place object on a raft
while its in motion. model_falling2 handles the physics modeling for falling entities. update_clouds updates the
cloud particle system based on variables from the weather engine.
void do_global_frame2(){int a;BMupdate_all();model_missiles(); // model missile movementmove_animals(); // move animalsif (last_active_animal >= 0) // model animal attacks { for (a=0; a <= last_active_animal; a++) { if (!animal[a].active) continue; if (!animal[a].alive) continue; if (!animal[a].attacking) continue; animal[a].attack_counter++; if (animal[a].attack_counter>=30) { animal[a].attacking=0; animal[a].xr=0.0f; animal[a].attack_counter=0; continue; } if (animal[a].attack_counter==15) new_resolve_animal_attack(a); } }if (last_active_animal >= 0) // model animal suprise { for (a=0; a <= last_active_animal; a++) { if (!animal[a].active) continue; if (!animal[a].alive) continue; if (!animal[a].suprised) continue; animal[a].suprise_counter++; if (animal[a].suprise_counter>60) animal[a].suprised=0; } }move_rafts2();model_falling2();update_clouds();}
do_global_second, minute, day, and year are similar, modeling everything from animals entangled in nets or
bolas getting free, to background radiation (old age).


And that's the basic code structure of the game. pretty straight forward, a fixed time step game loop, with framerate
limiter. The only unusual things are: FPS/RPG mode or SIMs style do action mode, and the render based on
accelerated time.

Part 6:
https://www.gamedev.net/blog/1730/entry-2260310-the-building-of-caveman-part-6-data-structures/

Part 4:
https://www.gamedev.net/blog/1730/entry-2259583-the-building-of-caveman-part-4-the-z-game-library/
Norman Barrows
New Avian AI done

The new Avian AI has been implemented.

There are just a few remaining tasks to complete, and then the AI will be refactored, with the new orders features added.

first off, i still have to hook up the avian ai:


the current code:
you can see how avians were originally implemented as a bunch of special cases throughout the animal AI code.
you can also see where the old land animal AI has been turned off, and the new land animal AI gets called instead.
All three versions of the AI are still in the code: the original AI, the setstate/runstate refactored AI, and the new AI.
Most of the old AI code is turned off via comment blocks. function level linking takes care of the rest.


void move_animals(){int a,t;if (turns_per_render > 128) return;if (last_active_animal < 0) return;for (a=0; a <= last_active_animal; a++) { if (!animal[a].active) continue; if (!animal[a].alive) continue; t=animal[a].type; if (animaltype[t].avian) { if (animal[a].suprised) { move_suprised_avian(a); continue; } else if (animaltype[t].AI==ATTACK_AI) avian_predator_setstate(a); else setstate(a); runstate(a); } else { if (animal[a].suprised) continue; // setstate(a); // runstate(a); B2_run_animal_AI(a); } }}



the new code will look more like:


void move_animals(){int a,t;if (turns_per_render > 128) return;if (last_active_animal < 0) return;for (a=0; a <= last_active_animal; a++) { if (!animal[a].active) continue; if (!animal[a].alive) continue; t=animal[a].type; if (animaltype[t].avian) B2_run_avian_AI(a); else { if (animal[a].suprised) continue; B2_run_animal_AI(a); } }}



I also need to add fatigue modeling to the animal and avian movement code in the new AI.
Here's a snippet of code from the old AI that does fatigue modeling and sets the movement amount all at once.
This will be adapted to create a routine that increases fatigue based on the animal's current movement rate.
This "increase_fatigue" routine will then be called by the land animal and avian move routines.



if (animal[a].fatigue>=100000) { animal[a].fatigue-=7; return; }t=animal[a].type;spd=animal_speed(a);if (running) { if (animal[a].fatigue<100000) { spd*=4.0f; animal[a].fatigue+=64; if (animal[a].fatigue>100000) animal[a].fatigue=100000; } else { spd *= 2.0f; animal[a].fatigue+=4; if (animal[a].fatigue>100000) animal[a].fatigue=100000; } }else { animal[a].fatigue+=2; if (animal[a].fatigue>100000) animal[a].fatigue=100000; }



i also need to add modeling of sneak detection for hired NPC warriors and NPC travelling companions. while they are NPCs,
they are friendly with the player, and the player can give them combat orders. One of the orders they can be given is to
use sneak mode. So i need to make a version of the sneak detection code that works with animals. Cavemen are just another
animal type (species), type 2 to be specific: homo sapien. Hippidion is type 0, smilodon is type 1. pterasaur is type 3,
in anticipation of the bring on the dinos option. Yes, you can punch up a pterasaur encounter and tkae them on with a
spear and throwing rocks! . But for now, they can only be triggered from the playtest menu, and are not in the game's
encounter tables.

The current code only works for bandmembers. its that same old design question we all face when starting a game project: should
i make the player part of the entity list or keep them separate? keeping them in the list means possible code reuse (a good thing).
but usually you need much more data about the player then other entities. that leads to designs where some data is in the entity
list, and the rest is elsewhere. somewhat more complex (a bad thing). a lot depends on whether you can get code savings.
A C-E apprach for components shared by both player and non-player entities seesm like a good idea, but can also be a bit
more complex than a brute force implementation. In my Airships simulator, i model the players ship in great detail, then copy
the pertinant results to entity #0 which is predfeined to be the player's ship. This gives me a simple player airship data
structure, but can still use generic entity code for things like movement, collisions, drawing, etc.

In Caveman, there's isnt a single PC like in most single player games. The human player can control up to 10 PCs. So Caveman
has two entity lists: one for PCs, and one for eveything else. The data for a PC is much more than that for an animal
(everything else). so they are two different types of data strutres stored in two separate lists. Right now, the sneak code work
with a cavemanrec, but not with an animalrec. note that this code is actually in CScript, a c++ macro processor/code generator
i wrote and use in-house. You can freely mix c++ and Cscript code. the first line of BMmodel_sneak_detection() reads:
function void BMmodel_sneak_detection int a
the . at the end is a close squiggly.
This code includes raypick /raycasting style line-of-sight testing.
Note that Caveman differentiates between detected by friendly and detected by hostile. That way you're not detected just becasue
your horse can see you (Oblivion!).


int detection_range(int a) // returns dist at which player a can be seen{int x,z;x=cm[a].mx;z=cm[a].mz;switch(map[x][z].coverage) { case WOODS: case GRASS: case JUNGLE: return(50); }return(300);} // returns 1 if there's a clear line-of-sight from location L to loction L2int clear_LOS(location *L,location *L2){float dx,dy,dz, // displacement & normalized direction vector from p1 to p2 x,y,z, // the point we raycast from p1 to p2 mag; // magnitude of displacement vector from p1 to p2 int mx,mz, // mx,mz of the point we raycast from p1 to p2 a; // loop counter. the number of steps iterated so far in the raycast.location L3; // location of our raycast point for call to terrain_in_way()x = L2->x + (L2->mx - L->mx) * 26400.0f; // convert x,z of p2 to p1 mx,mz relative coordsz = L2->z + (L2->mz - L->mz) * 26400.0f; dx = x - L->x; // calc displacement vector dx,dy,dz between the 2 pointsdy = L2->y - L->y;dz = z - L->z;mag=sqrt(dx*dx+dz*dz); // calc magnitude of the displacement vectormag=sqrt(mag*mag+dy*dy);dx/=mag; // divide displacment vector by mag to get normalized direction vectordy/=mag;dz/=mag;mx=L->mx; // start at 1st pointmz=L->mz;x=L->x; y=L->y;z=L->z;for (a=0; a < (int)mag; a++) // dir vec mag = 1. # steps = mag of displacement vec. { x+=dx; // move the point y+=dy; z+=dz; if (x>26400.0f) // handle map sq edges { x-=26400.0f; mx++; } if (x<0.0f) { x+=26400.0f; mx--; } if (z>26400.0f) { z-=26400.0f; mz++; } if (z<0.0f) { z+=26400.0f; mz--; } L3.mx=mx; // check for terrain collision L3.mz=mz; L3.x=x; L3.y=y; L3.z=z; if (terrain_in_way(&L3)) return(0); if (heightmap(mx,mz,x,z) >= y) return(0); // check for ground collision }return(1); // no collisions, have clear LOS, return 1.} // returns: 0=not detected. 1=detected by some animal. 2=detected by wild or hostile targeting the playerint detection_state(int a) // a is band member #{int b, // animal # dr, // detection rng of bandmember a rh, // rel heading, animal to band member rng, // range from band member to animal result, // return value targeting_player; // booleanfloat x,z;location L,L2;dr=detection_range(a);result=0;for (b=0; b.active) continue; if (! animal.alive) continue; if (animal.location != cm[cm0].location) continue; if (abs(cm[a].mx-animal.mx) > 1) continue; // more than 1 map sq away in x direction if (abs(cm[a].mz-animal.mz) > 1) continue; // more than 1 map sq away in z direction if ( ((animal.state==WILD) || (animal.state==HOSTILE)) && (animal.tgt_is_caveman==1) && (animal.tgt==a)) targeting_player=1; else targeting_player=0; if ( (result==0) || ((result==1) && (targeting_player)) ) { x=cm[a].x+(cm[a].mx-animal.mx)*26400.0f; // calc band member x,z rel to animal's map sq z=cm[a].z+(cm[a].mz-animal.mz)*26400.0f; // calc band member x,z rel to animal's map sq rng=rng2D((int)animal.x,(int)animal.z,(int)x,(int)z); if (rng > animal_cliprng-20) continue; if (rng > dr) continue; rh=relheading((int)animal.x,(int)animal.z,(int)rad2deg(animal.yr),(int)x,(int)z); // normalized, ok. if (abs(rh) > 90) continue; L.mx=animal.mx; L.mz=animal.mz; L.x=animal.x; L.y=animal.y; L.z=animal.z; L2.mx=cm[a].mx; L2.mz=cm[a].mz; L2.x=cm[a].x; L2.y=cm[a].y; L2.z=cm[a].z; if (! clear_LOS(&L,&L2) ) continue; } else continue; switch(result) { case 0: if (targeting_player) return(2); else result=1; break; case 1: return(2); } }return(result);} // returns 1 if band member a is targeted by a hostile caveman or wild animalint bandmember_targeted(int a){int b;for (b=0; b.active) continue; if (! animal.alive) continue; if ((animal.state != HOSTILE) && (animal.state != WILD)) continue; if (! animal.tgt_is_caveman) continue; if (animal.tgt != a) continue; return(1); }return(0);} fn v BMmodel_sneak_detection i aif (a % 15 != frame) return;if (cm[a].sneak_state==0) return;if (cm[a].sneak_state==3) { if (! bandmember_targeted(a)) cm[a].sneak_state=1; }else // states 1 & 2 { switch (detection_state(a)) { case 0: cm[a].sneak_state=1; // sneaking - undetected break; case 1: cm[a].sneak_state=2; // sneaking - detected - non-hostile break; case 2: cm[a].sneak_state=3; // sneaking - detected - hostile break; } }.





another thing left to do is to init the "taking fire" variables for animals when they get hit by a missile.
again, there's only code for bandmembers at the moment. More CScript. this function just sets three variables.
It gets called when a bandmember gets hit by a missile. I need to make a version for animals. IE: replace cm[] with
animal[], then call it from the code that checks missile collisions with animals.


fn v set_BM_taking_fire i cm1= cm[cm1].taking_fire 1= cm[cm1].taking_fire_counter 0= cm[cm1].taking_fire_dir (float)(dice(628)/100.0f).



another thing to do is make an avian version of do_orders, where the new AI follows the player's orders. This
is basically a copy / paste /edit of B2_do_orders to create B2_avian_do_orders. calls to B2_avian_setpitch get
added after calls to turn the animal, and avian versions of attack and move are used.


the last thing left is to add animal[a].diving to the savegame file format. Its used by avian predators to track
their attack state (diving on tgt, or climbing for next pass). the variable has already been added to the
animalrec struct declaration and is used by the code. but the vsae and load code writes individual fields, not
entire structs. so the old savegames will still load, with animal[a].diving taking a default value of zero (false)
as desired. So all i have to do is add one line of code to save the variable, then run the game to convert the
existing savegames to the new format by simply loading and saving each one (there's only one - a long term
playtest game). Then i add one line of code to read the new variable, and i'm done. file format updated, and
savegames converted. If i wanted backward compatability with savegames i didn't convert, i add an extra line of
code to save a junk value before the new data. when i read, i try to tread the junk value. if i get an EOF, its
an old format, and any variables normally read after that point will not be read and simpy keep their default
initial values. if i don't get an eof, there's more data, so i keep reading until the next "EOF test" or i've
read everything. Since changes to the file format are appended at the end of the file, you can read in something
many versions old and get the original data plus defualt values for newver variables. So the basic idea is you
init everything to default values, then read in the savegame values over them. whatever you don't read in,
uses the default values. when you save, you write everyting.
Norman Barrows
New land animal AI implemented



The new land animal AI has been implemented and plugged into the game.




The new land animal AI actually consists of 8 different types of AI:
1. AI for NPC allies of the player (travelling companions, hired warriors, and tamed pets).
2. AI for thieves
3. AI for neutral NPC cavemen
4. AI for animals and hostile cavemen who are defending a location
5. AI for hostile cavemen
6. AI for predators
7. AI for animals that defend their ground
8. AI for animals that maintain their distance






In refactoring the ground animal AI, it has taken a new form.

The old AI was more or less a setstate / runstate type design.

The new AI is more of the form:

[color=#0000ff]if (condition A) handle_condition_A()
else if (condition B) handle_condition_B()
else if (condition C) handle_condition_C()
else if (condition D) handle_condition_D()
etc.[/color]

The routines to handle different conditions turn and move the animal,trigger attacks, and play animations as required.






The conditions are more or less ordered from most to least important to respond to.

For example, all the animal AI code starts out the same:
if fatigued, restelse if rested, stop restingelse if cornered, attackelse if in collision recovery, do collision recoveryelse if taking fire { if have target, attack else flee in random direction }else if halfdead, fleeelse if have target within 20 feet { if target is stronger, flee else attack }







Instead of a single AI_state variable as used in a setstate / runstate design,
the new AI instead uses multiple state variables:

is_resting (boolean)
is_hunting (boolean)
in_collision_recovery (boolean)
orders (a predefined order such as goto location).
has_orders_target (boolean)
graze_state (stand, wander, flock, or migrate)
taking_fire (boolean)

this allows an animal to be in multiple AI states simultaneously, such as hunting, taking fire, in collision recovery, and resting.

IE, i'm on the hunt (targeting animals not bigger than me), but i'm taking fire from an unknown source, so i'm running,
but i've hit an obsticle, so i'm in collision recovery (bang and turn), and while in collision recovery, my fatigue has maxed out,
and i can't take another step, so i have to stop and catch my breath for a moment (rest).





One interesting thing is the fact that the handle_condition code for grazing actually uses a state machine variable (graze_state)
and uses a setstate / runstate type design.




I've been coding game AI on and off for 25 years now, and i keep coming back to expert systems implemented as multilevel decision trees
with multiple state variables, and the odd state machine thrown in at some level or another. Basically, each of the handle_condition
routines uses whatever AI type will work best for its particular task. In the case of graze, this just happens to be a state machine.
Most of the other handle_condition routines are decision trees, or simply code to turn some amount, move some amount, and possibly attack,
based on the condition being handled. At the lowest level, all the higher level AI routines eventually output calls to move, turn, attack,
and play animations as appropriate.




The dreaded avian AI is next! It turns out that AI for an avian predator is quite complex - perhaps amongst the most complex single entity AI I've ever heard of. And its ALMOST right, but not quite there. They still do this circle the target thing from time to time that doesn't seem correct, and i'm not quite sure what they're doing (as far as what their AI state is). Putting a simple trace variable on it will reveal what's going on, I just haven't gotten around to it yet. But implementing and testing the new avian AI should finally fix that odd behavior. I suspect it may have something to do with either resting but not landing first, or trying to fly and turn towards a target who is trying to move and turn towards you, resulting in the two of you moving in a circle, chasing each other.