Generalized-ray theory for electromagnetic fields in layered media