Randomly Spawning Surface Objects?

I saw some neat code here Mission generation that someone used to randomly spawn some trees on the surface of his world so long as it was above a certain point. Randomly spawning trees across a terrain is something I can do in a heartbeat, but how would one make sure than the base of the trees match up with the bottom of the ground?

The only way I can think of is to assign each of them gravity and “drop” them onto the screen grid, assigning all of them the initial altitude of the highest height on the map. That way each one would drop to its own designated place. That seems very tedious, however, and it seems like it would use a lot of unneeded processing power. My terrain is generated by a heightmap, and so maybe there’s a way to make sure than the trees starting altitude match up with the heightmap altitudes?

Any ideas would be greatly appreciated. I know I didn’t articulate that perfectly, so I can clarify if needed.

Vector3f treeLoc = new Vector3f(0,0,-30);
new Vector2f( treeLoc.x, treeLoc.z ) ) );
This works for random gen terrain, otherwise you don’t need it…

Copied from the book: jmonkeyengine beginners guide. I think this is the site you should use: https://www.packtpub.com/game-development/jmonkeyengine-30-beginners-guide

In addition to the previous answer you can also use raycasting when there are other assets in the level (such as buildings, roads, …)

My old approach was to do raycasting, and then check if the hits object material is the terrain (eg to prevent them from growing ontop of buildings). Also i suggest to drop them a little deeper than the hitpoint and adjust the models for this, so they look better on slopes.

Are there any good bits of code that exemplify the raycasting → check for material method? That sounds like the best idea for what I’m trying to do.

The ray casting is explained here:

the second part then is just a hitgeom.getMaterial();

Awesome! It’s just that second part I was after. Thank you all so much!