The origin of discs and spheroids in simulated galaxies