Luck plays a HUGE role. If the company is doing really well, rather than "limping along," then the environment is motivating in itself. I am ready to bet none of the places you have worked have been doing really well.
When the company is "average" then it is the management team (importantly your direct manager) that hold the keys to you being happy.
The question is, "Would a really good manager stick around at a company that is limping along?"